diff --git a/.drone.yml b/.drone.yml index 341f49e4e..d58733504 100644 --- a/.drone.yml +++ b/.drone.yml @@ -23,7 +23,7 @@ steps: - export WORKFLOW_BRANCH_OR_TAG=release-cfw - export FORCE_NO_DIRTY=yes - export FBT_GIT_SUBMODULE_SHALLOW=1 - - rm -rf assets/resources/apps/ + - rm -rf applications/main/clock_app/resources/apps/ - rm -rf build/ - rm -rf dist/ - rm -rf .sconsign.dblite @@ -46,8 +46,8 @@ steps: - export FBT_GIT_SUBMODULE_SHALLOW=1 - wget https://github.com/xMasterX/all-the-plugins/releases/latest/download/all-the-apps-base.tgz - tar zxvf all-the-apps-base.tgz - - cp -R base_pack_build/artifacts-base/* assets/resources/apps/ - - cp -R base_pack_build/apps_data/* assets/resources/apps_data/ + - cp -R base_pack_build/artifacts-base/* applications/main/clock_app/resources/apps/ + - cp -R base_pack_build/apps_data/* applications/main/clock_app/resources/apps_data/ - rm -rf base_pack_build - rm -rf all-the-apps-base.tgz - rm -f build/f7-firmware-C/toolbox/version.* @@ -66,7 +66,7 @@ steps: commands: - wget https://github.com/xMasterX/all-the-plugins/releases/latest/download/all-the-apps-extra.tgz - tar zxvf all-the-apps-extra.tgz - - cp -R extra_pack_build/artifacts-extra/* assets/resources/apps/ + - cp -R extra_pack_build/artifacts-extra/* applications/main/clock_app/resources/apps/ - rm -rf extra_pack_build - export DIST_SUFFIX=${DRONE_TAG}e - export WORKFLOW_BRANCH_OR_TAG=release-cfw @@ -109,7 +109,7 @@ steps: - git checkout -- . - rm -f assets/dolphin/external/manifest.txt - cp .ci_files/anims_ofw.txt assets/dolphin/external/manifest.txt - - rm -rf assets/resources/apps/ + - rm -rf applications/main/clock_app/resources/apps/ - export DIST_SUFFIX=${DRONE_TAG}n - export WORKFLOW_BRANCH_OR_TAG=no-custom-anims - export FORCE_NO_DIRTY=yes @@ -118,8 +118,8 @@ steps: - ./fbt COMPACT=1 DEBUG=0 updater_package - wget https://github.com/xMasterX/all-the-plugins/releases/latest/download/all-the-apps-base.tgz - tar zxvf all-the-apps-base.tgz - - cp -R base_pack_build/artifacts-base/* assets/resources/apps/ - - cp -R base_pack_build/apps_data/* assets/resources/apps_data/ + - cp -R base_pack_build/artifacts-base/* applications/main/clock_app/resources/apps/ + - cp -R base_pack_build/apps_data/* applications/main/clock_app/resources/apps_data/ - rm -rf base_pack_build - rm -rf all-the-apps-base.tgz - rm -f build/f7-firmware-C/toolbox/version.* @@ -397,7 +397,7 @@ steps: - export WORKFLOW_BRANCH_OR_TAG=dev-cfw - export FORCE_NO_DIRTY=yes - export FBT_GIT_SUBMODULE_SHALLOW=1 - - rm -rf assets/resources/apps/ + - rm -rf applications/main/clock_app/resources/apps/ - rm -rf build/ - rm -rf dist/ - rm -rf .sconsign.dblite @@ -421,8 +421,8 @@ steps: - export FBT_GIT_SUBMODULE_SHALLOW=1 - wget https://github.com/xMasterX/all-the-plugins/releases/latest/download/all-the-apps-base.tgz - tar zxvf all-the-apps-base.tgz - - cp -R base_pack_build/artifacts-base/* assets/resources/apps/ - - cp -R base_pack_build/apps_data/* assets/resources/apps_data/ + - cp -R base_pack_build/artifacts-base/* applications/main/clock_app/resources/apps/ + - cp -R base_pack_build/apps_data/* applications/main/clock_app/resources/apps_data/ - rm -rf base_pack_build - rm -rf all-the-apps-base.tgz - rm -f build/f7-firmware-C/toolbox/version.* @@ -441,7 +441,7 @@ steps: commands: - wget https://github.com/xMasterX/all-the-plugins/releases/latest/download/all-the-apps-extra.tgz - tar zxvf all-the-apps-extra.tgz - - cp -R extra_pack_build/artifacts-extra/* assets/resources/apps/ + - cp -R extra_pack_build/artifacts-extra/* applications/main/clock_app/resources/apps/ - rm -rf extra_pack_build - export DIST_SUFFIX=${DRONE_BUILD_NUMBER}e - export WORKFLOW_BRANCH_OR_TAG=dev-cfw diff --git a/.pvsoptions b/.pvsoptions index 2e0b2fb8d..031218092 100644 --- a/.pvsoptions +++ b/.pvsoptions @@ -1 +1 @@ ---ignore-ccache -C gccarm --rules-config .pvsconfig -e lib/cmsis_core -e lib/fatfs -e lib/fnv1a-hash -e lib/FreeRTOS-Kernel -e lib/heatshrink -e lib/libusb_stm32 -e lib/littlefs -e lib/mbedtls -e lib/micro-ecc -e lib/microtar -e lib/mlib -e lib/qrcode -e lib/ST25RFAL002 -e lib/stm32wb_cmsis -e lib/stm32wb_copro -e lib/stm32wb_hal -e lib/u8g2 -e lib/nanopb -e */arm-none-eabi/* +--ignore-ccache -C gccarm --rules-config .pvsconfig -e lib/cmsis_core -e lib/fatfs -e lib/fnv1a-hash -e lib/FreeRTOS-Kernel -e lib/heatshrink -e lib/libusb_stm32 -e lib/littlefs -e lib/mbedtls -e lib/micro-ecc -e lib/microtar -e lib/mlib -e lib/qrcode -e lib/stm32wb_cmsis -e lib/stm32wb_copro -e lib/stm32wb_hal -e lib/u8g2 -e lib/nanopb -e */arm-none-eabi/* diff --git a/SConstruct b/SConstruct index 698ea85ec..248fcf1d1 100644 --- a/SConstruct +++ b/SConstruct @@ -67,22 +67,22 @@ if GetOption("fullenv") or any( # Target for self-update package dist_basic_arguments = [ "--bundlever", - '"${UPDATE_VERSION_STRING}"', + "${UPDATE_VERSION_STRING}", ] dist_radio_arguments = [ "--radio", - '"${ROOT_DIR.abspath}/${COPRO_STACK_BIN_DIR}/${COPRO_STACK_BIN}"', + "${ROOT_DIR.abspath}/${COPRO_STACK_BIN_DIR}/${COPRO_STACK_BIN}", "--radiotype", "${COPRO_STACK_TYPE}", "${COPRO_DISCLAIMER}", "--obdata", - '"${ROOT_DIR.abspath}/${COPRO_OB_DATA}"', + "${ROOT_DIR.abspath}/${COPRO_OB_DATA}", "--stackversion", "${COPRO_CUBE_VERSION}", ] dist_resource_arguments = [ "-r", - '"${ROOT_DIR.abspath}/assets/resources"', + firmware_env.subst("${RESOURCES_ROOT}"), ] dist_splash_arguments = ( [ @@ -95,7 +95,7 @@ if GetOption("fullenv") or any( selfupdate_dist = distenv.DistCommand( "updater_package", - (distenv["DIST_DEPENDS"], firmware_env["FW_RESOURCES"]), + (distenv["DIST_DEPENDS"], firmware_env["FW_RESOURCES_MANIFEST"]), DIST_EXTRA=[ *dist_basic_arguments, *dist_radio_arguments, @@ -128,7 +128,8 @@ if GetOption("fullenv") or any( # Installation over USB & CLI usb_update_package = distenv.AddUsbFlashTarget( - "#build/usbinstall.flag", (firmware_env["FW_RESOURCES"], selfupdate_dist) + "#build/usbinstall.flag", + (firmware_env["FW_RESOURCES_MANIFEST"], selfupdate_dist), ) distenv.Alias("flash_usb_full", usb_update_package) @@ -166,17 +167,25 @@ Depends( list(app_artifact.validator for app_artifact in external_app_list), ) Alias("fap_dist", fap_dist) -# distenv.Default(fap_dist) - -distenv.Depends(firmware_env["FW_RESOURCES"], external_apps_artifacts.resources_dist) # Copy all faps to device fap_deploy = distenv.PhonyTarget( "fap_deploy", - "${PYTHON3} ${FBT_SCRIPT_DIR}/storage.py -p ${FLIP_PORT} send ${SOURCE} /ext/apps", - source=Dir("#/assets/resources/apps"), + [ + [ + "${PYTHON3}", + "${FBT_SCRIPT_DIR}/storage.py", + "-p", + "${FLIP_PORT}", + "send", + "${SOURCE}", + "/ext/apps", + ] + ], + source=firmware_env.Dir(("${RESOURCES_ROOT}/apps")), ) +Depends(fap_deploy, firmware_env["FW_RESOURCES_MANIFEST"]) # Target for bundling core2 package for qFlipper @@ -314,9 +323,7 @@ distenv.PhonyTarget( ) # Start Flipper CLI via PySerial's miniterm -distenv.PhonyTarget( - "cli", "${PYTHON3} ${FBT_SCRIPT_DIR}/serial_cli.py -p ${FLIP_PORT}" -) +distenv.PhonyTarget("cli", "${PYTHON3} ${FBT_SCRIPT_DIR}/serial_cli.py -p ${FLIP_PORT}") # Update WiFi devboard firmware distenv.PhonyTarget("devboard_flash", "${PYTHON3} ${FBT_SCRIPT_DIR}/wifi_board.py") diff --git a/applications/debug/direct_draw/direct_draw.c b/applications/debug/direct_draw/direct_draw.c index 71c65eab1..63e03530a 100644 --- a/applications/debug/direct_draw/direct_draw.c +++ b/applications/debug/direct_draw/direct_draw.c @@ -71,7 +71,7 @@ static void direct_draw_run(DirectDraw* instance) { size_t counter = 0; float fps = 0; - vTaskPrioritySet(furi_thread_get_current_id(), FuriThreadPriorityIdle); + furi_thread_set_current_priority(FuriThreadPriorityIdle); do { size_t elapsed = DWT->CYCCNT - start; diff --git a/applications/debug/rpc_debug_app/rpc_debug_app.c b/applications/debug/rpc_debug_app/rpc_debug_app.c index 314be5e72..2a0756383 100644 --- a/applications/debug/rpc_debug_app/rpc_debug_app.c +++ b/applications/debug/rpc_debug_app/rpc_debug_app.c @@ -21,22 +21,51 @@ static void rpc_debug_app_tick_event_callback(void* context) { scene_manager_handle_tick_event(app->scene_manager); } -static void rpc_debug_app_rpc_command_callback(RpcAppSystemEvent event, void* context) { +static void + rpc_debug_app_format_hex(const uint8_t* data, size_t data_size, char* buf, size_t buf_size) { + if(data == NULL || data_size == 0) { + strncpy(buf, "", buf_size); + return; + } + + const size_t byte_width = 3; + const size_t line_width = 7; + + data_size = MIN(data_size, buf_size / (byte_width + 1)); + + for(size_t i = 0; i < data_size; ++i) { + char* p = buf + (i * byte_width); + char sep = !((i + 1) % line_width) ? '\n' : ' '; + snprintf(p, byte_width + 1, "%02X%c", data[i], sep); + } + + buf[buf_size - 1] = '\0'; +} + +static void rpc_debug_app_rpc_command_callback(const RpcAppSystemEvent* event, void* context) { furi_assert(context); RpcDebugApp* app = context; furi_assert(app->rpc); - if(event == RpcAppEventSessionClose) { + if(event->type == RpcAppEventTypeSessionClose) { scene_manager_stop(app->scene_manager); view_dispatcher_stop(app->view_dispatcher); rpc_system_app_set_callback(app->rpc, NULL, NULL); app->rpc = NULL; - } else if(event == RpcAppEventAppExit) { + } else if(event->type == RpcAppEventTypeAppExit) { scene_manager_stop(app->scene_manager); view_dispatcher_stop(app->view_dispatcher); - rpc_system_app_confirm(app->rpc, RpcAppEventAppExit, true); + rpc_system_app_confirm(app->rpc, true); + } else if(event->type == RpcAppEventTypeDataExchange) { + furi_assert(event->data.type == RpcAppSystemEventDataTypeBytes); + + rpc_debug_app_format_hex( + event->data.bytes.ptr, event->data.bytes.size, app->text_store, TEXT_STORE_SIZE); + + view_dispatcher_send_custom_event( + app->view_dispatcher, RpcDebugAppCustomEventRpcDataExchange); } else { - rpc_system_app_confirm(app->rpc, event, false); + rpc_system_app_confirm(app->rpc, false); } } diff --git a/applications/debug/rpc_debug_app/scenes/rpc_debug_app_scene_receive_data_exchange.c b/applications/debug/rpc_debug_app/scenes/rpc_debug_app_scene_receive_data_exchange.c index 98bafff8a..10d5e36f6 100644 --- a/applications/debug/rpc_debug_app/scenes/rpc_debug_app_scene_receive_data_exchange.c +++ b/applications/debug/rpc_debug_app/scenes/rpc_debug_app_scene_receive_data_exchange.c @@ -1,40 +1,5 @@ #include "../rpc_debug_app.h" -static void rpc_debug_app_scene_start_format_hex( - const uint8_t* data, - size_t data_size, - char* buf, - size_t buf_size) { - furi_assert(data); - furi_assert(buf); - - const size_t byte_width = 3; - const size_t line_width = 7; - - data_size = MIN(data_size, buf_size / (byte_width + 1)); - - for(size_t i = 0; i < data_size; ++i) { - char* p = buf + (i * byte_width); - char sep = !((i + 1) % line_width) ? '\n' : ' '; - snprintf(p, byte_width + 1, "%02X%c", data[i], sep); - } - - buf[buf_size - 1] = '\0'; -} - -static void rpc_debug_app_scene_receive_data_exchange_callback( - const uint8_t* data, - size_t data_size, - void* context) { - RpcDebugApp* app = context; - if(data) { - rpc_debug_app_scene_start_format_hex(data, data_size, app->text_store, TEXT_STORE_SIZE); - } else { - strncpy(app->text_store, "", TEXT_STORE_SIZE); - } - view_dispatcher_send_custom_event(app->view_dispatcher, RpcDebugAppCustomEventRpcDataExchange); -} - void rpc_debug_app_scene_receive_data_exchange_on_enter(void* context) { RpcDebugApp* app = context; strncpy(app->text_store, "Received data will appear here...", TEXT_STORE_SIZE); @@ -42,8 +7,6 @@ void rpc_debug_app_scene_receive_data_exchange_on_enter(void* context) { text_box_set_text(app->text_box, app->text_store); text_box_set_font(app->text_box, TextBoxFontHex); - rpc_system_app_set_data_exchange_callback( - app->rpc, rpc_debug_app_scene_receive_data_exchange_callback, app); view_dispatcher_switch_to_view(app->view_dispatcher, RpcDebugAppViewTextBox); } @@ -53,6 +16,7 @@ bool rpc_debug_app_scene_receive_data_exchange_on_event(void* context, SceneMana if(event.type == SceneManagerEventTypeCustom) { if(event.event == RpcDebugAppCustomEventRpcDataExchange) { + rpc_system_app_confirm(app->rpc, true); notification_message(app->notifications, &sequence_blink_cyan_100); notification_message(app->notifications, &sequence_display_backlight_on); text_box_set_text(app->text_box, app->text_store); @@ -66,5 +30,4 @@ bool rpc_debug_app_scene_receive_data_exchange_on_event(void* context, SceneMana void rpc_debug_app_scene_receive_data_exchange_on_exit(void* context) { RpcDebugApp* app = context; text_box_reset(app->text_box); - rpc_system_app_set_data_exchange_callback(app->rpc, NULL, NULL); } diff --git a/applications/debug/unit_tests/application.fam b/applications/debug/unit_tests/application.fam index ad9a278f3..aa25dab27 100644 --- a/applications/debug/unit_tests/application.fam +++ b/applications/debug/unit_tests/application.fam @@ -5,6 +5,7 @@ App( cdefines=["APP_UNIT_TESTS"], requires=["system_settings"], provides=["delay_test"], + resources="resources", order=100, ) diff --git a/applications/debug/unit_tests/bt/bt_test.c b/applications/debug/unit_tests/bt/bt_test.c index 2cbfd684a..32cf6533f 100644 --- a/applications/debug/unit_tests/bt/bt_test.c +++ b/applications/debug/unit_tests/bt/bt_test.c @@ -28,7 +28,7 @@ void bt_test_alloc() { } void bt_test_free() { - furi_assert(bt_test); + furi_check(bt_test); free(bt_test->nvm_ram_buff_ref); free(bt_test->nvm_ram_buff_dut); bt_keys_storage_free(bt_test->bt_keys_storage); @@ -89,7 +89,7 @@ static void bt_test_keys_remove_test_file() { } MU_TEST(bt_test_keys_storage_serial_profile) { - furi_assert(bt_test); + furi_check(bt_test); bt_test_keys_remove_test_file(); bt_test_keys_storage_profile(); diff --git a/applications/debug/unit_tests/infrared/infrared_test.c b/applications/debug/unit_tests/infrared/infrared_test.c index b2acad470..294c2da9a 100644 --- a/applications/debug/unit_tests/infrared/infrared_test.c +++ b/applications/debug/unit_tests/infrared/infrared_test.c @@ -27,7 +27,7 @@ static void infrared_test_alloc() { } static void infrared_test_free() { - furi_assert(test); + furi_check(test); infrared_free_decoder(test->decoder_handler); infrared_free_encoder(test->encoder_handler); flipper_format_free(test->ff); diff --git a/applications/debug/unit_tests/manifest/manifest.c b/applications/debug/unit_tests/manifest/manifest.c index 0b24ad1ed..19370b0e1 100644 --- a/applications/debug/unit_tests/manifest/manifest.c +++ b/applications/debug/unit_tests/manifest/manifest.c @@ -22,7 +22,7 @@ MU_TEST(manifest_iteration_test) { ResourceManifestReader* manifest_reader = resource_manifest_reader_alloc(storage); do { // Open manifest file - if(!resource_manifest_reader_open(manifest_reader, EXT_PATH("unit_tests/Manifest"))) { + if(!resource_manifest_reader_open(manifest_reader, EXT_PATH("unit_tests/Manifest_test"))) { result = false; break; } diff --git a/applications/debug/unit_tests/nfc/nfc_test.c b/applications/debug/unit_tests/nfc/nfc_test.c index bc2f7887b..2d647f8ef 100644 --- a/applications/debug/unit_tests/nfc/nfc_test.c +++ b/applications/debug/unit_tests/nfc/nfc_test.c @@ -1,570 +1,536 @@ #include #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include #include "../minunit.h" #define TAG "NfcTest" -#define NFC_TEST_RESOURCES_DIR EXT_PATH("unit_tests/nfc/") -#define NFC_TEST_SIGNAL_SHORT_FILE "nfc_nfca_signal_short.nfc" -#define NFC_TEST_SIGNAL_LONG_FILE "nfc_nfca_signal_long.nfc" -#define NFC_TEST_DICT_PATH EXT_PATH("unit_tests/mf_classic_dict.nfc") -#define NFC_TEST_NFC_DEV_PATH EXT_PATH("unit_tests/nfc/nfc_dev_test.nfc") - -static const char* nfc_test_file_type = "Flipper NFC test"; -static const uint32_t nfc_test_file_version = 1; - -#define NFC_TEST_DATA_MAX_LEN 18 -#define NFC_TETS_TIMINGS_MAX_LEN 1350 - -// Maximum allowed time for buffer preparation to fit 500us nt message timeout -#define NFC_TEST_4_BYTE_BUILD_BUFFER_TIM_MAX (150) -#define NFC_TEST_16_BYTE_BUILD_BUFFER_TIM_MAX (640) -#define NFC_TEST_4_BYTE_BUILD_SIGNAL_TIM_MAX (110) -#define NFC_TEST_16_BYTE_BUILD_SIGNAL_TIM_MAX (440) +#define NFC_TEST_NFC_DEV_PATH EXT_PATH("unit_tests/nfc/nfc_device_test.nfc") +#define NFC_APP_MF_CLASSIC_DICT_UNIT_TEST_PATH EXT_PATH("unit_tests/mf_dict.nfc") typedef struct { Storage* storage; - NfcaSignal* signal; - uint32_t test_data_len; - uint8_t test_data[NFC_TEST_DATA_MAX_LEN]; - uint32_t test_timings_len; - uint32_t test_timings[NFC_TETS_TIMINGS_MAX_LEN]; } NfcTest; static NfcTest* nfc_test = NULL; static void nfc_test_alloc() { nfc_test = malloc(sizeof(NfcTest)); - nfc_test->signal = nfca_signal_alloc(); nfc_test->storage = furi_record_open(RECORD_STORAGE); } static void nfc_test_free() { - furi_assert(nfc_test); + furi_check(nfc_test); furi_record_close(RECORD_STORAGE); - nfca_signal_free(nfc_test->signal); free(nfc_test); nfc_test = NULL; } -static bool nfc_test_read_signal_from_file(const char* file_name) { - bool success = false; +static void nfc_test_save_and_load(NfcDevice* nfc_device_ref) { + NfcDevice* nfc_device_dut = nfc_device_alloc(); - FlipperFormat* file = flipper_format_file_alloc(nfc_test->storage); - FuriString* file_type; - file_type = furi_string_alloc(); - uint32_t file_version = 0; + mu_assert( + nfc_device_save(nfc_device_ref, NFC_TEST_NFC_DEV_PATH), "nfc_device_save() failed\r\n"); - do { - if(!flipper_format_file_open_existing(file, file_name)) break; - if(!flipper_format_read_header(file, file_type, &file_version)) break; - if(furi_string_cmp_str(file_type, nfc_test_file_type) || - file_version != nfc_test_file_version) - break; - if(!flipper_format_read_uint32(file, "Data length", &nfc_test->test_data_len, 1)) break; - if(nfc_test->test_data_len > NFC_TEST_DATA_MAX_LEN) break; - if(!flipper_format_read_hex( - file, "Plain data", nfc_test->test_data, nfc_test->test_data_len)) - break; - if(!flipper_format_read_uint32(file, "Timings length", &nfc_test->test_timings_len, 1)) - break; - if(nfc_test->test_timings_len > NFC_TETS_TIMINGS_MAX_LEN) break; - if(!flipper_format_read_uint32( - file, "Timings", nfc_test->test_timings, nfc_test->test_timings_len)) - break; - success = true; - } while(false); + mu_assert( + nfc_device_load(nfc_device_dut, NFC_TEST_NFC_DEV_PATH), "nfc_device_load() failed\r\n"); - furi_string_free(file_type); - flipper_format_free(file); + mu_assert( + nfc_device_is_equal(nfc_device_ref, nfc_device_dut), + "nfc_device_data_dut != nfc_device_data_ref\r\n"); - return success; + mu_assert( + storage_simply_remove(nfc_test->storage, NFC_TEST_NFC_DEV_PATH), + "storage_simply_remove() failed\r\n"); + + nfc_device_free(nfc_device_dut); } -static bool nfc_test_digital_signal_test_encode( - const char* file_name, - uint32_t build_signal_max_time_us, - uint32_t build_buffer_max_time_us, - uint32_t timing_tolerance, - uint32_t timings_sum_tolerance) { - furi_assert(nfc_test); +static void iso14443_3a_file_test(uint8_t uid_len) { + NfcDevice* nfc_device = nfc_device_alloc(); - bool success = false; - uint32_t dut_timings_sum = 0; - uint32_t ref_timings_sum = 0; - uint8_t parity[10] = {}; + Iso14443_3aData* data = iso14443_3a_alloc(); + data->uid_len = uid_len; + furi_hal_random_fill_buf(data->uid, uid_len); + furi_hal_random_fill_buf(data->atqa, sizeof(data->atqa)); + furi_hal_random_fill_buf(&data->sak, 1); - do { - // Read test data - if(!nfc_test_read_signal_from_file(file_name)) { - FURI_LOG_E(TAG, "Failed to read signal from file"); - break; - } + nfc_device_set_data(nfc_device, NfcProtocolIso14443_3a, data); + nfc_test_save_and_load(nfc_device); - // Encode signal - FURI_CRITICAL_ENTER(); - uint32_t time_start = DWT->CYCCNT; - - nfca_signal_encode( - nfc_test->signal, nfc_test->test_data, nfc_test->test_data_len * 8, parity); - - uint32_t time_signal = - (DWT->CYCCNT - time_start) / furi_hal_cortex_instructions_per_microsecond(); - - time_start = DWT->CYCCNT; - - digital_signal_prepare_arr(nfc_test->signal->tx_signal); - - uint32_t time_buffer = - (DWT->CYCCNT - time_start) / furi_hal_cortex_instructions_per_microsecond(); - FURI_CRITICAL_EXIT(); - - // Check timings - if(time_signal > build_signal_max_time_us) { - FURI_LOG_E( - TAG, - "Build signal time: %ld us while accepted value: %ld us", - time_signal, - build_signal_max_time_us); - break; - } - if(time_buffer > build_buffer_max_time_us) { - FURI_LOG_E( - TAG, - "Build buffer time: %ld us while accepted value: %ld us", - time_buffer, - build_buffer_max_time_us); - break; - } - - // Check data - if(nfc_test->signal->tx_signal->edge_cnt != nfc_test->test_timings_len) { - FURI_LOG_E(TAG, "Not equal timings buffers length"); - break; - } - - uint32_t timings_diff = 0; - uint32_t* ref = nfc_test->test_timings; - uint32_t* dut = nfc_test->signal->tx_signal->reload_reg_buff; - bool timing_check_success = true; - for(size_t i = 0; i < nfc_test->test_timings_len; i++) { - timings_diff = dut[i] > ref[i] ? dut[i] - ref[i] : ref[i] - dut[i]; - dut_timings_sum += dut[i]; - ref_timings_sum += ref[i]; - if(timings_diff > timing_tolerance) { - FURI_LOG_E( - TAG, "Too big difference in %d timings. Ref: %ld, DUT: %ld", i, ref[i], dut[i]); - timing_check_success = false; - break; - } - } - if(!timing_check_success) break; - uint32_t sum_diff = dut_timings_sum > ref_timings_sum ? dut_timings_sum - ref_timings_sum : - ref_timings_sum - dut_timings_sum; - if(sum_diff > timings_sum_tolerance) { - FURI_LOG_E( - TAG, - "Too big difference in timings sum. Ref: %ld, DUT: %ld", - ref_timings_sum, - dut_timings_sum); - break; - } - - FURI_LOG_I( - TAG, - "Build signal time: %ld us. Acceptable time: %ld us", - time_signal, - build_signal_max_time_us); - FURI_LOG_I( - TAG, - "Build buffer time: %ld us. Acceptable time: %ld us", - time_buffer, - build_buffer_max_time_us); - FURI_LOG_I( - TAG, - "Timings sum difference: %ld [1/64MHZ]. Acceptable difference: %ld [1/64MHz]", - sum_diff, - timings_sum_tolerance); - success = true; - } while(false); - - return success; + iso14443_3a_free(data); + nfc_device_free(nfc_device); } -MU_TEST(nfc_digital_signal_test) { - mu_assert( - nfc_test_digital_signal_test_encode( - NFC_TEST_RESOURCES_DIR NFC_TEST_SIGNAL_SHORT_FILE, - NFC_TEST_4_BYTE_BUILD_SIGNAL_TIM_MAX, - NFC_TEST_4_BYTE_BUILD_BUFFER_TIM_MAX, - 1, - 37), - "NFC short digital signal test failed\r\n"); - mu_assert( - nfc_test_digital_signal_test_encode( - NFC_TEST_RESOURCES_DIR NFC_TEST_SIGNAL_LONG_FILE, - NFC_TEST_16_BYTE_BUILD_SIGNAL_TIM_MAX, - NFC_TEST_16_BYTE_BUILD_BUFFER_TIM_MAX, - 1, - 37), - "NFC long digital signal test failed\r\n"); +static void nfc_file_test_with_generator(NfcDataGeneratorType type) { + NfcDevice* nfc_device_ref = nfc_device_alloc(); + + nfc_data_generator_fill_data(type, nfc_device_ref); + nfc_test_save_and_load(nfc_device_ref); + + nfc_device_free(nfc_device_ref); } -MU_TEST(mf_classic_dict_test) { - MfClassicDict* instance = NULL; - uint64_t key = 0; - FuriString* temp_str; - temp_str = furi_string_alloc(); - - instance = mf_classic_dict_alloc(MfClassicDictTypeUnitTest); - mu_assert(instance != NULL, "mf_classic_dict_alloc\r\n"); - - mu_assert( - mf_classic_dict_get_total_keys(instance) == 0, - "mf_classic_dict_get_total_keys == 0 assert failed\r\n"); - - furi_string_set(temp_str, "2196FAD8115B"); - mu_assert( - mf_classic_dict_add_key_str(instance, temp_str), - "mf_classic_dict_add_key == true assert failed\r\n"); - - mu_assert( - mf_classic_dict_get_total_keys(instance) == 1, - "mf_classic_dict_get_total_keys == 1 assert failed\r\n"); - - mu_assert(mf_classic_dict_rewind(instance), "mf_classic_dict_rewind == 1 assert failed\r\n"); - - mu_assert( - mf_classic_dict_get_key_at_index_str(instance, temp_str, 0), - "mf_classic_dict_get_key_at_index_str == true assert failed\r\n"); - mu_assert( - furi_string_cmp(temp_str, "2196FAD8115B") == 0, - "string_cmp(temp_str, \"2196FAD8115B\") == 0 assert failed\r\n"); - - mu_assert(mf_classic_dict_rewind(instance), "mf_classic_dict_rewind == 1 assert failed\r\n"); - - mu_assert( - mf_classic_dict_get_key_at_index(instance, &key, 0), - "mf_classic_dict_get_key_at_index == true assert failed\r\n"); - mu_assert(key == 0x2196FAD8115B, "key == 0x2196FAD8115B assert failed\r\n"); - - mu_assert(mf_classic_dict_rewind(instance), "mf_classic_dict_rewind == 1 assert failed\r\n"); - - mu_assert( - mf_classic_dict_delete_index(instance, 0), - "mf_classic_dict_delete_index == true assert failed\r\n"); - - mf_classic_dict_free(instance); - furi_string_free(temp_str); +MU_TEST(iso14443_3a_4b_file_test) { + iso14443_3a_file_test(4); } -MU_TEST(mf_classic_dict_load_test) { - Storage* storage = furi_record_open(RECORD_STORAGE); - mu_assert(storage != NULL, "storage != NULL assert failed\r\n"); - - // Delete unit test dict file if exists - if(storage_file_exists(storage, NFC_TEST_DICT_PATH)) { - mu_assert( - storage_simply_remove(storage, NFC_TEST_DICT_PATH), - "remove == true assert failed\r\n"); - } - - // Create unit test dict file - Stream* file_stream = file_stream_alloc(storage); - mu_assert(file_stream != NULL, "file_stream != NULL assert failed\r\n"); - mu_assert( - file_stream_open(file_stream, NFC_TEST_DICT_PATH, FSAM_WRITE, FSOM_OPEN_ALWAYS), - "file_stream_open == true assert failed\r\n"); - - // Write unit test dict file - char key_str[] = "a0a1a2a3a4a5"; - mu_assert( - stream_write_cstring(file_stream, key_str) == strlen(key_str), - "write == true assert failed\r\n"); - // Close unit test dict file - mu_assert(file_stream_close(file_stream), "file_stream_close == true assert failed\r\n"); - - // Load unit test dict file - MfClassicDict* instance = NULL; - instance = mf_classic_dict_alloc(MfClassicDictTypeUnitTest); - mu_assert(instance != NULL, "mf_classic_dict_alloc\r\n"); - uint32_t total_keys = mf_classic_dict_get_total_keys(instance); - mu_assert(total_keys == 1, "total_keys == 1 assert failed\r\n"); - - // Read key - uint64_t key_ref = 0xa0a1a2a3a4a5; - uint64_t key_dut = 0; - FuriString* temp_str = furi_string_alloc(); - mu_assert( - mf_classic_dict_get_next_key_str(instance, temp_str), - "get_next_key_str == true assert failed\r\n"); - mu_assert(furi_string_cmp_str(temp_str, key_str) == 0, "invalid key loaded\r\n"); - mu_assert(mf_classic_dict_rewind(instance), "mf_classic_dict_rewind == 1 assert failed\r\n"); - mu_assert( - mf_classic_dict_get_next_key(instance, &key_dut), - "get_next_key == true assert failed\r\n"); - mu_assert(key_dut == key_ref, "invalid key loaded\r\n"); - furi_string_free(temp_str); - mf_classic_dict_free(instance); - - // Check that MfClassicDict added new line to the end of the file - mu_assert( - file_stream_open(file_stream, NFC_TEST_DICT_PATH, FSAM_READ, FSOM_OPEN_EXISTING), - "file_stream_open == true assert failed\r\n"); - mu_assert(stream_seek(file_stream, -1, StreamOffsetFromEnd), "seek == true assert failed\r\n"); - uint8_t last_char = 0; - mu_assert(stream_read(file_stream, &last_char, 1) == 1, "read == true assert failed\r\n"); - mu_assert(last_char == '\n', "last_char == '\\n' assert failed\r\n"); - mu_assert(file_stream_close(file_stream), "file_stream_close == true assert failed\r\n"); - - // Delete unit test dict file - mu_assert( - storage_simply_remove(storage, NFC_TEST_DICT_PATH), "remove == true assert failed\r\n"); - stream_free(file_stream); - furi_record_close(RECORD_STORAGE); +MU_TEST(iso14443_3a_7b_file_test) { + iso14443_3a_file_test(7); } -MU_TEST(nfca_file_test) { - NfcDevice* nfc = nfc_device_alloc(); - mu_assert(nfc != NULL, "nfc_device_data != NULL assert failed\r\n"); - nfc->format = NfcDeviceSaveFormatUid; - - // Fill the UID, sak, ATQA and type - uint8_t uid[7] = {0x04, 0x01, 0x23, 0x45, 0x67, 0x89, 0x00}; - memcpy(nfc->dev_data.nfc_data.uid, uid, 7); - nfc->dev_data.nfc_data.uid_len = 7; - - nfc->dev_data.nfc_data.sak = 0x08; - nfc->dev_data.nfc_data.atqa[0] = 0x00; - nfc->dev_data.nfc_data.atqa[1] = 0x04; - nfc->dev_data.nfc_data.type = FuriHalNfcTypeA; - - // Save the NFC device data to the file - mu_assert( - nfc_device_save(nfc, NFC_TEST_NFC_DEV_PATH), "nfc_device_save == true assert failed\r\n"); - nfc_device_free(nfc); - - // Load the NFC device data from the file - NfcDevice* nfc_validate = nfc_device_alloc(); - mu_assert( - nfc_device_load(nfc_validate, NFC_TEST_NFC_DEV_PATH, true), - "nfc_device_load == true assert failed\r\n"); - - // Check the UID, sak, ATQA and type - mu_assert(memcmp(nfc_validate->dev_data.nfc_data.uid, uid, 7) == 0, "uid assert failed\r\n"); - mu_assert(nfc_validate->dev_data.nfc_data.sak == 0x08, "sak == 0x08 assert failed\r\n"); - mu_assert( - nfc_validate->dev_data.nfc_data.atqa[0] == 0x00, "atqa[0] == 0x00 assert failed\r\n"); - mu_assert( - nfc_validate->dev_data.nfc_data.atqa[1] == 0x04, "atqa[1] == 0x04 assert failed\r\n"); - mu_assert( - nfc_validate->dev_data.nfc_data.type == FuriHalNfcTypeA, - "type == FuriHalNfcTypeA assert failed\r\n"); - nfc_device_free(nfc_validate); +MU_TEST(mf_ultralight_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeMfUltralight); } -static void mf_classic_generator_test(uint8_t uid_len, MfClassicType type) { - NfcDevice* nfc_dev = nfc_device_alloc(); - mu_assert(nfc_dev != NULL, "nfc_device_data != NULL assert failed\r\n"); - nfc_dev->format = NfcDeviceSaveFormatMifareClassic; - - // Create a test file - nfc_generate_mf_classic(&nfc_dev->dev_data, uid_len, type); - - // Get the uid from generated MFC - uint8_t uid[7] = {0}; - memcpy(uid, nfc_dev->dev_data.nfc_data.uid, uid_len); - uint8_t sak = nfc_dev->dev_data.nfc_data.sak; - uint8_t atqa[2] = {}; - memcpy(atqa, nfc_dev->dev_data.nfc_data.atqa, 2); - - MfClassicData* mf_data = &nfc_dev->dev_data.mf_classic_data; - // Check the manufacturer block (should be uid[uid_len] + BCC (for 4byte only) + SAK + ATQA0 + ATQA1 + 0xFF[rest]) - uint8_t manufacturer_block[16] = {0}; - memcpy(manufacturer_block, nfc_dev->dev_data.mf_classic_data.block[0].value, 16); - mu_assert( - memcmp(manufacturer_block, uid, uid_len) == 0, - "manufacturer_block uid doesn't match the file\r\n"); - - uint8_t position = 0; - if(uid_len == 4) { - position = uid_len; - - uint8_t bcc = 0; - - for(int i = 0; i < uid_len; i++) { - bcc ^= uid[i]; - } - - mu_assert(manufacturer_block[position] == bcc, "manufacturer_block bcc assert failed\r\n"); - } else { - position = uid_len - 1; - } - - mu_assert(manufacturer_block[position + 1] == sak, "manufacturer_block sak assert failed\r\n"); - - mu_assert( - manufacturer_block[position + 2] == atqa[0], "manufacturer_block atqa0 assert failed\r\n"); - - mu_assert( - manufacturer_block[position + 3] == atqa[1], "manufacturer_block atqa1 assert failed\r\n"); - - for(uint8_t i = position + 4; i < 16; i++) { - mu_assert( - manufacturer_block[i] == 0xFF, "manufacturer_block[i] == 0xFF assert failed\r\n"); - } - - // Reference sector trailers (should be 0xFF[6] + 0xFF + 0x07 + 0x80 + 0x69 + 0xFF[6]) - uint8_t sector_trailer[16] = { - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0x07, - 0x80, - 0x69, - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0xFF, - 0xFF}; - // Reference block data - uint8_t block_data[16] = {}; - memset(block_data, 0xff, sizeof(block_data)); - uint16_t total_blocks = mf_classic_get_total_block_num(type); - for(size_t i = 1; i < total_blocks; i++) { - if(mf_classic_is_sector_trailer(i)) { - mu_assert( - memcmp(mf_data->block[i].value, sector_trailer, 16) == 0, - "Failed sector trailer compare"); - } else { - mu_assert(memcmp(mf_data->block[i].value, block_data, 16) == 0, "Failed data compare"); - } - } - // Save the NFC device data to the file - mu_assert( - nfc_device_save(nfc_dev, NFC_TEST_NFC_DEV_PATH), - "nfc_device_save == true assert failed\r\n"); - // Verify that key cache is saved - FuriString* key_cache_name = furi_string_alloc(); - furi_string_set_str(key_cache_name, "/ext/nfc/.cache/"); - for(size_t i = 0; i < uid_len; i++) { - furi_string_cat_printf(key_cache_name, "%02X", uid[i]); - } - furi_string_cat_printf(key_cache_name, ".keys"); - mu_assert( - storage_common_stat(nfc_dev->storage, furi_string_get_cstr(key_cache_name), NULL) == - FSE_OK, - "Key cache file save failed"); - nfc_device_free(nfc_dev); - - // Load the NFC device data from the file - NfcDevice* nfc_validate = nfc_device_alloc(); - mu_assert(nfc_validate, "Nfc device alloc assert"); - mu_assert( - nfc_device_load(nfc_validate, NFC_TEST_NFC_DEV_PATH, false), - "nfc_device_load == true assert failed\r\n"); - - // Check the UID, sak, ATQA and type - mu_assert( - memcmp(nfc_validate->dev_data.nfc_data.uid, uid, uid_len) == 0, - "uid compare assert failed\r\n"); - mu_assert(nfc_validate->dev_data.nfc_data.sak == sak, "sak compare assert failed\r\n"); - mu_assert( - memcmp(nfc_validate->dev_data.nfc_data.atqa, atqa, 2) == 0, - "atqa compare assert failed\r\n"); - mu_assert( - nfc_validate->dev_data.nfc_data.type == FuriHalNfcTypeA, - "type == FuriHalNfcTypeA assert failed\r\n"); - - // Check the manufacturer block - mu_assert( - memcmp(nfc_validate->dev_data.mf_classic_data.block[0].value, manufacturer_block, 16) == 0, - "manufacturer_block assert failed\r\n"); - // Check other blocks - for(size_t i = 1; i < total_blocks; i++) { - if(mf_classic_is_sector_trailer(i)) { - mu_assert( - memcmp(mf_data->block[i].value, sector_trailer, 16) == 0, - "Failed sector trailer compare"); - } else { - mu_assert(memcmp(mf_data->block[i].value, block_data, 16) == 0, "Failed data compare"); - } - } - nfc_device_free(nfc_validate); - - // Check saved key cache - NfcDevice* nfc_keys = nfc_device_alloc(); - mu_assert(nfc_validate, "Nfc device alloc assert"); - nfc_keys->dev_data.nfc_data.uid_len = uid_len; - memcpy(nfc_keys->dev_data.nfc_data.uid, uid, uid_len); - mu_assert(nfc_device_load_key_cache(nfc_keys), "Failed to load key cache"); - uint8_t total_sec = mf_classic_get_total_sectors_num(type); - uint8_t default_key[6] = {}; - memset(default_key, 0xff, 6); - for(size_t i = 0; i < total_sec; i++) { - MfClassicSectorTrailer* sec_tr = - mf_classic_get_sector_trailer_by_sector(&nfc_keys->dev_data.mf_classic_data, i); - mu_assert(memcmp(sec_tr->key_a, default_key, 6) == 0, "Failed key compare"); - mu_assert(memcmp(sec_tr->key_b, default_key, 6) == 0, "Failed key compare"); - } - - // Delete key cache file - mu_assert( - storage_common_remove(nfc_keys->storage, furi_string_get_cstr(key_cache_name)) == FSE_OK, - "Failed to remove key cache file"); - furi_string_free(key_cache_name); - nfc_device_free(nfc_keys); +MU_TEST(mf_ultralight_ev1_11_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeMfUltralightEV1_11); } -MU_TEST(mf_mini_file_test) { - mf_classic_generator_test(4, MfClassicTypeMini); +MU_TEST(mf_ultralight_ev1_h11_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeMfUltralightEV1_H11); +} + +MU_TEST(mf_ultralight_ev1_21_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeMfUltralightEV1_21); +} + +MU_TEST(mf_ultralight_ev1_h21_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeMfUltralightEV1_H21); +} + +MU_TEST(mf_ultralight_ntag_203_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeNTAG203); +} + +MU_TEST(mf_ultralight_ntag_213_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeNTAG213); +} + +MU_TEST(mf_ultralight_ntag_215_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeNTAG215); +} + +MU_TEST(mf_ultralight_ntag_216_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeNTAG216); +} + +MU_TEST(mf_ultralight_ntag_i2c_1k_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeNTAGI2C1k); +} + +MU_TEST(mf_ultralight_ntag_i2c_2k_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeNTAGI2C2k); +} + +MU_TEST(mf_ultralight_ntag_i2c_plus_1k_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeNTAGI2CPlus1k); +} + +MU_TEST(mf_ultralight_ntag_i2c_plus_2k_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeNTAGI2CPlus2k); +} + +MU_TEST(mf_classic_mini_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeMfClassicMini); } MU_TEST(mf_classic_1k_4b_file_test) { - mf_classic_generator_test(4, MfClassicType1k); -} - -MU_TEST(mf_classic_4k_4b_file_test) { - mf_classic_generator_test(4, MfClassicType4k); + nfc_file_test_with_generator(NfcDataGeneratorTypeMfClassic1k_4b); } MU_TEST(mf_classic_1k_7b_file_test) { - mf_classic_generator_test(7, MfClassicType1k); + nfc_file_test_with_generator(NfcDataGeneratorTypeMfClassic1k_7b); +} + +MU_TEST(mf_classic_4k_4b_file_test) { + nfc_file_test_with_generator(NfcDataGeneratorTypeMfClassic4k_4b); } MU_TEST(mf_classic_4k_7b_file_test) { - mf_classic_generator_test(7, MfClassicType4k); + nfc_file_test_with_generator(NfcDataGeneratorTypeMfClassic4k_7b); +} + +MU_TEST(iso14443_3a_reader) { + Nfc* poller = nfc_alloc(); + Nfc* listener = nfc_alloc(); + + Iso14443_3aData iso14443_3a_listener_data = { + .uid_len = 7, + .uid = {0x04, 0x51, 0x5C, 0xFA, 0x6F, 0x73, 0x81}, + .atqa = {0x44, 0x00}, + .sak = 0x00, + }; + NfcListener* iso3_listener = + nfc_listener_alloc(listener, NfcProtocolIso14443_3a, &iso14443_3a_listener_data); + nfc_listener_start(iso3_listener, NULL, NULL); + + Iso14443_3aData iso14443_3a_poller_data = {}; + mu_assert( + iso14443_3a_poller_read(poller, &iso14443_3a_poller_data) == Iso14443_3aErrorNone, + "iso14443_3a_poller_read() failed"); + + nfc_listener_stop(iso3_listener); + mu_assert( + iso14443_3a_is_equal(&iso14443_3a_poller_data, &iso14443_3a_listener_data), + "Data not matches"); + + nfc_listener_free(iso3_listener); + nfc_free(listener); + nfc_free(poller); +} + +static void mf_ultralight_reader_test(const char* path) { + FURI_LOG_I(TAG, "Testing file: %s", path); + Nfc* poller = nfc_alloc(); + Nfc* listener = nfc_alloc(); + + NfcDevice* nfc_device = nfc_device_alloc(); + mu_assert(nfc_device_load(nfc_device, path), "nfc_device_load() failed\r\n"); + + NfcListener* mfu_listener = nfc_listener_alloc( + listener, + NfcProtocolMfUltralight, + nfc_device_get_data(nfc_device, NfcProtocolMfUltralight)); + nfc_listener_start(mfu_listener, NULL, NULL); + + MfUltralightData* mfu_data = mf_ultralight_alloc(); + MfUltralightError error = mf_ultralight_poller_read_card(poller, mfu_data); + mu_assert(error == MfUltralightErrorNone, "mf_ultralight_poller_read_card() failed"); + + nfc_listener_stop(mfu_listener); + nfc_listener_free(mfu_listener); + + mu_assert( + mf_ultralight_is_equal(mfu_data, nfc_device_get_data(nfc_device, NfcProtocolMfUltralight)), + "Data not matches"); + + mf_ultralight_free(mfu_data); + nfc_device_free(nfc_device); + nfc_free(listener); + nfc_free(poller); +} + +MU_TEST(mf_ultralight_11_reader) { + mf_ultralight_reader_test(EXT_PATH("unit_tests/nfc/Ultralight_11.nfc")); +} + +MU_TEST(mf_ultralight_21_reader) { + mf_ultralight_reader_test(EXT_PATH("unit_tests/nfc/Ultralight_21.nfc")); +} + +MU_TEST(ntag_215_reader) { + mf_ultralight_reader_test(EXT_PATH("unit_tests/nfc/Ntag215.nfc")); +} + +MU_TEST(ntag_216_reader) { + mf_ultralight_reader_test(EXT_PATH("unit_tests/nfc/Ntag216.nfc")); +} + +MU_TEST(ntag_213_locked_reader) { + FURI_LOG_I(TAG, "Testing Ntag215 locked file"); + Nfc* poller = nfc_alloc(); + Nfc* listener = nfc_alloc(); + + NfcDeviceData* nfc_device = nfc_device_alloc(); + mu_assert( + nfc_device_load(nfc_device, EXT_PATH("unit_tests/nfc/Ntag213_locked.nfc")), + "nfc_device_load() failed\r\n"); + + NfcListener* mfu_listener = nfc_listener_alloc( + listener, + NfcProtocolMfUltralight, + nfc_device_get_data(nfc_device, NfcProtocolMfUltralight)); + nfc_listener_start(mfu_listener, NULL, NULL); + + MfUltralightData* mfu_data = mf_ultralight_alloc(); + MfUltralightError error = mf_ultralight_poller_read_card(poller, mfu_data); + mu_assert(error == MfUltralightErrorNone, "mf_ultralight_poller_read_card() failed"); + + nfc_listener_stop(mfu_listener); + nfc_listener_free(mfu_listener); + + MfUltralightConfigPages* config = NULL; + const MfUltralightData* mfu_ref_data = + nfc_device_get_data(nfc_device, NfcProtocolMfUltralight); + mu_assert( + mf_ultralight_get_config_page(mfu_ref_data, &config), + "mf_ultralight_get_config_page() failed"); + uint16_t pages_locked = config->auth0; + + mu_assert(mfu_data->pages_read == pages_locked, "Unexpected pages read"); + + mf_ultralight_free(mfu_data); + nfc_device_free(nfc_device); + nfc_free(listener); + nfc_free(poller); +} + +static void mf_ultralight_write() { + Nfc* poller = nfc_alloc(); + Nfc* listener = nfc_alloc(); + + NfcDevice* nfc_device = nfc_device_alloc(); + nfc_data_generator_fill_data(NfcDataGeneratorTypeMfUltralightEV1_21, nfc_device); + + NfcListener* mfu_listener = nfc_listener_alloc( + listener, + NfcProtocolMfUltralight, + nfc_device_get_data(nfc_device, NfcProtocolMfUltralight)); + nfc_listener_start(mfu_listener, NULL, NULL); + + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + // Initial read + MfUltralightError error = mf_ultralight_poller_read_card(poller, mfu_data); + mu_assert(error == MfUltralightErrorNone, "mf_ultralight_poller_read_card() failed"); + + mu_assert( + mf_ultralight_is_equal(mfu_data, nfc_device_get_data(nfc_device, NfcProtocolMfUltralight)), + "Data not matches"); + + // Write random data + for(size_t i = 5; i < 15; i++) { + MfUltralightPage page = {}; + FURI_LOG_D(TAG, "Writing page %d", i); + furi_hal_random_fill_buf(page.data, sizeof(MfUltralightPage)); + mfu_data->page[i] = page; + error = mf_ultralight_poller_write_page(poller, i, &page); + mu_assert(error == MfUltralightErrorNone, "mf_ultralight_poller_write_page() failed"); + } + + // Verification read + error = mf_ultralight_poller_read_card(poller, mfu_data); + mu_assert(error == MfUltralightErrorNone, "mf_ultralight_poller_read_card() failed"); + + nfc_listener_stop(mfu_listener); + const MfUltralightData* mfu_listener_data = + nfc_listener_get_data(mfu_listener, NfcProtocolMfUltralight); + + mu_assert(mf_ultralight_is_equal(mfu_data, mfu_listener_data), "Data not matches"); + + nfc_listener_free(mfu_listener); + mf_ultralight_free(mfu_data); + nfc_device_free(nfc_device); + nfc_free(listener); + nfc_free(poller); +} + +static void mf_classic_reader() { + Nfc* poller = nfc_alloc(); + Nfc* listener = nfc_alloc(); + + NfcDevice* nfc_device = nfc_device_alloc(); + nfc_data_generator_fill_data(NfcDataGeneratorTypeMfClassic4k_7b, nfc_device); + NfcListener* mfc_listener = nfc_listener_alloc( + listener, NfcProtocolMfClassic, nfc_device_get_data(nfc_device, NfcProtocolMfClassic)); + nfc_listener_start(mfc_listener, NULL, NULL); + + MfClassicBlock block = {}; + MfClassicKey key = {.data = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}; + + mf_classic_poller_read_block(poller, 0, &key, MfClassicKeyTypeA, &block); + + nfc_listener_stop(mfc_listener); + nfc_listener_free(mfc_listener); + + const MfClassicData* mfc_data = nfc_device_get_data(nfc_device, NfcProtocolMfClassic); + mu_assert(memcmp(&mfc_data->block[0], &block, sizeof(MfClassicBlock)) == 0, "Data mismatch"); + + nfc_device_free(nfc_device); + nfc_free(listener); + nfc_free(poller); +} + +static void mf_classic_write() { + Nfc* poller = nfc_alloc(); + Nfc* listener = nfc_alloc(); + + NfcDevice* nfc_device = nfc_device_alloc(); + nfc_data_generator_fill_data(NfcDataGeneratorTypeMfClassic4k_7b, nfc_device); + NfcListener* mfc_listener = nfc_listener_alloc( + listener, NfcProtocolMfClassic, nfc_device_get_data(nfc_device, NfcProtocolMfClassic)); + nfc_listener_start(mfc_listener, NULL, NULL); + + MfClassicBlock block_write = {}; + MfClassicBlock block_read = {}; + furi_hal_random_fill_buf(block_write.data, sizeof(MfClassicBlock)); + MfClassicKey key = {.data = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}; + + mf_classic_poller_write_block(poller, 1, &key, MfClassicKeyTypeA, &block_write); + mf_classic_poller_read_block(poller, 1, &key, MfClassicKeyTypeA, &block_read); + + nfc_listener_stop(mfc_listener); + nfc_listener_free(mfc_listener); + + mu_assert(memcmp(&block_read, &block_write, sizeof(MfClassicBlock)) == 0, "Data mismatch"); + + nfc_device_free(nfc_device); + nfc_free(listener); + nfc_free(poller); +} + +static void mf_classic_value_block() { + Nfc* poller = nfc_alloc(); + Nfc* listener = nfc_alloc(); + + NfcDevice* nfc_device = nfc_device_alloc(); + nfc_data_generator_fill_data(NfcDataGeneratorTypeMfClassic4k_7b, nfc_device); + NfcListener* mfc_listener = nfc_listener_alloc( + listener, NfcProtocolMfClassic, nfc_device_get_data(nfc_device, NfcProtocolMfClassic)); + nfc_listener_start(mfc_listener, NULL, NULL); + + MfClassicKey key = {.data = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}; + + int32_t value = 228; + MfClassicBlock block_write = {}; + mf_classic_value_to_block(value, 1, &block_write); + + MfClassicError error = MfClassicErrorNone; + error = mf_classic_poller_write_block(poller, 1, &key, MfClassicKeyTypeA, &block_write); + mu_assert(error == MfClassicErrorNone, "Write failed"); + + int32_t data = 200; + int32_t new_value = 0; + error = mf_classic_poller_change_value(poller, 1, &key, MfClassicKeyTypeA, data, &new_value); + mu_assert(error == MfClassicErrorNone, "Value increment failed"); + mu_assert(new_value == value + data, "Value not match"); + + error = mf_classic_poller_change_value(poller, 1, &key, MfClassicKeyTypeA, -data, &new_value); + mu_assert(error == MfClassicErrorNone, "Value decrement failed"); + mu_assert(new_value == value, "Value not match"); + + nfc_listener_stop(mfc_listener); + nfc_listener_free(mfc_listener); + nfc_device_free(nfc_device); + nfc_free(listener); + nfc_free(poller); +} + +MU_TEST(mf_classic_dict_test) { + Storage* storage = furi_record_open(RECORD_STORAGE); + if(storage_common_stat(storage, NFC_APP_MF_CLASSIC_DICT_UNIT_TEST_PATH, NULL) == FSE_OK) { + mu_assert( + storage_simply_remove(storage, NFC_APP_MF_CLASSIC_DICT_UNIT_TEST_PATH), + "Remove test dict failed"); + } + + NfcDict* dict = nfc_dict_alloc( + NFC_APP_MF_CLASSIC_DICT_UNIT_TEST_PATH, NfcDictModeOpenAlways, sizeof(MfClassicKey)); + mu_assert(dict != NULL, "nfc_dict_alloc() failed"); + + size_t dict_keys_total = nfc_dict_get_total_keys(dict); + mu_assert(dict_keys_total == 0, "nfc_dict_keys_total() failed"); + + const uint32_t test_key_num = 30; + MfClassicKey* key_arr_ref = malloc(test_key_num * sizeof(MfClassicKey)); + for(size_t i = 0; i < test_key_num; i++) { + furi_hal_random_fill_buf(key_arr_ref[i].data, sizeof(MfClassicKey)); + mu_assert( + nfc_dict_add_key(dict, key_arr_ref[i].data, sizeof(MfClassicKey)), "add key failed"); + + size_t dict_keys_total = nfc_dict_get_total_keys(dict); + mu_assert(dict_keys_total == (i + 1), "nfc_dict_keys_total() failed"); + } + + nfc_dict_free(dict); + + dict = nfc_dict_alloc( + NFC_APP_MF_CLASSIC_DICT_UNIT_TEST_PATH, NfcDictModeOpenAlways, sizeof(MfClassicKey)); + mu_assert(dict != NULL, "nfc_dict_alloc() failed"); + + dict_keys_total = nfc_dict_get_total_keys(dict); + mu_assert(dict_keys_total == test_key_num, "nfc_dict_keys_total() failed"); + + MfClassicKey key_dut = {}; + size_t key_idx = 0; + while(nfc_dict_get_next_key(dict, key_dut.data, sizeof(MfClassicKey))) { + mu_assert( + memcmp(key_arr_ref[key_idx].data, key_dut.data, sizeof(MfClassicKey)) == 0, + "Loaded key data mismatch"); + key_idx++; + } + + uint32_t delete_keys_idx[] = {1, 3, 9, 11, 19, 27}; + + for(size_t i = 0; i < COUNT_OF(delete_keys_idx); i++) { + MfClassicKey* key = &key_arr_ref[delete_keys_idx[i]]; + mu_assert( + nfc_dict_is_key_present(dict, key->data, sizeof(MfClassicKey)), + "nfc_dict_is_key_present() failed"); + mu_assert( + nfc_dict_delete_key(dict, key->data, sizeof(MfClassicKey)), + "nfc_dict_delete_key() failed"); + } + + dict_keys_total = nfc_dict_get_total_keys(dict); + mu_assert( + dict_keys_total == test_key_num - COUNT_OF(delete_keys_idx), + "nfc_dict_keys_total() failed"); + + nfc_dict_free(dict); + free(key_arr_ref); + + mu_assert( + storage_simply_remove(storage, NFC_APP_MF_CLASSIC_DICT_UNIT_TEST_PATH), + "Remove test dict failed"); } MU_TEST_SUITE(nfc) { nfc_test_alloc(); - MU_RUN_TEST(nfca_file_test); - MU_RUN_TEST(mf_mini_file_test); + MU_RUN_TEST(iso14443_3a_reader); + MU_RUN_TEST(mf_ultralight_11_reader); + MU_RUN_TEST(mf_ultralight_21_reader); + MU_RUN_TEST(ntag_215_reader); + MU_RUN_TEST(ntag_216_reader); + MU_RUN_TEST(ntag_213_locked_reader); + + MU_RUN_TEST(mf_ultralight_write); + + MU_RUN_TEST(iso14443_3a_4b_file_test); + MU_RUN_TEST(iso14443_3a_7b_file_test); + + MU_RUN_TEST(mf_ultralight_file_test); + MU_RUN_TEST(mf_ultralight_ev1_11_file_test); + MU_RUN_TEST(mf_ultralight_ev1_h11_file_test); + MU_RUN_TEST(mf_ultralight_ev1_21_file_test); + MU_RUN_TEST(mf_ultralight_ev1_h21_file_test); + MU_RUN_TEST(mf_ultralight_ntag_203_file_test); + MU_RUN_TEST(mf_ultralight_ntag_213_file_test); + MU_RUN_TEST(mf_ultralight_ntag_215_file_test); + MU_RUN_TEST(mf_ultralight_ntag_216_file_test); + MU_RUN_TEST(mf_ultralight_ntag_i2c_1k_file_test); + MU_RUN_TEST(mf_ultralight_ntag_i2c_2k_file_test); + MU_RUN_TEST(mf_ultralight_ntag_i2c_plus_1k_file_test); + MU_RUN_TEST(mf_ultralight_ntag_i2c_plus_2k_file_test); + + MU_RUN_TEST(mf_classic_mini_file_test); MU_RUN_TEST(mf_classic_1k_4b_file_test); - MU_RUN_TEST(mf_classic_4k_4b_file_test); MU_RUN_TEST(mf_classic_1k_7b_file_test); + MU_RUN_TEST(mf_classic_4k_4b_file_test); MU_RUN_TEST(mf_classic_4k_7b_file_test); - MU_RUN_TEST(nfc_digital_signal_test); + MU_RUN_TEST(mf_classic_reader); + + MU_RUN_TEST(mf_classic_write); + MU_RUN_TEST(mf_classic_value_block); + MU_RUN_TEST(mf_classic_dict_test); - MU_RUN_TEST(mf_classic_dict_load_test); nfc_test_free(); } diff --git a/applications/debug/unit_tests/nfc/nfc_transport.c b/applications/debug/unit_tests/nfc/nfc_transport.c new file mode 100644 index 000000000..e2e313fde --- /dev/null +++ b/applications/debug/unit_tests/nfc/nfc_transport.c @@ -0,0 +1,458 @@ +#ifdef FW_CFG_unit_tests + +#include +#include +#include + +#include + +#define NFC_MAX_BUFFER_SIZE (256) + +typedef enum { + NfcTransportLogLevelWarning, + NfcTransportLogLevelInfo, +} NfcTransportLogLevel; + +FuriMessageQueue* poller_queue = NULL; +FuriMessageQueue* listener_queue = NULL; + +typedef enum { + NfcMessageTypeTx, + NfcMessageTypeTimeout, + NfcMessageTypeAbort, +} NfcMessageType; + +typedef struct { + uint16_t data_bits; + uint8_t data[NFC_MAX_BUFFER_SIZE]; +} NfcMessageData; + +typedef struct { + NfcMessageType type; + NfcMessageData data; +} NfcMessage; + +typedef enum { + NfcStateIdle, + NfcStateReady, + NfcStateReset, +} NfcState; + +typedef enum { + Iso14443_3aColResStatusIdle, + Iso14443_3aColResStatusInProgress, + Iso14443_3aColResStatusDone, +} Iso14443_3aColResStatus; + +typedef struct { + Iso14443_3aSensResp sens_resp; + Iso14443_3aSddResp sdd_resp[2]; + Iso14443_3aSelResp sel_resp[2]; +} Iso14443_3aColResData; + +struct Nfc { + NfcState state; + + Iso14443_3aColResStatus col_res_status; + Iso14443_3aColResData col_res_data; + + NfcEventCallback callback; + void* context; + + NfcMode mode; + + FuriThread* worker_thread; +}; + +static void nfc_test_print( + NfcTransportLogLevel log_level, + const char* message, + uint8_t* buffer, + uint16_t bits) { + FuriString* str = furi_string_alloc(); + size_t bytes = (bits + 7) / 8; + + for(size_t i = 0; i < bytes; i++) { + furi_string_cat_printf(str, " %02X", buffer[i]); + } + if(log_level == NfcTransportLogLevelWarning) { + FURI_LOG_W(message, "%s", furi_string_get_cstr(str)); + } else { + FURI_LOG_I(message, "%s", furi_string_get_cstr(str)); + } + + furi_string_free(str); +} + +static void nfc_prepare_col_res_data( + Nfc* instance, + uint8_t* uid, + uint8_t uid_len, + uint8_t* atqa, + uint8_t sak) { + memcpy(instance->col_res_data.sens_resp.sens_resp, atqa, 2); + + if(uid_len == 7) { + instance->col_res_data.sdd_resp[0].nfcid[0] = 0x88; + memcpy(&instance->col_res_data.sdd_resp[0].nfcid[1], uid, 3); + uint8_t bss = 0; + for(size_t i = 0; i < 4; i++) { + bss ^= instance->col_res_data.sdd_resp[0].nfcid[i]; + } + instance->col_res_data.sdd_resp[0].bss = bss; + instance->col_res_data.sel_resp[0].sak = 0x04; + + memcpy(instance->col_res_data.sdd_resp[1].nfcid, &uid[3], 4); + bss = 0; + for(size_t i = 0; i < 4; i++) { + bss ^= instance->col_res_data.sdd_resp[1].nfcid[i]; + } + instance->col_res_data.sdd_resp[1].bss = bss; + instance->col_res_data.sel_resp[1].sak = sak; + + } else { + furi_crash("Not supporting not 7 bytes"); + } +} + +Nfc* nfc_alloc() { + Nfc* instance = malloc(sizeof(Nfc)); + + return instance; +} + +void nfc_free(Nfc* instance) { + furi_check(instance); + + free(instance); +} + +void nfc_config(Nfc* instance, NfcMode mode, NfcTech tech) { + UNUSED(instance); + UNUSED(tech); + + instance->mode = mode; +} + +void nfc_set_fdt_poll_fc(Nfc* instance, uint32_t fdt_poll_fc) { + UNUSED(instance); + UNUSED(fdt_poll_fc); +} + +void nfc_set_fdt_listen_fc(Nfc* instance, uint32_t fdt_listen_fc) { + UNUSED(instance); + UNUSED(fdt_listen_fc); +} + +void nfc_set_mask_receive_time_fc(Nfc* instance, uint32_t mask_rx_time_fc) { + UNUSED(instance); + UNUSED(mask_rx_time_fc); +} + +void nfc_set_fdt_poll_poll_us(Nfc* instance, uint32_t fdt_poll_poll_us) { + UNUSED(instance); + UNUSED(fdt_poll_poll_us); +} + +void nfc_set_guard_time_us(Nfc* instance, uint32_t guard_time_us) { + UNUSED(instance); + UNUSED(guard_time_us); +} + +NfcError nfc_iso14443a_listener_set_col_res_data( + Nfc* instance, + uint8_t* uid, + uint8_t uid_len, + uint8_t* atqa, + uint8_t sak) { + furi_check(instance); + furi_check(uid); + furi_check(atqa); + + nfc_prepare_col_res_data(instance, uid, uid_len, atqa, sak); + + return NfcErrorNone; +} + +static int32_t nfc_worker_poller(void* context) { + Nfc* instance = context; + furi_check(instance->callback); + + instance->state = NfcStateReady; + NfcCommand command = NfcCommandContinue; + NfcEvent event = {}; + + while(true) { + event.type = NfcEventTypePollerReady; + command = instance->callback(event, instance->context); + if(command == NfcCommandStop) { + break; + } + } + + instance->state = NfcStateIdle; + + return 0; +} + +static void nfc_worker_listener_pass_col_res(Nfc* instance, uint8_t* rx_data, uint16_t rx_bits) { + furi_check(instance->col_res_status != Iso14443_3aColResStatusDone); + BitBuffer* tx_buffer = bit_buffer_alloc(NFC_MAX_BUFFER_SIZE); + + bool processed = false; + + if((rx_bits == 7) && (rx_data[0] == 0x52)) { + instance->col_res_status = Iso14443_3aColResStatusInProgress; + bit_buffer_copy_bytes( + tx_buffer, + instance->col_res_data.sens_resp.sens_resp, + sizeof(instance->col_res_data.sens_resp.sens_resp)); + nfc_listener_tx(instance, tx_buffer); + processed = true; + } else if(rx_bits == 2 * 8) { + if((rx_data[0] == 0x93) && (rx_data[1] == 0x20)) { + bit_buffer_copy_bytes( + tx_buffer, + (const uint8_t*)&instance->col_res_data.sdd_resp[0], + sizeof(Iso14443_3aSddResp)); + nfc_listener_tx(instance, tx_buffer); + processed = true; + } else if((rx_data[0] == 0x95) && (rx_data[1] == 0x20)) { + bit_buffer_copy_bytes( + tx_buffer, + (const uint8_t*)&instance->col_res_data.sdd_resp[1], + sizeof(Iso14443_3aSddResp)); + nfc_listener_tx(instance, tx_buffer); + processed = true; + } + } else if(rx_bits == 9 * 8) { + if((rx_data[0] == 0x93) && (rx_data[1] == 0x70)) { + bit_buffer_set_size_bytes(tx_buffer, 1); + bit_buffer_set_byte(tx_buffer, 0, instance->col_res_data.sel_resp[0].sak); + iso14443_crc_append(Iso14443CrcTypeA, tx_buffer); + nfc_listener_tx(instance, tx_buffer); + processed = true; + } else if((rx_data[0] == 0x95) && (rx_data[1] == 0x70)) { + bit_buffer_set_size_bytes(tx_buffer, 1); + bit_buffer_set_byte(tx_buffer, 0, instance->col_res_data.sel_resp[1].sak); + iso14443_crc_append(Iso14443CrcTypeA, tx_buffer); + nfc_listener_tx(instance, tx_buffer); + instance->col_res_status = Iso14443_3aColResStatusDone; + NfcEvent event = {.type = NfcEventTypeListenerActivated}; + instance->callback(event, instance->context); + + processed = true; + } + } + + if(!processed) { + NfcMessage message = {.type = NfcMessageTypeTimeout}; + furi_message_queue_put(poller_queue, &message, FuriWaitForever); + } + + bit_buffer_free(tx_buffer); +} + +static int32_t nfc_worker_listener(void* context) { + Nfc* instance = context; + furi_check(instance->callback); + + NfcMessage message = {}; + + NfcEventData event_data = {}; + event_data.buffer = bit_buffer_alloc(NFC_MAX_BUFFER_SIZE); + NfcEvent nfc_event = {.data = event_data}; + + while(true) { + furi_message_queue_get(listener_queue, &message, FuriWaitForever); + bit_buffer_copy_bits(event_data.buffer, message.data.data, message.data.data_bits); + if((message.data.data[0] == 0x52) && (message.data.data_bits == 7)) { + instance->col_res_status = Iso14443_3aColResStatusIdle; + } + + if(message.type == NfcMessageTypeAbort) { + break; + } else if(message.type == NfcMessageTypeTx) { + nfc_test_print( + NfcTransportLogLevelInfo, "RDR", message.data.data, message.data.data_bits); + if(instance->col_res_status != Iso14443_3aColResStatusDone) { + nfc_worker_listener_pass_col_res( + instance, message.data.data, message.data.data_bits); + } else { + instance->state = NfcStateReady; + nfc_event.type = NfcEventTypeRxEnd; + instance->callback(nfc_event, instance->context); + } + } + } + + instance->state = NfcStateIdle; + instance->col_res_status = Iso14443_3aColResStatusIdle; + memset(&instance->col_res_data, 0, sizeof(instance->col_res_data)); + bit_buffer_free(nfc_event.data.buffer); + + return 0; +} + +void nfc_start(Nfc* instance, NfcEventCallback callback, void* context) { + furi_check(instance); + furi_check(instance->worker_thread == NULL); + + if(instance->mode == NfcModeListener) { + furi_check(listener_queue == NULL); + // Check that poller didn't start + furi_check(poller_queue == NULL); + } else { + furi_check(poller_queue == NULL); + // Check that poller is started after listener + furi_check(listener_queue); + } + + instance->callback = callback; + instance->context = context; + + if(instance->mode == NfcModeListener) { + listener_queue = furi_message_queue_alloc(4, sizeof(NfcMessage)); + } else { + poller_queue = furi_message_queue_alloc(4, sizeof(NfcMessage)); + } + + instance->worker_thread = furi_thread_alloc(); + furi_thread_set_context(instance->worker_thread, instance); + furi_thread_set_priority(instance->worker_thread, FuriThreadPriorityHigh); + furi_thread_set_stack_size(instance->worker_thread, 8 * 1024); + + if(instance->mode == NfcModeListener) { + furi_thread_set_name(instance->worker_thread, "NfcWorkerListener"); + furi_thread_set_callback(instance->worker_thread, nfc_worker_listener); + } else { + furi_thread_set_name(instance->worker_thread, "NfcWorkerPoller"); + furi_thread_set_callback(instance->worker_thread, nfc_worker_poller); + } + + furi_thread_start(instance->worker_thread); +} + +void nfc_stop(Nfc* instance) { + furi_check(instance); + furi_check(instance->worker_thread); + + if(instance->mode == NfcModeListener) { + NfcMessage message = {.type = NfcMessageTypeAbort}; + furi_message_queue_put(listener_queue, &message, FuriWaitForever); + furi_thread_join(instance->worker_thread); + + furi_message_queue_free(listener_queue); + listener_queue = NULL; + + furi_thread_free(instance->worker_thread); + instance->worker_thread = NULL; + } else { + furi_thread_join(instance->worker_thread); + + furi_message_queue_free(poller_queue); + poller_queue = NULL; + + furi_thread_free(instance->worker_thread); + instance->worker_thread = NULL; + } +} + +// Called from worker thread + +NfcError nfc_listener_tx(Nfc* instance, const BitBuffer* tx_buffer) { + furi_check(instance); + furi_check(poller_queue); + furi_check(listener_queue); + furi_check(tx_buffer); + + NfcMessage message = {}; + message.type = NfcMessageTypeTx; + message.data.data_bits = bit_buffer_get_size(tx_buffer); + bit_buffer_write_bytes(tx_buffer, message.data.data, bit_buffer_get_size_bytes(tx_buffer)); + + furi_message_queue_put(poller_queue, &message, FuriWaitForever); + + return NfcErrorNone; +} + +NfcError nfc_iso14443a_listener_tx_custom_parity(Nfc* instance, const BitBuffer* tx_buffer) { + return nfc_listener_tx(instance, tx_buffer); +} + +NfcError + nfc_poller_trx(Nfc* instance, const BitBuffer* tx_buffer, BitBuffer* rx_buffer, uint32_t fwt) { + furi_check(instance); + furi_check(tx_buffer); + furi_check(rx_buffer); + furi_check(poller_queue); + furi_check(listener_queue); + UNUSED(fwt); + + NfcError error = NfcErrorNone; + + NfcMessage message = {}; + message.type = NfcMessageTypeTx; + message.data.data_bits = bit_buffer_get_size(tx_buffer); + bit_buffer_write_bytes(tx_buffer, message.data.data, bit_buffer_get_size_bytes(tx_buffer)); + // Tx + furi_check(furi_message_queue_put(listener_queue, &message, FuriWaitForever) == FuriStatusOk); + // Rx + FuriStatus status = furi_message_queue_get(poller_queue, &message, 50); + + if(status == FuriStatusErrorTimeout) { + error = NfcErrorTimeout; + } else if(message.type == NfcMessageTypeTx) { + bit_buffer_copy_bits(rx_buffer, message.data.data, message.data.data_bits); + nfc_test_print( + NfcTransportLogLevelWarning, "TAG", message.data.data, message.data.data_bits); + } else if(message.type == NfcMessageTypeTimeout) { + error = NfcErrorTimeout; + } + + return error; +} + +NfcError nfc_iso14443a_poller_trx_custom_parity( + Nfc* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + return nfc_poller_trx(instance, tx_buffer, rx_buffer, fwt); +} + +// Technology specific API + +NfcError nfc_iso14443a_poller_trx_short_frame( + Nfc* instance, + NfcIso14443aShortFrame frame, + BitBuffer* rx_buffer, + uint32_t fwt) { + UNUSED(frame); + + BitBuffer* tx_buffer = bit_buffer_alloc(32); + bit_buffer_set_size(tx_buffer, 7); + bit_buffer_set_byte(tx_buffer, 0, 0x52); + + NfcError error = nfc_poller_trx(instance, tx_buffer, rx_buffer, fwt); + + bit_buffer_free(tx_buffer); + + return error; +} + +NfcError nfc_iso14443a_poller_trx_sdd_frame( + Nfc* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + return nfc_poller_trx(instance, tx_buffer, rx_buffer, fwt); +} + +NfcError nfc_iso15693_listener_tx_sof(Nfc* instance) { + UNUSED(instance); + + return NfcErrorNone; +} + +#endif diff --git a/assets/unit_tests/Manifest b/applications/debug/unit_tests/resources/unit_tests/Manifest_test similarity index 100% rename from assets/unit_tests/Manifest rename to applications/debug/unit_tests/resources/unit_tests/Manifest_test diff --git a/assets/unit_tests/infrared/test_kaseikyo.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_kaseikyo.irtest similarity index 100% rename from assets/unit_tests/infrared/test_kaseikyo.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_kaseikyo.irtest diff --git a/assets/unit_tests/infrared/test_nec.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_nec.irtest similarity index 100% rename from assets/unit_tests/infrared/test_nec.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_nec.irtest diff --git a/assets/unit_tests/infrared/test_nec42.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_nec42.irtest similarity index 100% rename from assets/unit_tests/infrared/test_nec42.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_nec42.irtest diff --git a/assets/unit_tests/infrared/test_nec42ext.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_nec42ext.irtest similarity index 100% rename from assets/unit_tests/infrared/test_nec42ext.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_nec42ext.irtest diff --git a/assets/unit_tests/infrared/test_necext.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_necext.irtest similarity index 100% rename from assets/unit_tests/infrared/test_necext.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_necext.irtest diff --git a/assets/unit_tests/infrared/test_rc5.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_rc5.irtest similarity index 100% rename from assets/unit_tests/infrared/test_rc5.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_rc5.irtest diff --git a/assets/unit_tests/infrared/test_rc5x.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_rc5x.irtest similarity index 100% rename from assets/unit_tests/infrared/test_rc5x.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_rc5x.irtest diff --git a/assets/unit_tests/infrared/test_rc6.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_rc6.irtest similarity index 100% rename from assets/unit_tests/infrared/test_rc6.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_rc6.irtest diff --git a/assets/unit_tests/infrared/test_rca.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_rca.irtest similarity index 100% rename from assets/unit_tests/infrared/test_rca.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_rca.irtest diff --git a/assets/unit_tests/infrared/test_samsung32.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_samsung32.irtest similarity index 100% rename from assets/unit_tests/infrared/test_samsung32.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_samsung32.irtest diff --git a/assets/unit_tests/infrared/test_sirc.irtest b/applications/debug/unit_tests/resources/unit_tests/infrared/test_sirc.irtest similarity index 100% rename from assets/unit_tests/infrared/test_sirc.irtest rename to applications/debug/unit_tests/resources/unit_tests/infrared/test_sirc.irtest diff --git a/applications/debug/unit_tests/resources/unit_tests/nfc/Ntag213_locked.nfc b/applications/debug/unit_tests/resources/unit_tests/nfc/Ntag213_locked.nfc new file mode 100644 index 000000000..32f777116 --- /dev/null +++ b/applications/debug/unit_tests/resources/unit_tests/nfc/Ntag213_locked.nfc @@ -0,0 +1,66 @@ +Filetype: Flipper NFC device +Version: 3 +# Nfc device type can be UID, Mifare Ultralight, Mifare Classic +Device type: NTAG213 +# UID, ATQA and SAK are common for all formats +UID: 04 AC 6B 72 BA 6C 80 +ATQA: 00 44 +SAK: 00 +# Mifare Ultralight specific data +Data format version: 1 +Signature: 2D AE BC AF 84 B8 85 87 C2 FB FE 76 13 58 86 72 8E 1D 3C B5 DA 24 23 44 E5 63 4D 4C 82 FB D7 18 +Mifare version: 00 04 04 02 01 00 0F 03 +Counter 0: 0 +Tearing 0: 00 +Counter 1: 0 +Tearing 1: 00 +Counter 2: 0 +Tearing 2: 00 +Pages total: 45 +Pages read: 45 +Page 0: 04 AC 6B 4B +Page 1: 72 BA 6C 80 +Page 2: 24 48 00 00 +Page 3: E1 10 12 00 +Page 4: 00 00 41 50 +Page 5: 00 00 31 31 +Page 6: 00 20 09 28 +Page 7: 00 03 31 59 +Page 8: 91 DF D3 00 +Page 9: 00 00 00 00 +Page 10: 00 00 00 00 +Page 11: 00 00 00 00 +Page 12: 00 00 00 00 +Page 13: 00 00 00 00 +Page 14: 00 00 00 00 +Page 15: 00 00 00 00 +Page 16: 00 00 00 00 +Page 17: 00 00 00 00 +Page 18: 00 00 00 00 +Page 19: 00 00 00 00 +Page 20: 00 00 00 00 +Page 21: 00 00 00 00 +Page 22: 00 00 00 00 +Page 23: 00 00 00 00 +Page 24: 00 00 00 00 +Page 25: 00 00 00 00 +Page 26: 00 00 00 00 +Page 27: 00 00 00 00 +Page 28: 00 00 00 00 +Page 29: 00 00 00 00 +Page 30: 00 00 00 00 +Page 31: 00 00 00 00 +Page 32: 00 00 00 00 +Page 33: 00 00 00 00 +Page 34: 00 00 00 00 +Page 35: 00 00 00 00 +Page 36: 00 00 00 00 +Page 37: 00 00 00 00 +Page 38: 00 00 00 00 +Page 39: 00 00 00 00 +Page 40: 00 00 00 BD +Page 41: 04 00 00 04 +Page 42: C0 05 00 00 +Page 43: 95 3F 52 FF +Page 44: 00 00 00 00 +Failed authentication attempts: 0 diff --git a/applications/debug/unit_tests/resources/unit_tests/nfc/Ntag215.nfc b/applications/debug/unit_tests/resources/unit_tests/nfc/Ntag215.nfc new file mode 100644 index 000000000..420af08a6 --- /dev/null +++ b/applications/debug/unit_tests/resources/unit_tests/nfc/Ntag215.nfc @@ -0,0 +1,156 @@ +Filetype: Flipper NFC device +Version: 3 +# Nfc device type can be UID, Mifare Ultralight, Mifare Classic +Device type: NTAG215 +# UID, ATQA and SAK are common for all formats +UID: 04 51 5C FA 6F 73 81 +ATQA: 00 44 +SAK: 00 +# Mifare Ultralight specific data +Data format version: 1 +Signature: 42 21 E4 6C 79 6A 81 5E EA 0D 93 6D 85 EE 4B 0C 2A 00 D5 77 F1 C5 67 F3 63 75 F8 EB 86 48 5E 6B +Mifare version: 00 04 04 02 01 00 11 03 +Counter 0: 0 +Tearing 0: 00 +Counter 1: 0 +Tearing 1: 00 +Counter 2: 00 +Tearing 2: 00 +Pages total: 135 +Pages read: 135 +Page 0: 04 51 5C 81 +Page 1: FA 6F 73 81 +Page 2: 67 48 0F E0 +Page 3: F1 10 FF EE +Page 4: A5 00 00 00 +Page 5: 90 42 74 71 +Page 6: FD 8F 50 61 +Page 7: C5 65 1B 54 +Page 8: EF 68 D0 8E +Page 9: 3D 35 DB 83 +Page 10: D3 00 29 F6 +Page 11: 42 2A A5 5C +Page 12: F1 69 0A FC +Page 13: B6 44 E9 6B +Page 14: 77 41 88 81 +Page 15: 86 31 CB AD +Page 16: B1 DE F1 AB +Page 17: DF 96 C2 C5 +Page 18: C1 26 99 96 +Page 19: 85 AF 9F 0E +Page 20: 58 FE ED DC +Page 21: 0A 0A 00 01 +Page 22: 03 C1 05 02 +Page 23: 38 39 34 33 +Page 24: 49 2D 4E 5C +Page 25: 5B 21 0F 44 +Page 26: 3F 3F 76 69 +Page 27: B4 72 D8 38 +Page 28: A0 35 53 51 +Page 29: 53 EB A6 7C +Page 30: 3E 8B 97 C0 +Page 31: 00 7A 45 13 +Page 32: 3A 8B D4 0F +Page 33: 31 C2 32 CC +Page 34: B4 24 A6 1B +Page 35: D3 F5 4A 1F +Page 36: CD 8F 1D 64 +Page 37: 01 F4 DF C2 +Page 38: 11 16 C2 C5 +Page 39: 30 6D 49 AF +Page 40: 10 D4 7C 3C +Page 41: 6E 36 4E 08 +Page 42: 95 76 BC 84 +Page 43: 35 50 DD F0 +Page 44: 21 0F EE D9 +Page 45: 85 19 54 5F +Page 46: 3E A9 04 20 +Page 47: 1B 97 E4 39 +Page 48: FF 0A 45 F6 +Page 49: 13 D4 3E DD +Page 50: 97 42 FC 67 +Page 51: 6A AC 78 96 +Page 52: D1 DA 25 23 +Page 53: BF 4D B3 76 +Page 54: F1 21 ED 15 +Page 55: BD 55 11 C4 +Page 56: 4E 8C E9 23 +Page 57: C0 C4 6D 5A +Page 58: 58 25 FF 95 +Page 59: 3C 2B 7A 57 +Page 60: 66 BE A0 61 +Page 61: BC FC 4A 31 +Page 62: 4D AC EE 81 +Page 63: BE 1A 86 04 +Page 64: F6 D7 5E B3 +Page 65: E7 A8 A2 86 +Page 66: E9 40 AB 47 +Page 67: C8 36 E4 3E +Page 68: A7 4D D3 EA +Page 69: 83 9A 64 F7 +Page 70: 96 6B 5D BF +Page 71: 4E A2 A6 0F +Page 72: BD 3D BE 7C +Page 73: 22 0C 68 51 +Page 74: 0F 9A B8 AE +Page 75: 38 2C C4 CD +Page 76: 53 D8 DD 18 +Page 77: A6 5D 35 87 +Page 78: C9 6D 99 59 +Page 79: 61 9F B6 DC +Page 80: E6 22 0F 99 +Page 81: 39 82 79 60 +Page 82: 58 2E BE F7 +Page 83: EF F7 95 62 +Page 84: D5 06 1B 58 +Page 85: 65 05 A9 08 +Page 86: 75 ED 5D 90 +Page 87: 5A E1 7E C9 +Page 88: 35 D6 29 BB +Page 89: D0 67 6C F9 +Page 90: A0 FF 0B 93 +Page 91: 22 EA A3 3F +Page 92: E2 BD BD 58 +Page 93: BE 93 D9 94 +Page 94: 41 CC 7E 40 +Page 95: E6 8C 5A 43 +Page 96: 65 C1 24 94 +Page 97: B9 97 61 13 +Page 98: AD 74 FF 21 +Page 99: 0F EC F6 03 +Page 100: 89 5D 89 E5 +Page 101: 8D 11 F8 D7 +Page 102: 33 43 79 2E +Page 103: 23 E5 29 B5 +Page 104: 53 98 13 FF +Page 105: E8 79 8B 33 +Page 106: 45 6C 34 38 +Page 107: 3B 69 28 D7 +Page 108: D2 80 B0 2F +Page 109: D0 18 D5 DD +Page 110: 6C 2D D9 97 +Page 111: CA 78 B4 A2 +Page 112: B7 3E B8 79 +Page 113: A2 BE 54 E4 +Page 114: C8 28 0C 4A +Page 115: 81 E7 EC 1C +Page 116: 39 93 6F 70 +Page 117: 75 77 5C FC +Page 118: 66 58 0C 1C +Page 119: 9F 70 2E C8 +Page 120: 52 4A 52 BD +Page 121: 56 D5 6A 15 +Page 122: 54 1B 33 90 +Page 123: 44 11 C1 07 +Page 124: 11 5C BA 80 +Page 125: 10 14 20 9A +Page 126: 4A D8 E6 36 +Page 127: DA B8 59 E5 +Page 128: 5E 48 95 DA +Page 129: 96 6A 26 85 +Page 130: 01 00 0F BD +Page 131: 00 00 00 04 +Page 132: 5F 00 00 00 +Page 133: 00 00 00 00 +Page 134: 00 00 00 00 +Failed authentication attempts: 0 diff --git a/applications/debug/unit_tests/resources/unit_tests/nfc/Ntag216.nfc b/applications/debug/unit_tests/resources/unit_tests/nfc/Ntag216.nfc new file mode 100644 index 000000000..debe43858 --- /dev/null +++ b/applications/debug/unit_tests/resources/unit_tests/nfc/Ntag216.nfc @@ -0,0 +1,252 @@ +Filetype: Flipper NFC device +Version: 2 +# Nfc device type can be UID, Mifare Ultralight, Mifare Classic, Bank card +Device type: NTAG216 +# UID, ATQA and SAK are common for all formats +UID: 04 D9 65 0A 32 5E 80 +ATQA: 44 00 +SAK: 00 +# Mifare Ultralight specific data +Data format version: 1 +Signature: 48 2A F2 01 0F F2 F5 A7 9A D5 79 6E CB 14 54 48 98 D1 57 5D 8A 23 A9 B0 E8 20 02 3E CD C8 16 DB +Mifare version: 00 04 04 02 01 00 13 03 +Counter 0: 0 +Tearing 0: 00 +Counter 1: 0 +Tearing 1: 00 +Counter 2: 0 +Tearing 2: 00 +Pages total: 231 +Pages read: 231 +Page 0: 04 D9 65 30 +Page 1: 0A 32 5E 80 +Page 2: E6 48 00 00 +Page 3: E1 10 6D 00 +Page 4: 03 37 D1 01 +Page 5: 33 55 04 6D +Page 6: 2E 79 6F 75 +Page 7: 74 75 62 65 +Page 8: 2E 63 6F 6D +Page 9: 2F 77 61 74 +Page 10: 63 68 3F 76 +Page 11: 3D 62 78 71 +Page 12: 4C 73 72 6C +Page 13: 61 6B 4B 38 +Page 14: 26 66 65 61 +Page 15: 74 75 72 65 +Page 16: 3D 79 6F 75 +Page 17: 74 75 2E 62 +Page 18: 65 FE 00 00 +Page 19: 00 00 00 00 +Page 20: 00 00 00 00 +Page 21: 00 00 00 00 +Page 22: 00 00 00 00 +Page 23: 00 00 00 00 +Page 24: 00 00 00 00 +Page 25: 00 00 00 00 +Page 26: 00 00 00 00 +Page 27: 00 00 00 00 +Page 28: 00 00 00 00 +Page 29: 00 00 00 00 +Page 30: 00 00 00 00 +Page 31: 00 00 00 00 +Page 32: 00 00 00 00 +Page 33: 00 00 00 00 +Page 34: 00 00 00 00 +Page 35: 00 00 00 00 +Page 36: 00 00 00 00 +Page 37: 00 00 00 00 +Page 38: 00 00 00 00 +Page 39: 00 00 00 00 +Page 40: 00 00 00 00 +Page 41: 00 00 00 00 +Page 42: 00 00 00 00 +Page 43: 00 00 00 00 +Page 44: 00 00 00 00 +Page 45: 00 00 00 00 +Page 46: 00 00 00 00 +Page 47: 00 00 00 00 +Page 48: 00 00 00 00 +Page 49: 00 00 00 00 +Page 50: 00 00 00 00 +Page 51: 00 00 00 00 +Page 52: 00 00 00 00 +Page 53: 00 00 00 00 +Page 54: 00 00 00 00 +Page 55: 00 00 00 00 +Page 56: 00 00 00 00 +Page 57: 00 00 00 00 +Page 58: 00 00 00 00 +Page 59: 00 00 00 00 +Page 60: 00 00 00 00 +Page 61: 00 00 00 00 +Page 62: 00 00 00 00 +Page 63: 00 00 00 00 +Page 64: 00 00 00 00 +Page 65: 00 00 00 00 +Page 66: 00 00 00 00 +Page 67: 00 00 00 00 +Page 68: 00 00 00 00 +Page 69: 00 00 00 00 +Page 70: 00 00 00 00 +Page 71: 00 00 00 00 +Page 72: 00 00 00 00 +Page 73: 00 00 00 00 +Page 74: 00 00 00 00 +Page 75: 00 00 00 00 +Page 76: 00 00 00 00 +Page 77: 00 00 00 00 +Page 78: 00 00 00 00 +Page 79: 00 00 00 00 +Page 80: 00 00 00 00 +Page 81: 00 00 00 00 +Page 82: 00 00 00 00 +Page 83: 00 00 00 00 +Page 84: 00 00 00 00 +Page 85: 00 00 00 00 +Page 86: 00 00 00 00 +Page 87: 00 00 00 00 +Page 88: 00 00 00 00 +Page 89: 00 00 00 00 +Page 90: 00 00 00 00 +Page 91: 00 00 00 00 +Page 92: 00 00 00 00 +Page 93: 00 00 00 00 +Page 94: 00 00 00 00 +Page 95: 00 00 00 00 +Page 96: 00 00 00 00 +Page 97: 00 00 00 00 +Page 98: 00 00 00 00 +Page 99: 00 00 00 00 +Page 100: 00 00 00 00 +Page 101: 00 00 00 00 +Page 102: 00 00 00 00 +Page 103: 00 00 00 00 +Page 104: 00 00 00 00 +Page 105: 00 00 00 00 +Page 106: 00 00 00 00 +Page 107: 00 00 00 00 +Page 108: 00 00 00 00 +Page 109: 00 00 00 00 +Page 110: 00 00 00 00 +Page 111: 00 00 00 00 +Page 112: 00 00 00 00 +Page 113: 00 00 00 00 +Page 114: 00 00 00 00 +Page 115: 00 00 00 00 +Page 116: 00 00 00 00 +Page 117: 00 00 00 00 +Page 118: 00 00 00 00 +Page 119: 00 00 00 00 +Page 120: 00 00 00 00 +Page 121: 00 00 00 00 +Page 122: 00 00 00 00 +Page 123: 00 00 00 00 +Page 124: 00 00 00 00 +Page 125: 00 00 00 00 +Page 126: 00 00 00 00 +Page 127: 00 00 00 00 +Page 128: 00 00 00 00 +Page 129: 00 00 00 00 +Page 130: 00 00 00 00 +Page 131: 00 00 00 00 +Page 132: 00 00 00 00 +Page 133: 00 00 00 00 +Page 134: 00 00 00 00 +Page 135: 00 00 00 00 +Page 136: 00 00 00 00 +Page 137: 00 00 00 00 +Page 138: 00 00 00 00 +Page 139: 00 00 00 00 +Page 140: 00 00 00 00 +Page 141: 00 00 00 00 +Page 142: 00 00 00 00 +Page 143: 00 00 00 00 +Page 144: 00 00 00 00 +Page 145: 00 00 00 00 +Page 146: 00 00 00 00 +Page 147: 00 00 00 00 +Page 148: 00 00 00 00 +Page 149: 00 00 00 00 +Page 150: 00 00 00 00 +Page 151: 00 00 00 00 +Page 152: 00 00 00 00 +Page 153: 00 00 00 00 +Page 154: 00 00 00 00 +Page 155: 00 00 00 00 +Page 156: 00 00 00 00 +Page 157: 00 00 00 00 +Page 158: 00 00 00 00 +Page 159: 00 00 00 00 +Page 160: 00 00 00 00 +Page 161: 00 00 00 00 +Page 162: 00 00 00 00 +Page 163: 00 00 00 00 +Page 164: 00 00 00 00 +Page 165: 00 00 00 00 +Page 166: 00 00 00 00 +Page 167: 00 00 00 00 +Page 168: 00 00 00 00 +Page 169: 00 00 00 00 +Page 170: 00 00 00 00 +Page 171: 00 00 00 00 +Page 172: 00 00 00 00 +Page 173: 00 00 00 00 +Page 174: 00 00 00 00 +Page 175: 00 00 00 00 +Page 176: 00 00 00 00 +Page 177: 00 00 00 00 +Page 178: 00 00 00 00 +Page 179: 00 00 00 00 +Page 180: 00 00 00 00 +Page 181: 00 00 00 00 +Page 182: 00 00 00 00 +Page 183: 00 00 00 00 +Page 184: 00 00 00 00 +Page 185: 00 00 00 00 +Page 186: 00 00 00 00 +Page 187: 00 00 00 00 +Page 188: 00 00 00 00 +Page 189: 00 00 00 00 +Page 190: 00 00 00 00 +Page 191: 00 00 00 00 +Page 192: 00 00 00 00 +Page 193: 00 00 00 00 +Page 194: 00 00 00 00 +Page 195: 00 00 00 00 +Page 196: 00 00 00 00 +Page 197: 00 00 00 00 +Page 198: 00 00 00 00 +Page 199: 00 00 00 00 +Page 200: 00 00 00 00 +Page 201: 00 00 00 00 +Page 202: 00 00 00 00 +Page 203: 00 00 00 00 +Page 204: 00 00 00 00 +Page 205: 00 00 00 00 +Page 206: 00 00 00 00 +Page 207: 00 00 00 00 +Page 208: 00 00 00 00 +Page 209: 00 00 00 00 +Page 210: 00 00 00 00 +Page 211: 00 00 00 00 +Page 212: 00 00 00 00 +Page 213: 00 00 00 00 +Page 214: 00 00 00 00 +Page 215: 00 00 00 00 +Page 216: 00 00 00 00 +Page 217: 00 00 00 00 +Page 218: 00 00 00 00 +Page 219: 00 00 00 00 +Page 220: 00 00 00 00 +Page 221: 00 00 00 00 +Page 222: 00 00 00 00 +Page 223: 00 00 00 00 +Page 224: 00 00 00 00 +Page 225: 00 00 00 00 +Page 226: 00 00 00 BD +Page 227: 04 00 00 FF +Page 228: 00 05 00 00 +Page 229: 00 00 00 00 +Page 230: 00 00 00 00 +Failed authentication attempts: 0 diff --git a/applications/debug/unit_tests/resources/unit_tests/nfc/Ultralight_11.nfc b/applications/debug/unit_tests/resources/unit_tests/nfc/Ultralight_11.nfc new file mode 100644 index 000000000..22441289d --- /dev/null +++ b/applications/debug/unit_tests/resources/unit_tests/nfc/Ultralight_11.nfc @@ -0,0 +1,41 @@ +Filetype: Flipper NFC device +Version: 3 +# Nfc device type can be UID, Mifare Ultralight, Mifare Classic +Device type: Mifare Ultralight 11 +# UID, ATQA and SAK are common for all formats +UID: 04 15 74 F2 B0 5E 81 +ATQA: 00 44 +SAK: 00 +# Mifare Ultralight specific data +Data format version: 1 +Signature: A4 37 7D E5 8C 2F 88 D8 04 60 41 6E 3A C8 CD DB 19 94 26 12 C5 D0 12 B0 EB 88 05 72 89 F2 A5 61 +Mifare version: 00 04 03 01 01 00 0B 03 +Counter 0: 0 +Tearing 0: BD +Counter 1: 0 +Tearing 1: BD +Counter 2: 0 +Tearing 2: BD +Pages total: 20 +Pages read: 20 +Page 0: 04 15 74 ED +Page 1: F2 B0 5E 81 +Page 2: 9D 48 F8 FF +Page 3: C1 31 3E 3F +Page 4: B0 00 F0 02 +Page 5: 2F B3 45 A0 +Page 6: D4 9C 02 F2 +Page 7: 4A B1 ED FF +Page 8: C8 01 00 02 +Page 9: 4F B3 46 70 +Page 10: EE F6 60 B0 +Page 11: B6 C6 12 1B +Page 12: B9 1E 49 C3 +Page 13: 49 DF 7A 57 +Page 14: 08 52 2A 11 +Page 15: 28 0A 28 59 +Page 16: 00 00 00 FF +Page 17: 00 05 00 00 +Page 18: FF FF FF FF +Page 19: 00 00 00 00 +Failed authentication attempts: 0 diff --git a/applications/debug/unit_tests/resources/unit_tests/nfc/Ultralight_21.nfc b/applications/debug/unit_tests/resources/unit_tests/nfc/Ultralight_21.nfc new file mode 100644 index 000000000..dc01e93a6 --- /dev/null +++ b/applications/debug/unit_tests/resources/unit_tests/nfc/Ultralight_21.nfc @@ -0,0 +1,62 @@ +Filetype: Flipper NFC device +Version: 3 +# Nfc device type can be UID, Mifare Ultralight, Mifare Classic +Device type: Mifare Ultralight 21 +# UID, ATQA and SAK are common for all formats +UID: 34 BF AB B1 AE 73 D6 +ATQA: 00 44 +SAK: 00 +# Mifare Ultralight specific data +Data format version: 1 +Signature: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 +Mifare version: 00 34 21 01 01 00 0E 03 +Counter 0: 0 +Tearing 0: 00 +Counter 1: 0 +Tearing 1: 00 +Counter 2: 0 +Tearing 2: 00 +Pages total: 41 +Pages read: 41 +Page 0: 34 BF AB A8 +Page 1: B1 AE 73 D6 +Page 2: BA 00 70 08 +Page 3: FF FF FF FC +Page 4: 45 D9 BB A0 +Page 5: 5D 9D FA 00 +Page 6: 80 70 38 40 +Page 7: 12 30 02 00 +Page 8: 00 00 00 00 +Page 9: 00 00 00 00 +Page 10: AC A1 0D E4 +Page 11: 80 70 38 40 +Page 12: 00 57 A0 01 +Page 13: 00 08 C1 40 +Page 14: 00 00 00 00 +Page 15: AC A1 0D E4 +Page 16: 00 00 00 00 +Page 17: 00 00 00 00 +Page 18: 00 00 00 00 +Page 19: 00 00 00 00 +Page 20: 00 00 00 00 +Page 21: 00 00 00 00 +Page 22: 00 00 00 00 +Page 23: 00 00 00 00 +Page 24: 00 00 00 00 +Page 25: 00 00 00 00 +Page 26: 00 00 00 00 +Page 27: 00 00 00 00 +Page 28: 00 00 00 00 +Page 29: 00 00 00 00 +Page 30: 00 00 00 00 +Page 31: 00 00 00 00 +Page 32: 00 00 00 00 +Page 33: 00 00 00 00 +Page 34: 00 00 00 00 +Page 35: 00 00 00 00 +Page 36: 00 00 00 BD +Page 37: 00 00 00 FF +Page 38: 00 05 00 00 +Page 39: FF FF FF FF +Page 40: 00 00 00 00 +Failed authentication attempts: 0 diff --git a/assets/unit_tests/nfc/nfc_nfca_signal_long.nfc b/applications/debug/unit_tests/resources/unit_tests/nfc/nfc_nfca_signal_long.nfc similarity index 100% rename from assets/unit_tests/nfc/nfc_nfca_signal_long.nfc rename to applications/debug/unit_tests/resources/unit_tests/nfc/nfc_nfca_signal_long.nfc diff --git a/assets/unit_tests/nfc/nfc_nfca_signal_short.nfc b/applications/debug/unit_tests/resources/unit_tests/nfc/nfc_nfca_signal_short.nfc similarity index 100% rename from assets/unit_tests/nfc/nfc_nfca_signal_short.nfc rename to applications/debug/unit_tests/resources/unit_tests/nfc/nfc_nfca_signal_short.nfc diff --git a/assets/unit_tests/storage/md5.txt b/applications/debug/unit_tests/resources/unit_tests/storage/md5.txt similarity index 100% rename from assets/unit_tests/storage/md5.txt rename to applications/debug/unit_tests/resources/unit_tests/storage/md5.txt diff --git a/assets/unit_tests/subghz/alutech_at_4n_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/alutech_at_4n_raw.sub similarity index 100% rename from assets/unit_tests/subghz/alutech_at_4n_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/alutech_at_4n_raw.sub diff --git a/assets/unit_tests/subghz/ansonic.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/ansonic.sub similarity index 100% rename from assets/unit_tests/subghz/ansonic.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/ansonic.sub diff --git a/assets/unit_tests/subghz/ansonic_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/ansonic_raw.sub similarity index 100% rename from assets/unit_tests/subghz/ansonic_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/ansonic_raw.sub diff --git a/assets/unit_tests/subghz/bett.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/bett.sub similarity index 100% rename from assets/unit_tests/subghz/bett.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/bett.sub diff --git a/assets/unit_tests/subghz/bett_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/bett_raw.sub similarity index 100% rename from assets/unit_tests/subghz/bett_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/bett_raw.sub diff --git a/assets/unit_tests/subghz/came.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/came.sub similarity index 100% rename from assets/unit_tests/subghz/came.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/came.sub diff --git a/assets/unit_tests/subghz/came_atomo_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/came_atomo_raw.sub similarity index 100% rename from assets/unit_tests/subghz/came_atomo_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/came_atomo_raw.sub diff --git a/assets/unit_tests/subghz/came_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/came_raw.sub similarity index 100% rename from assets/unit_tests/subghz/came_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/came_raw.sub diff --git a/assets/unit_tests/subghz/came_twee.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/came_twee.sub similarity index 100% rename from assets/unit_tests/subghz/came_twee.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/came_twee.sub diff --git a/assets/unit_tests/subghz/came_twee_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/came_twee_raw.sub similarity index 100% rename from assets/unit_tests/subghz/came_twee_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/came_twee_raw.sub diff --git a/assets/unit_tests/subghz/cenmax_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/cenmax_raw.sub similarity index 100% rename from assets/unit_tests/subghz/cenmax_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/cenmax_raw.sub diff --git a/assets/unit_tests/subghz/clemsa.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/clemsa.sub similarity index 100% rename from assets/unit_tests/subghz/clemsa.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/clemsa.sub diff --git a/assets/unit_tests/subghz/clemsa_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/clemsa_raw.sub similarity index 100% rename from assets/unit_tests/subghz/clemsa_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/clemsa_raw.sub diff --git a/assets/unit_tests/subghz/doitrand.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/doitrand.sub similarity index 100% rename from assets/unit_tests/subghz/doitrand.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/doitrand.sub diff --git a/assets/unit_tests/subghz/doitrand_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/doitrand_raw.sub similarity index 100% rename from assets/unit_tests/subghz/doitrand_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/doitrand_raw.sub diff --git a/assets/unit_tests/subghz/doorhan.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/doorhan.sub similarity index 100% rename from assets/unit_tests/subghz/doorhan.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/doorhan.sub diff --git a/assets/unit_tests/subghz/doorhan_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/doorhan_raw.sub similarity index 100% rename from assets/unit_tests/subghz/doorhan_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/doorhan_raw.sub diff --git a/assets/unit_tests/subghz/dooya.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/dooya.sub similarity index 100% rename from assets/unit_tests/subghz/dooya.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/dooya.sub diff --git a/assets/unit_tests/subghz/dooya_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/dooya_raw.sub similarity index 100% rename from assets/unit_tests/subghz/dooya_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/dooya_raw.sub diff --git a/assets/unit_tests/subghz/faac_slh_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/faac_slh_raw.sub similarity index 100% rename from assets/unit_tests/subghz/faac_slh_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/faac_slh_raw.sub diff --git a/assets/unit_tests/subghz/gate_tx.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/gate_tx.sub similarity index 100% rename from assets/unit_tests/subghz/gate_tx.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/gate_tx.sub diff --git a/assets/unit_tests/subghz/gate_tx_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/gate_tx_raw.sub similarity index 100% rename from assets/unit_tests/subghz/gate_tx_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/gate_tx_raw.sub diff --git a/assets/unit_tests/subghz/holtek.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/holtek.sub similarity index 100% rename from assets/unit_tests/subghz/holtek.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/holtek.sub diff --git a/assets/unit_tests/subghz/holtek_ht12x.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/holtek_ht12x.sub similarity index 100% rename from assets/unit_tests/subghz/holtek_ht12x.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/holtek_ht12x.sub diff --git a/assets/unit_tests/subghz/holtek_ht12x_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/holtek_ht12x_raw.sub similarity index 100% rename from assets/unit_tests/subghz/holtek_ht12x_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/holtek_ht12x_raw.sub diff --git a/assets/unit_tests/subghz/holtek_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/holtek_raw.sub similarity index 100% rename from assets/unit_tests/subghz/holtek_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/holtek_raw.sub diff --git a/assets/unit_tests/subghz/honeywell_wdb.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/honeywell_wdb.sub similarity index 100% rename from assets/unit_tests/subghz/honeywell_wdb.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/honeywell_wdb.sub diff --git a/assets/unit_tests/subghz/honeywell_wdb_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/honeywell_wdb_raw.sub similarity index 100% rename from assets/unit_tests/subghz/honeywell_wdb_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/honeywell_wdb_raw.sub diff --git a/assets/unit_tests/subghz/hormann_hsm_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/hormann_hsm_raw.sub similarity index 100% rename from assets/unit_tests/subghz/hormann_hsm_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/hormann_hsm_raw.sub diff --git a/assets/unit_tests/subghz/ido_117_111_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/ido_117_111_raw.sub similarity index 100% rename from assets/unit_tests/subghz/ido_117_111_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/ido_117_111_raw.sub diff --git a/assets/unit_tests/subghz/intertechno_v3.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/intertechno_v3.sub similarity index 100% rename from assets/unit_tests/subghz/intertechno_v3.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/intertechno_v3.sub diff --git a/assets/unit_tests/subghz/intertechno_v3_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/intertechno_v3_raw.sub similarity index 100% rename from assets/unit_tests/subghz/intertechno_v3_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/intertechno_v3_raw.sub diff --git a/assets/unit_tests/subghz/kia_seed_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/kia_seed_raw.sub similarity index 100% rename from assets/unit_tests/subghz/kia_seed_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/kia_seed_raw.sub diff --git a/assets/unit_tests/subghz/kinggates_stylo4k_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/kinggates_stylo4k_raw.sub similarity index 100% rename from assets/unit_tests/subghz/kinggates_stylo4k_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/kinggates_stylo4k_raw.sub diff --git a/assets/unit_tests/subghz/linear.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/linear.sub similarity index 100% rename from assets/unit_tests/subghz/linear.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/linear.sub diff --git a/assets/unit_tests/subghz/linear_delta3.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/linear_delta3.sub similarity index 100% rename from assets/unit_tests/subghz/linear_delta3.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/linear_delta3.sub diff --git a/assets/unit_tests/subghz/linear_delta3_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/linear_delta3_raw.sub similarity index 100% rename from assets/unit_tests/subghz/linear_delta3_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/linear_delta3_raw.sub diff --git a/assets/unit_tests/subghz/linear_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/linear_raw.sub similarity index 100% rename from assets/unit_tests/subghz/linear_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/linear_raw.sub diff --git a/assets/unit_tests/subghz/magellan.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/magellan.sub similarity index 100% rename from assets/unit_tests/subghz/magellan.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/magellan.sub diff --git a/assets/unit_tests/subghz/magellan_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/magellan_raw.sub similarity index 100% rename from assets/unit_tests/subghz/magellan_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/magellan_raw.sub diff --git a/assets/unit_tests/subghz/marantec.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/marantec.sub similarity index 100% rename from assets/unit_tests/subghz/marantec.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/marantec.sub diff --git a/assets/unit_tests/subghz/marantec_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/marantec_raw.sub similarity index 100% rename from assets/unit_tests/subghz/marantec_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/marantec_raw.sub diff --git a/assets/unit_tests/subghz/megacode.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/megacode.sub similarity index 100% rename from assets/unit_tests/subghz/megacode.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/megacode.sub diff --git a/assets/unit_tests/subghz/megacode_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/megacode_raw.sub similarity index 100% rename from assets/unit_tests/subghz/megacode_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/megacode_raw.sub diff --git a/assets/unit_tests/subghz/nero_radio_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/nero_radio_raw.sub similarity index 100% rename from assets/unit_tests/subghz/nero_radio_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/nero_radio_raw.sub diff --git a/assets/unit_tests/subghz/nero_sketch_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/nero_sketch_raw.sub similarity index 100% rename from assets/unit_tests/subghz/nero_sketch_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/nero_sketch_raw.sub diff --git a/assets/unit_tests/subghz/nice_flo.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/nice_flo.sub similarity index 100% rename from assets/unit_tests/subghz/nice_flo.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/nice_flo.sub diff --git a/assets/unit_tests/subghz/nice_flo_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/nice_flo_raw.sub similarity index 100% rename from assets/unit_tests/subghz/nice_flo_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/nice_flo_raw.sub diff --git a/assets/unit_tests/subghz/nice_flor_s_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/nice_flor_s_raw.sub similarity index 100% rename from assets/unit_tests/subghz/nice_flor_s_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/nice_flor_s_raw.sub diff --git a/assets/unit_tests/subghz/nice_one_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/nice_one_raw.sub similarity index 100% rename from assets/unit_tests/subghz/nice_one_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/nice_one_raw.sub diff --git a/assets/unit_tests/subghz/phoenix_v2.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/phoenix_v2.sub similarity index 100% rename from assets/unit_tests/subghz/phoenix_v2.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/phoenix_v2.sub diff --git a/assets/unit_tests/subghz/phoenix_v2_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/phoenix_v2_raw.sub similarity index 100% rename from assets/unit_tests/subghz/phoenix_v2_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/phoenix_v2_raw.sub diff --git a/assets/unit_tests/subghz/power_smart.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/power_smart.sub similarity index 100% rename from assets/unit_tests/subghz/power_smart.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/power_smart.sub diff --git a/assets/unit_tests/subghz/power_smart_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/power_smart_raw.sub similarity index 100% rename from assets/unit_tests/subghz/power_smart_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/power_smart_raw.sub diff --git a/assets/unit_tests/subghz/princeton.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/princeton.sub similarity index 100% rename from assets/unit_tests/subghz/princeton.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/princeton.sub diff --git a/assets/unit_tests/subghz/princeton_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/princeton_raw.sub similarity index 100% rename from assets/unit_tests/subghz/princeton_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/princeton_raw.sub diff --git a/assets/unit_tests/subghz/scher_khan_magic_code.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/scher_khan_magic_code.sub similarity index 100% rename from assets/unit_tests/subghz/scher_khan_magic_code.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/scher_khan_magic_code.sub diff --git a/assets/unit_tests/subghz/security_pls_1_0.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/security_pls_1_0.sub similarity index 100% rename from assets/unit_tests/subghz/security_pls_1_0.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/security_pls_1_0.sub diff --git a/assets/unit_tests/subghz/security_pls_1_0_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/security_pls_1_0_raw.sub similarity index 100% rename from assets/unit_tests/subghz/security_pls_1_0_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/security_pls_1_0_raw.sub diff --git a/assets/unit_tests/subghz/security_pls_2_0.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/security_pls_2_0.sub similarity index 100% rename from assets/unit_tests/subghz/security_pls_2_0.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/security_pls_2_0.sub diff --git a/assets/unit_tests/subghz/security_pls_2_0_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/security_pls_2_0_raw.sub similarity index 100% rename from assets/unit_tests/subghz/security_pls_2_0_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/security_pls_2_0_raw.sub diff --git a/assets/unit_tests/subghz/smc5326.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/smc5326.sub similarity index 100% rename from assets/unit_tests/subghz/smc5326.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/smc5326.sub diff --git a/assets/unit_tests/subghz/smc5326_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/smc5326_raw.sub similarity index 100% rename from assets/unit_tests/subghz/smc5326_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/smc5326_raw.sub diff --git a/assets/unit_tests/subghz/somfy_keytis_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/somfy_keytis_raw.sub similarity index 100% rename from assets/unit_tests/subghz/somfy_keytis_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/somfy_keytis_raw.sub diff --git a/assets/unit_tests/subghz/somfy_telis_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/somfy_telis_raw.sub similarity index 100% rename from assets/unit_tests/subghz/somfy_telis_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/somfy_telis_raw.sub diff --git a/assets/unit_tests/subghz/test_random_raw.sub b/applications/debug/unit_tests/resources/unit_tests/subghz/test_random_raw.sub similarity index 100% rename from assets/unit_tests/subghz/test_random_raw.sub rename to applications/debug/unit_tests/resources/unit_tests/subghz/test_random_raw.sub diff --git a/applications/debug/unit_tests/rpc/rpc_test.c b/applications/debug/unit_tests/rpc/rpc_test.c index 645e75e84..5659ba877 100644 --- a/applications/debug/unit_tests/rpc/rpc_test.c +++ b/applications/debug/unit_tests/rpc/rpc_test.c @@ -18,6 +18,8 @@ #include #include #include + +#include #include LIST_DEF(MsgList, PB_Main, M_POD_OPLIST) @@ -36,7 +38,7 @@ typedef struct { FuriStreamBuffer* output_stream; SemaphoreHandle_t close_session_semaphore; SemaphoreHandle_t terminate_semaphore; - TickType_t timeout; + uint32_t timeout; } RpcSessionContext; static RpcSessionContext rpc_session[TEST_RPC_SESSIONS]; @@ -544,7 +546,7 @@ static bool test_rpc_pb_stream_read(pb_istream_t* istream, pb_byte_t* buf, size_ RpcSessionContext* session_context = istream->state; size_t bytes_received = 0; - TickType_t now = xTaskGetTickCount(); + uint32_t now = furi_get_tick(); int32_t time_left = session_context->timeout - now; time_left = MAX(time_left, 0); bytes_received = @@ -688,7 +690,7 @@ static void test_rpc_decode_and_compare(MsgList_t expected_msg_list, uint8_t ses furi_check(!MsgList_empty_p(expected_msg_list)); furi_check(session < TEST_RPC_SESSIONS); - rpc_session[session].timeout = xTaskGetTickCount() + MAX_RECEIVE_OUTPUT_TIMEOUT; + rpc_session[session].timeout = furi_get_tick() + MAX_RECEIVE_OUTPUT_TIMEOUT; pb_istream_t istream = { .callback = test_rpc_pb_stream_read, .state = &rpc_session[session], @@ -712,7 +714,7 @@ static void test_rpc_decode_and_compare(MsgList_t expected_msg_list, uint8_t ses pb_release(&PB_Main_msg, &result); } - rpc_session[session].timeout = xTaskGetTickCount() + 50; + rpc_session[session].timeout = furi_get_tick() + 50; if(pb_decode_ex(&istream, &PB_Main_msg, &result, PB_DECODE_DELIMITED)) { mu_fail("decoded more than expected"); } diff --git a/applications/debug/unit_tests/test_index.c b/applications/debug/unit_tests/test_index.c index edaf950c5..7c1b6b444 100644 --- a/applications/debug/unit_tests/test_index.c +++ b/applications/debug/unit_tests/test_index.c @@ -65,8 +65,8 @@ const UnitTest unit_tests[] = { void minunit_print_progress() { static const char progress[] = {'\\', '|', '/', '-'}; static uint8_t progress_counter = 0; - static TickType_t last_tick = 0; - TickType_t current_tick = xTaskGetTickCount(); + static uint32_t last_tick = 0; + uint32_t current_tick = furi_get_tick(); if(current_tick - last_tick > 20) { last_tick = current_tick; printf("[%c]\033[3D", progress[++progress_counter % COUNT_OF(progress)]); diff --git a/applications/examples/example_plugins/application.fam b/applications/examples/example_plugins/application.fam index a6e3c2078..d9a36da56 100644 --- a/applications/examples/example_plugins/application.fam +++ b/applications/examples/example_plugins/application.fam @@ -5,6 +5,7 @@ App( entry_point="example_plugins_app", stack_size=2 * 1024, fap_category="Examples", + sources=["*.c", "!plugin*.c"], ) App( @@ -21,6 +22,7 @@ App( apptype=FlipperAppType.PLUGIN, entry_point="example_plugin1_ep", requires=["example_plugins", "example_plugins_multi"], + sources=["plugin1.c"], ) App( @@ -28,4 +30,5 @@ App( apptype=FlipperAppType.PLUGIN, entry_point="example_plugin2_ep", requires=["example_plugins_multi"], + sources=["plugin2.c"], ) diff --git a/applications/examples/example_plugins_advanced/application.fam b/applications/examples/example_plugins_advanced/application.fam index d40c0dde2..0c7e3e3b9 100644 --- a/applications/examples/example_plugins_advanced/application.fam +++ b/applications/examples/example_plugins_advanced/application.fam @@ -5,6 +5,7 @@ App( entry_point="example_advanced_plugins_app", stack_size=2 * 1024, fap_category="Examples", + sources=["*.c*", "!plugin*.c"], ) App( diff --git a/applications/main/archive/archive.c b/applications/main/archive/archive.c index 4a5a8b39e..066fcab05 100644 --- a/applications/main/archive/archive.c +++ b/applications/main/archive/archive.c @@ -95,18 +95,17 @@ void archive_free(ArchiveApp* archive) { } void archive_show_loading_popup(ArchiveApp* context, bool show) { - TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME); ViewStack* view_stack = context->view_stack; Loading* loading = context->loading; if(show) { // Raise timer priority so that animations can play - vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1); + furi_timer_set_thread_priority(FuriTimerThreadPriorityElevated); view_stack_add_view(view_stack, loading_get_view(loading)); } else { view_stack_remove_view(view_stack, loading_get_view(loading)); // Restore default timer priority - vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY); + furi_timer_set_thread_priority(FuriTimerThreadPriorityNormal); } } diff --git a/applications/main/bad_usb/application.fam b/applications/main/bad_usb/application.fam index 5c42c9fa3..9844e248d 100644 --- a/applications/main/bad_usb/application.fam +++ b/applications/main/bad_usb/application.fam @@ -6,6 +6,7 @@ App( stack_size=2 * 1024, icon="A_BadUsb_14", order=70, + resources="resources", fap_libs=["assets"], fap_icon="icon.png", fap_category="USB", diff --git a/assets/resources/badusb/Install_qFlipper_macOS.txt b/applications/main/bad_usb/resources/badusb/Install_qFlipper_macOS.txt similarity index 100% rename from assets/resources/badusb/Install_qFlipper_macOS.txt rename to applications/main/bad_usb/resources/badusb/Install_qFlipper_macOS.txt diff --git a/assets/resources/badusb/Install_qFlipper_windows.txt b/applications/main/bad_usb/resources/badusb/Install_qFlipper_windows.txt similarity index 100% rename from assets/resources/badusb/Install_qFlipper_windows.txt rename to applications/main/bad_usb/resources/badusb/Install_qFlipper_windows.txt diff --git a/assets/resources/badusb/assets/layouts/ba-BA.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/ba-BA.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/ba-BA.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/ba-BA.kl diff --git a/assets/resources/badusb/assets/layouts/cz_CS.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/cz_CS.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/cz_CS.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/cz_CS.kl diff --git a/assets/resources/badusb/assets/layouts/da-DA.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/da-DA.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/da-DA.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/da-DA.kl diff --git a/assets/resources/badusb/assets/layouts/de-CH.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/de-CH.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/de-CH.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/de-CH.kl diff --git a/assets/resources/badusb/assets/layouts/de-DE.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/de-DE.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/de-DE.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/de-DE.kl diff --git a/assets/resources/badusb/assets/layouts/dvorak.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/dvorak.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/dvorak.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/dvorak.kl diff --git a/assets/resources/badusb/assets/layouts/en-UK.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/en-UK.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/en-UK.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/en-UK.kl diff --git a/assets/resources/badusb/assets/layouts/en-US.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/en-US.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/en-US.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/en-US.kl diff --git a/assets/resources/badusb/assets/layouts/es-ES.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/es-ES.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/es-ES.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/es-ES.kl diff --git a/assets/resources/badusb/assets/layouts/fr-BE.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/fr-BE.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/fr-BE.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/fr-BE.kl diff --git a/assets/resources/badusb/assets/layouts/fr-CA.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/fr-CA.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/fr-CA.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/fr-CA.kl diff --git a/assets/resources/badusb/assets/layouts/fr-CH.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/fr-CH.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/fr-CH.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/fr-CH.kl diff --git a/assets/resources/badusb/assets/layouts/fr-FR-mac.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/fr-FR-mac.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/fr-FR-mac.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/fr-FR-mac.kl diff --git a/assets/resources/badusb/assets/layouts/fr-FR.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/fr-FR.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/fr-FR.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/fr-FR.kl diff --git a/assets/resources/badusb/assets/layouts/hr-HR.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/hr-HR.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/hr-HR.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/hr-HR.kl diff --git a/assets/resources/badusb/assets/layouts/hu-HU.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/hu-HU.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/hu-HU.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/hu-HU.kl diff --git a/assets/resources/badusb/assets/layouts/it-IT.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/it-IT.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/it-IT.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/it-IT.kl diff --git a/assets/resources/badusb/assets/layouts/nb-NO.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/nb-NO.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/nb-NO.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/nb-NO.kl diff --git a/assets/resources/badusb/assets/layouts/nl-NL.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/nl-NL.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/nl-NL.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/nl-NL.kl diff --git a/assets/resources/badusb/assets/layouts/pt-BR.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/pt-BR.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/pt-BR.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/pt-BR.kl diff --git a/assets/resources/badusb/assets/layouts/pt-PT.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/pt-PT.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/pt-PT.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/pt-PT.kl diff --git a/assets/resources/badusb/assets/layouts/si-SI.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/si-SI.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/si-SI.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/si-SI.kl diff --git a/assets/resources/badusb/assets/layouts/sk-SK.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/sk-SK.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/sk-SK.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/sk-SK.kl diff --git a/assets/resources/badusb/assets/layouts/sv-SE.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/sv-SE.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/sv-SE.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/sv-SE.kl diff --git a/assets/resources/badusb/assets/layouts/tr-TR.kl b/applications/main/bad_usb/resources/badusb/assets/layouts/tr-TR.kl similarity index 100% rename from assets/resources/badusb/assets/layouts/tr-TR.kl rename to applications/main/bad_usb/resources/badusb/assets/layouts/tr-TR.kl diff --git a/assets/resources/badusb/demo_macos.txt b/applications/main/bad_usb/resources/badusb/demo_macos.txt similarity index 100% rename from assets/resources/badusb/demo_macos.txt rename to applications/main/bad_usb/resources/badusb/demo_macos.txt diff --git a/assets/resources/badusb/demo_windows.txt b/applications/main/bad_usb/resources/badusb/demo_windows.txt similarity index 100% rename from assets/resources/badusb/demo_windows.txt rename to applications/main/bad_usb/resources/badusb/demo_windows.txt diff --git a/applications/main/clock_app/application.fam b/applications/main/clock_app/application.fam index 47f152b1d..7dc7fb12a 100644 --- a/applications/main/clock_app/application.fam +++ b/applications/main/clock_app/application.fam @@ -6,6 +6,7 @@ App( icon="A_Clock_14", stack_size=2 * 1024, order=81, + resources="resources", fap_icon="icon.png", fap_category="Tools", ) diff --git a/assets/resources/ibtnfuzzer/example_uids_cyfral.txt b/applications/main/clock_app/resources/ibtnfuzzer/example_uids_cyfral.txt similarity index 100% rename from assets/resources/ibtnfuzzer/example_uids_cyfral.txt rename to applications/main/clock_app/resources/ibtnfuzzer/example_uids_cyfral.txt diff --git a/assets/resources/ibtnfuzzer/example_uids_ds1990.txt b/applications/main/clock_app/resources/ibtnfuzzer/example_uids_ds1990.txt similarity index 100% rename from assets/resources/ibtnfuzzer/example_uids_ds1990.txt rename to applications/main/clock_app/resources/ibtnfuzzer/example_uids_ds1990.txt diff --git a/assets/resources/ibtnfuzzer/example_uids_metakom.txt b/applications/main/clock_app/resources/ibtnfuzzer/example_uids_metakom.txt similarity index 100% rename from assets/resources/ibtnfuzzer/example_uids_metakom.txt rename to applications/main/clock_app/resources/ibtnfuzzer/example_uids_metakom.txt diff --git a/assets/resources/music_player/Marble_Machine.fmf b/applications/main/clock_app/resources/music_player/Marble_Machine.fmf similarity index 100% rename from assets/resources/music_player/Marble_Machine.fmf rename to applications/main/clock_app/resources/music_player/Marble_Machine.fmf diff --git a/assets/resources/rfidfuzzer/example_uids_em4100.txt b/applications/main/clock_app/resources/rfidfuzzer/example_uids_em4100.txt similarity index 100% rename from assets/resources/rfidfuzzer/example_uids_em4100.txt rename to applications/main/clock_app/resources/rfidfuzzer/example_uids_em4100.txt diff --git a/assets/resources/rfidfuzzer/example_uids_h10301.txt b/applications/main/clock_app/resources/rfidfuzzer/example_uids_h10301.txt similarity index 100% rename from assets/resources/rfidfuzzer/example_uids_h10301.txt rename to applications/main/clock_app/resources/rfidfuzzer/example_uids_h10301.txt diff --git a/assets/resources/rfidfuzzer/example_uids_hidprox.txt b/applications/main/clock_app/resources/rfidfuzzer/example_uids_hidprox.txt similarity index 100% rename from assets/resources/rfidfuzzer/example_uids_hidprox.txt rename to applications/main/clock_app/resources/rfidfuzzer/example_uids_hidprox.txt diff --git a/assets/resources/rfidfuzzer/example_uids_pac.txt b/applications/main/clock_app/resources/rfidfuzzer/example_uids_pac.txt similarity index 100% rename from assets/resources/rfidfuzzer/example_uids_pac.txt rename to applications/main/clock_app/resources/rfidfuzzer/example_uids_pac.txt diff --git a/assets/resources/subplaylist/example_playlist.txt b/applications/main/clock_app/resources/subplaylist/example_playlist.txt similarity index 100% rename from assets/resources/subplaylist/example_playlist.txt rename to applications/main/clock_app/resources/subplaylist/example_playlist.txt diff --git a/assets/resources/swd_scripts/100us.swd b/applications/main/clock_app/resources/swd_scripts/100us.swd similarity index 100% rename from assets/resources/swd_scripts/100us.swd rename to applications/main/clock_app/resources/swd_scripts/100us.swd diff --git a/assets/resources/swd_scripts/call_test_1.swd b/applications/main/clock_app/resources/swd_scripts/call_test_1.swd similarity index 100% rename from assets/resources/swd_scripts/call_test_1.swd rename to applications/main/clock_app/resources/swd_scripts/call_test_1.swd diff --git a/assets/resources/swd_scripts/call_test_2.swd b/applications/main/clock_app/resources/swd_scripts/call_test_2.swd similarity index 100% rename from assets/resources/swd_scripts/call_test_2.swd rename to applications/main/clock_app/resources/swd_scripts/call_test_2.swd diff --git a/assets/resources/swd_scripts/dump_0x00000000_1k.swd b/applications/main/clock_app/resources/swd_scripts/dump_0x00000000_1k.swd similarity index 100% rename from assets/resources/swd_scripts/dump_0x00000000_1k.swd rename to applications/main/clock_app/resources/swd_scripts/dump_0x00000000_1k.swd diff --git a/assets/resources/swd_scripts/dump_0x00000000_4b.swd b/applications/main/clock_app/resources/swd_scripts/dump_0x00000000_4b.swd similarity index 100% rename from assets/resources/swd_scripts/dump_0x00000000_4b.swd rename to applications/main/clock_app/resources/swd_scripts/dump_0x00000000_4b.swd diff --git a/assets/resources/swd_scripts/dump_STM32.swd b/applications/main/clock_app/resources/swd_scripts/dump_STM32.swd similarity index 100% rename from assets/resources/swd_scripts/dump_STM32.swd rename to applications/main/clock_app/resources/swd_scripts/dump_STM32.swd diff --git a/assets/resources/swd_scripts/goto_test.swd b/applications/main/clock_app/resources/swd_scripts/goto_test.swd similarity index 100% rename from assets/resources/swd_scripts/goto_test.swd rename to applications/main/clock_app/resources/swd_scripts/goto_test.swd diff --git a/assets/resources/swd_scripts/halt.swd b/applications/main/clock_app/resources/swd_scripts/halt.swd similarity index 100% rename from assets/resources/swd_scripts/halt.swd rename to applications/main/clock_app/resources/swd_scripts/halt.swd diff --git a/assets/resources/swd_scripts/reset.swd b/applications/main/clock_app/resources/swd_scripts/reset.swd similarity index 100% rename from assets/resources/swd_scripts/reset.swd rename to applications/main/clock_app/resources/swd_scripts/reset.swd diff --git a/assets/resources/swd_scripts/test_write.swd b/applications/main/clock_app/resources/swd_scripts/test_write.swd similarity index 100% rename from assets/resources/swd_scripts/test_write.swd rename to applications/main/clock_app/resources/swd_scripts/test_write.swd diff --git a/applications/main/ibutton/application.fam b/applications/main/ibutton/application.fam index a8faa629c..01c02ec23 100644 --- a/applications/main/ibutton/application.fam +++ b/applications/main/ibutton/application.fam @@ -17,5 +17,6 @@ App( apptype=FlipperAppType.STARTUP, targets=["f7"], entry_point="ibutton_on_system_start", + sources=["ibutton_cli.c"], order=60, ) diff --git a/applications/main/ibutton/ibutton.c b/applications/main/ibutton/ibutton.c index 760918097..fb6d9dcb5 100644 --- a/applications/main/ibutton/ibutton.c +++ b/applications/main/ibutton/ibutton.c @@ -39,21 +39,23 @@ static void ibutton_make_app_folder(iButton* ibutton) { furi_record_close(RECORD_STORAGE); } -static void ibutton_rpc_command_callback(RpcAppSystemEvent event, void* context) { +static void ibutton_rpc_command_callback(const RpcAppSystemEvent* event, void* context) { furi_assert(context); iButton* ibutton = context; - if(event == RpcAppEventSessionClose) { + if(event->type == RpcAppEventTypeSessionClose) { view_dispatcher_send_custom_event( ibutton->view_dispatcher, iButtonCustomEventRpcSessionClose); rpc_system_app_set_callback(ibutton->rpc, NULL, NULL); ibutton->rpc = NULL; - } else if(event == RpcAppEventAppExit) { + } else if(event->type == RpcAppEventTypeAppExit) { view_dispatcher_send_custom_event(ibutton->view_dispatcher, iButtonCustomEventRpcExit); - } else if(event == RpcAppEventLoadFile) { - view_dispatcher_send_custom_event(ibutton->view_dispatcher, iButtonCustomEventRpcLoad); + } else if(event->type == RpcAppEventTypeLoadFile) { + furi_assert(event->data.type == RpcAppSystemEventDataTypeString); + furi_string_set(ibutton->file_path, event->data.string); + view_dispatcher_send_custom_event(ibutton->view_dispatcher, iButtonCustomEventRpcLoadFile); } else { - rpc_system_app_confirm(ibutton->rpc, event, false); + rpc_system_app_confirm(ibutton->rpc, false); } } diff --git a/applications/main/ibutton/ibutton_custom_event.h b/applications/main/ibutton/ibutton_custom_event.h index 28bcb94a0..b0246d310 100644 --- a/applications/main/ibutton/ibutton_custom_event.h +++ b/applications/main/ibutton/ibutton_custom_event.h @@ -1,6 +1,6 @@ #pragma once -enum iButtonCustomEvent { +typedef enum { // Reserve first 100 events for button types and indexes, starting from 0 iButtonCustomEventReserved = 100, @@ -10,8 +10,12 @@ enum iButtonCustomEvent { iButtonCustomEventByteEditResult, iButtonCustomEventWorkerEmulated, iButtonCustomEventWorkerRead, + iButtonCustomEventWorkerWriteOK, + iButtonCustomEventWorkerWriteSameKey, + iButtonCustomEventWorkerWriteNoDetect, + iButtonCustomEventWorkerWriteCannotWrite, - iButtonCustomEventRpcLoad, + iButtonCustomEventRpcLoadFile, iButtonCustomEventRpcExit, iButtonCustomEventRpcSessionClose, -}; +} iButtonCustomEvent; diff --git a/applications/main/ibutton/scenes/ibutton_scene_rpc.c b/applications/main/ibutton/scenes/ibutton_scene_rpc.c index 9205eb4b4..7106fefaa 100644 --- a/applications/main/ibutton/scenes/ibutton_scene_rpc.c +++ b/applications/main/ibutton/scenes/ibutton_scene_rpc.c @@ -23,28 +23,23 @@ bool ibutton_scene_rpc_on_event(void* context, SceneManagerEvent event) { if(event.type == SceneManagerEventTypeCustom) { consumed = true; - if(event.event == iButtonCustomEventRpcLoad) { + if(event.event == iButtonCustomEventRpcLoadFile) { bool result = false; - const char* file_path = rpc_system_app_get_data(ibutton->rpc); - if(file_path && (furi_string_empty(ibutton->file_path))) { - furi_string_set(ibutton->file_path, file_path); + if(ibutton_load_key(ibutton)) { + popup_set_text(popup, ibutton->key_name, 82, 32, AlignCenter, AlignTop); + view_dispatcher_switch_to_view(ibutton->view_dispatcher, iButtonViewPopup); - if(ibutton_load_key(ibutton)) { - popup_set_text(popup, ibutton->key_name, 82, 32, AlignCenter, AlignTop); - view_dispatcher_switch_to_view(ibutton->view_dispatcher, iButtonViewPopup); + ibutton_notification_message(ibutton, iButtonNotificationMessageEmulateStart); + ibutton_worker_emulate_start(ibutton->worker, ibutton->key); - ibutton_notification_message(ibutton, iButtonNotificationMessageEmulateStart); - ibutton_worker_emulate_start(ibutton->worker, ibutton->key); - - result = true; - } + result = true; } - rpc_system_app_confirm(ibutton->rpc, RpcAppEventLoadFile, result); + rpc_system_app_confirm(ibutton->rpc, result); } else if(event.event == iButtonCustomEventRpcExit) { - rpc_system_app_confirm(ibutton->rpc, RpcAppEventAppExit, true); + rpc_system_app_confirm(ibutton->rpc, true); scene_manager_stop(ibutton->scene_manager); view_dispatcher_stop(ibutton->view_dispatcher); diff --git a/applications/main/ibutton/scenes/ibutton_scene_write.c b/applications/main/ibutton/scenes/ibutton_scene_write.c index 541aa1c52..63be63506 100644 --- a/applications/main/ibutton/scenes/ibutton_scene_write.c +++ b/applications/main/ibutton/scenes/ibutton_scene_write.c @@ -5,9 +5,26 @@ typedef enum { iButtonSceneWriteStateBlinkYellow, } iButtonSceneWriteState; +static inline iButtonCustomEvent + ibutton_scene_write_to_custom_event(iButtonWorkerWriteResult result) { + switch(result) { + case iButtonWorkerWriteOK: + return iButtonCustomEventWorkerWriteOK; + case iButtonWorkerWriteSameKey: + return iButtonCustomEventWorkerWriteSameKey; + case iButtonWorkerWriteNoDetect: + return iButtonCustomEventWorkerWriteNoDetect; + case iButtonWorkerWriteCannotWrite: + return iButtonCustomEventWorkerWriteCannotWrite; + default: + furi_crash(); + } +} + static void ibutton_scene_write_callback(void* context, iButtonWorkerWriteResult result) { iButton* ibutton = context; - view_dispatcher_send_custom_event(ibutton->view_dispatcher, result); + view_dispatcher_send_custom_event( + ibutton->view_dispatcher, ibutton_scene_write_to_custom_event(result)); } void ibutton_scene_write_on_enter(void* context) { @@ -61,16 +78,14 @@ bool ibutton_scene_write_on_event(void* context, SceneManagerEvent event) { if(event.type == SceneManagerEventTypeCustom) { consumed = true; - if((event.event == iButtonWorkerWriteOK) || (event.event == iButtonWorkerWriteSameKey)) { + if((event.event == iButtonCustomEventWorkerWriteOK) || + (event.event == iButtonCustomEventWorkerWriteSameKey)) { scene_manager_next_scene(scene_manager, iButtonSceneWriteSuccess); - } else if(event.event == iButtonWorkerWriteNoDetect) { + } else if(event.event == iButtonCustomEventWorkerWriteNoDetect) { ibutton_notification_message(ibutton, iButtonNotificationMessageEmulateBlink); - } else if(event.event == iButtonWorkerWriteCannotWrite) { + } else if(event.event == iButtonCustomEventWorkerWriteCannotWrite) { ibutton_notification_message(ibutton, iButtonNotificationMessageYellowBlink); } - - } else if(event.type == SceneManagerEventTypeTick) { - consumed = true; } return consumed; diff --git a/applications/main/infrared/application.fam b/applications/main/infrared/application.fam index b78b088a7..575bebbe4 100644 --- a/applications/main/infrared/application.fam +++ b/applications/main/infrared/application.fam @@ -7,6 +7,8 @@ App( icon="A_Infrared_14", stack_size=3 * 1024, order=40, + sources=["*.c", "!infrared_cli.c"], + resources="resources", fap_libs=["assets"], fap_icon="icon.png", fap_category="Infrared", @@ -17,5 +19,10 @@ App( apptype=FlipperAppType.STARTUP, targets=["f7"], entry_point="infrared_on_system_start", + sources=[ + "infrared_cli.c", + "infrared_brute_force.c", + "infrared_signal.c", + ], order=20, ) diff --git a/applications/main/infrared/infrared.h b/applications/main/infrared/infrared.h deleted file mode 100644 index e5eeb1177..000000000 --- a/applications/main/infrared/infrared.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -typedef struct Infrared Infrared; diff --git a/applications/main/infrared/infrared.c b/applications/main/infrared/infrared_app.c similarity index 68% rename from applications/main/infrared/infrared.c rename to applications/main/infrared/infrared_app.c index 9c31a15fc..6af3e7c92 100644 --- a/applications/main/infrared/infrared.c +++ b/applications/main/infrared/infrared_app.c @@ -1,69 +1,85 @@ -#include "infrared_i.h" +#include "infrared_app_i.h" #include +#include #include +#define TAG "InfraredApp" + #define INFRARED_TX_MIN_INTERVAL_MS 50U -static const NotificationSequence* infrared_notification_sequences[] = { - &sequence_success, - &sequence_set_only_green_255, - &sequence_reset_green, - &sequence_solid_yellow, - &sequence_reset_rgb, - &sequence_blink_start_cyan, - &sequence_blink_start_magenta, - &sequence_blink_stop, +static const NotificationSequence* + infrared_notification_sequences[InfraredNotificationMessageCount] = { + &sequence_success, + &sequence_set_only_green_255, + &sequence_reset_green, + &sequence_solid_yellow, + &sequence_reset_rgb, + &sequence_blink_start_cyan, + &sequence_blink_start_magenta, + &sequence_blink_stop, }; -static void infrared_make_app_folder(Infrared* infrared) { +static void infrared_make_app_folder(InfraredApp* infrared) { if(!storage_simply_mkdir(infrared->storage, INFRARED_APP_FOLDER)) { - dialog_message_show_storage_error(infrared->dialogs, "Cannot create\napp folder"); + infrared_show_error_message(infrared, "Cannot create\napp folder"); } } static bool infrared_custom_event_callback(void* context, uint32_t event) { furi_assert(context); - Infrared* infrared = context; + InfraredApp* infrared = context; return scene_manager_handle_custom_event(infrared->scene_manager, event); } static bool infrared_back_event_callback(void* context) { furi_assert(context); - Infrared* infrared = context; + InfraredApp* infrared = context; return scene_manager_handle_back_event(infrared->scene_manager); } static void infrared_tick_event_callback(void* context) { furi_assert(context); - Infrared* infrared = context; + InfraredApp* infrared = context; scene_manager_handle_tick_event(infrared->scene_manager); } -static void infrared_rpc_command_callback(RpcAppSystemEvent event, void* context) { +static void infrared_rpc_command_callback(const RpcAppSystemEvent* event, void* context) { furi_assert(context); - Infrared* infrared = context; + InfraredApp* infrared = context; furi_assert(infrared->rpc_ctx); - if(event == RpcAppEventSessionClose) { + if(event->type == RpcAppEventTypeSessionClose) { view_dispatcher_send_custom_event( infrared->view_dispatcher, InfraredCustomEventTypeRpcSessionClose); rpc_system_app_set_callback(infrared->rpc_ctx, NULL, NULL); infrared->rpc_ctx = NULL; - } else if(event == RpcAppEventAppExit) { + } else if(event->type == RpcAppEventTypeAppExit) { view_dispatcher_send_custom_event( infrared->view_dispatcher, InfraredCustomEventTypeRpcExit); - } else if(event == RpcAppEventLoadFile) { + } else if(event->type == RpcAppEventTypeLoadFile) { + furi_assert(event->data.type == RpcAppSystemEventDataTypeString); + furi_string_set(infrared->file_path, event->data.string); view_dispatcher_send_custom_event( - infrared->view_dispatcher, InfraredCustomEventTypeRpcLoad); - } else if(event == RpcAppEventButtonPress) { - view_dispatcher_send_custom_event( - infrared->view_dispatcher, InfraredCustomEventTypeRpcButtonPress); - } else if(event == RpcAppEventButtonRelease) { + infrared->view_dispatcher, InfraredCustomEventTypeRpcLoadFile); + } else if(event->type == RpcAppEventTypeButtonPress) { + furi_assert( + event->data.type == RpcAppSystemEventDataTypeString || + event->data.type == RpcAppSystemEventDataTypeInt32); + if(event->data.type == RpcAppSystemEventDataTypeString) { + furi_string_set(infrared->button_name, event->data.string); + view_dispatcher_send_custom_event( + infrared->view_dispatcher, InfraredCustomEventTypeRpcButtonPressName); + } else { + infrared->app_state.current_button_index = event->data.i32; + view_dispatcher_send_custom_event( + infrared->view_dispatcher, InfraredCustomEventTypeRpcButtonPressIndex); + } + } else if(event->type == RpcAppEventTypeButtonRelease) { view_dispatcher_send_custom_event( infrared->view_dispatcher, InfraredCustomEventTypeRpcButtonRelease); } else { - rpc_system_app_confirm(infrared->rpc_ctx, event, false); + rpc_system_app_confirm(infrared->rpc_ctx, false); } } @@ -109,10 +125,11 @@ static void infrared_find_vacant_remote_name(FuriString* name, const char* path) furi_record_close(RECORD_STORAGE); } -static Infrared* infrared_alloc() { - Infrared* infrared = malloc(sizeof(Infrared)); +static InfraredApp* infrared_alloc() { + InfraredApp* infrared = malloc(sizeof(InfraredApp)); infrared->file_path = furi_string_alloc(); + infrared->button_name = furi_string_alloc(); InfraredAppState* app_state = &infrared->app_state; app_state->is_learning_new_remote = false; @@ -139,7 +156,7 @@ static Infrared* infrared_alloc() { infrared->worker = infrared_worker_alloc(); infrared->remote = infrared_remote_alloc(); - infrared->received_signal = infrared_signal_alloc(); + infrared->current_signal = infrared_signal_alloc(); infrared->brute_force = infrared_brute_force_alloc(); infrared->submenu = submenu_alloc(); @@ -150,16 +167,16 @@ static Infrared* infrared_alloc() { view_dispatcher_add_view( view_dispatcher, InfraredViewTextInput, text_input_get_view(infrared->text_input)); + infrared->dialog_ex = dialog_ex_alloc(); + view_dispatcher_add_view( + view_dispatcher, InfraredViewDialogEx, dialog_ex_get_view(infrared->dialog_ex)); + infrared->variable_item_list = variable_item_list_alloc(); view_dispatcher_add_view( infrared->view_dispatcher, InfraredViewVariableItemList, variable_item_list_get_view(infrared->variable_item_list)); - infrared->dialog_ex = dialog_ex_alloc(); - view_dispatcher_add_view( - view_dispatcher, InfraredViewDialogEx, dialog_ex_get_view(infrared->dialog_ex)); - infrared->button_menu = button_menu_alloc(); view_dispatcher_add_view( view_dispatcher, InfraredViewButtonMenu, button_menu_get_view(infrared->button_menu)); @@ -190,7 +207,7 @@ static Infrared* infrared_alloc() { return infrared; } -static void infrared_free(Infrared* infrared) { +static void infrared_free(InfraredApp* infrared) { furi_assert(infrared); ViewDispatcher* view_dispatcher = infrared->view_dispatcher; InfraredAppState* app_state = &infrared->app_state; @@ -207,12 +224,12 @@ static void infrared_free(Infrared* infrared) { view_dispatcher_remove_view(view_dispatcher, InfraredViewTextInput); text_input_free(infrared->text_input); - view_dispatcher_remove_view(infrared->view_dispatcher, InfraredViewVariableItemList); - variable_item_list_free(infrared->variable_item_list); - view_dispatcher_remove_view(view_dispatcher, InfraredViewDialogEx); dialog_ex_free(infrared->dialog_ex); + view_dispatcher_remove_view(infrared->view_dispatcher, InfraredViewVariableItemList); + variable_item_list_free(infrared->variable_item_list); + view_dispatcher_remove_view(view_dispatcher, InfraredViewButtonMenu); button_menu_free(infrared->button_menu); @@ -238,7 +255,7 @@ static void infrared_free(Infrared* infrared) { scene_manager_free(infrared->scene_manager); infrared_brute_force_free(infrared->brute_force); - infrared_signal_free(infrared->received_signal); + infrared_signal_free(infrared->current_signal); infrared_remote_free(infrared->remote); infrared_worker_free(infrared->worker); @@ -252,75 +269,67 @@ static void infrared_free(Infrared* infrared) { infrared->gui = NULL; furi_string_free(infrared->file_path); - - // Disable 5v power if was enabled for external module - if(furi_hal_power_is_otg_enabled()) { - furi_hal_power_disable_otg(); - } + furi_string_free(infrared->button_name); free(infrared); } bool infrared_add_remote_with_button( - Infrared* infrared, + const InfraredApp* infrared, const char* button_name, - InfraredSignal* signal) { + const InfraredSignal* signal) { InfraredRemote* remote = infrared->remote; - FuriString *new_name, *new_path; - new_name = furi_string_alloc_set(INFRARED_DEFAULT_REMOTE_NAME); - new_path = furi_string_alloc_set(INFRARED_APP_FOLDER); + FuriString* new_name = furi_string_alloc_set(INFRARED_DEFAULT_REMOTE_NAME); + FuriString* new_path = furi_string_alloc_set(INFRARED_APP_FOLDER); infrared_find_vacant_remote_name(new_name, furi_string_get_cstr(new_path)); furi_string_cat_printf( new_path, "/%s%s", furi_string_get_cstr(new_name), INFRARED_APP_EXTENSION); - infrared_remote_reset(remote); - infrared_remote_set_name(remote, furi_string_get_cstr(new_name)); - infrared_remote_set_path(remote, furi_string_get_cstr(new_path)); + bool success = false; + + do { + if(!infrared_remote_create(remote, furi_string_get_cstr(new_path))) break; + if(!infrared_remote_append_signal(remote, signal, button_name)) break; + success = true; + } while(false); furi_string_free(new_name); furi_string_free(new_path); - return infrared_remote_add_button(remote, button_name, signal); + + return success; } -bool infrared_rename_current_remote(Infrared* infrared, const char* name) { +bool infrared_rename_current_remote(const InfraredApp* infrared, const char* new_name) { InfraredRemote* remote = infrared->remote; - const char* remote_path = infrared_remote_get_path(remote); + const char* old_path = infrared_remote_get_path(remote); - if(!strcmp(infrared_remote_get_name(remote), name)) { + if(!strcmp(infrared_remote_get_name(remote), new_name)) { return true; } - FuriString* new_name; - new_name = furi_string_alloc_set(name); + FuriString* new_name_fstr = furi_string_alloc_set(new_name); + FuriString* new_path_fstr = furi_string_alloc_set(old_path); - infrared_find_vacant_remote_name(new_name, remote_path); + infrared_find_vacant_remote_name(new_name_fstr, old_path); - FuriString* new_path; - new_path = furi_string_alloc_set(infrared_remote_get_path(remote)); - if(furi_string_end_with(new_path, INFRARED_APP_EXTENSION)) { - size_t filename_start = furi_string_search_rchar(new_path, '/'); - furi_string_left(new_path, filename_start); + if(furi_string_end_with(new_path_fstr, INFRARED_APP_EXTENSION)) { + path_extract_dirname(old_path, new_path_fstr); } - furi_string_cat_printf( - new_path, "/%s%s", furi_string_get_cstr(new_name), INFRARED_APP_EXTENSION); - Storage* storage = furi_record_open(RECORD_STORAGE); + path_append(new_path_fstr, furi_string_get_cstr(new_name_fstr)); + furi_string_cat(new_path_fstr, INFRARED_APP_EXTENSION); - FS_Error status = storage_common_rename( - storage, infrared_remote_get_path(remote), furi_string_get_cstr(new_path)); - infrared_remote_set_name(remote, furi_string_get_cstr(new_name)); - infrared_remote_set_path(remote, furi_string_get_cstr(new_path)); + const bool success = infrared_remote_rename(remote, furi_string_get_cstr(new_path_fstr)); - furi_string_free(new_name); - furi_string_free(new_path); + furi_string_free(new_name_fstr); + furi_string_free(new_path_fstr); - furi_record_close(RECORD_STORAGE); - return (status == FSE_OK || status == FSE_EXIST); + return success; } -void infrared_tx_start_signal(Infrared* infrared, InfraredSignal* signal) { +void infrared_tx_start(InfraredApp* infrared) { if(infrared->app_state.is_transmitting) { return; } @@ -331,12 +340,12 @@ void infrared_tx_start_signal(Infrared* infrared, InfraredSignal* signal) { return; } - if(infrared_signal_is_raw(signal)) { - InfraredRawSignal* raw = infrared_signal_get_raw_signal(signal); + if(infrared_signal_is_raw(infrared->current_signal)) { + const InfraredRawSignal* raw = infrared_signal_get_raw_signal(infrared->current_signal); infrared_worker_set_raw_signal( infrared->worker, raw->timings, raw->timings_size, raw->frequency, raw->duty_cycle); } else { - InfraredMessage* message = infrared_signal_get_message(signal); + const InfraredMessage* message = infrared_signal_get_message(infrared->current_signal); infrared_worker_set_decoded_signal(infrared->worker, message); } @@ -350,20 +359,20 @@ void infrared_tx_start_signal(Infrared* infrared, InfraredSignal* signal) { infrared->app_state.is_transmitting = true; } -void infrared_tx_start_button_index(Infrared* infrared, size_t button_index) { - furi_assert(button_index < infrared_remote_get_button_count(infrared->remote)); +void infrared_tx_start_button_index(InfraredApp* infrared, size_t button_index) { + furi_assert(button_index < infrared_remote_get_signal_count(infrared->remote)); - InfraredRemoteButton* button = infrared_remote_get_button(infrared->remote, button_index); - InfraredSignal* signal = infrared_remote_button_get_signal(button); - - infrared_tx_start_signal(infrared, signal); + if(infrared_remote_load_signal(infrared->remote, infrared->current_signal, button_index)) { + infrared_tx_start(infrared); + } else { + infrared_show_error_message( + infrared, + "Failed to load\n\"%s\"", + infrared_remote_get_signal_name(infrared->remote, button_index)); + } } -void infrared_tx_start_received(Infrared* infrared) { - infrared_tx_start_signal(infrared, infrared->received_signal); -} - -void infrared_tx_stop(Infrared* infrared) { +void infrared_tx_stop(InfraredApp* infrared) { if(!infrared->app_state.is_transmitting) { return; } @@ -377,53 +386,65 @@ void infrared_tx_stop(Infrared* infrared) { infrared->app_state.last_transmit_time = furi_get_tick(); } -void infrared_text_store_set(Infrared* infrared, uint32_t bank, const char* text, ...) { +void infrared_text_store_set(InfraredApp* infrared, uint32_t bank, const char* fmt, ...) { va_list args; - va_start(args, text); + va_start(args, fmt); - vsnprintf(infrared->text_store[bank], INFRARED_TEXT_STORE_SIZE, text, args); + vsnprintf(infrared->text_store[bank], INFRARED_TEXT_STORE_SIZE, fmt, args); va_end(args); } -void infrared_text_store_clear(Infrared* infrared, uint32_t bank) { +void infrared_text_store_clear(InfraredApp* infrared, uint32_t bank) { memset(infrared->text_store[bank], 0, INFRARED_TEXT_STORE_SIZE + 1); } -void infrared_play_notification_message(Infrared* infrared, uint32_t message) { - furi_assert(message < sizeof(infrared_notification_sequences) / sizeof(NotificationSequence*)); +void infrared_play_notification_message( + const InfraredApp* infrared, + InfraredNotificationMessage message) { + furi_assert(message < InfraredNotificationMessageCount); notification_message(infrared->notifications, infrared_notification_sequences[message]); } -void infrared_show_loading_popup(Infrared* infrared, bool show) { - TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME); +void infrared_show_loading_popup(const InfraredApp* infrared, bool show) { ViewStack* view_stack = infrared->view_stack; Loading* loading = infrared->loading; if(show) { // Raise timer priority so that animations can play - vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1); + furi_timer_set_thread_priority(FuriTimerThreadPriorityElevated); view_stack_add_view(view_stack, loading_get_view(loading)); } else { view_stack_remove_view(view_stack, loading_get_view(loading)); // Restore default timer priority - vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY); + furi_timer_set_thread_priority(FuriTimerThreadPriorityNormal); } } +void infrared_show_error_message(const InfraredApp* infrared, const char* fmt, ...) { + va_list args; + va_start(args, fmt); + + FuriString* message = furi_string_alloc_vprintf(fmt, args); + dialog_message_show_storage_error(infrared->dialogs, furi_string_get_cstr(message)); + + furi_string_free(message); + va_end(args); +} + void infrared_signal_received_callback(void* context, InfraredWorkerSignal* received_signal) { furi_assert(context); - Infrared* infrared = context; + InfraredApp* infrared = context; if(infrared_worker_signal_is_decoded(received_signal)) { infrared_signal_set_message( - infrared->received_signal, infrared_worker_get_decoded_signal(received_signal)); + infrared->current_signal, infrared_worker_get_decoded_signal(received_signal)); } else { const uint32_t* timings; size_t timings_size; infrared_worker_get_raw_signal(received_signal, &timings, &timings_size); infrared_signal_set_raw_signal( - infrared->received_signal, + infrared->current_signal, timings, timings_size, INFRARED_COMMON_CARRIER_FREQUENCY, @@ -436,20 +457,20 @@ void infrared_signal_received_callback(void* context, InfraredWorkerSignal* rece void infrared_text_input_callback(void* context) { furi_assert(context); - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event( infrared->view_dispatcher, InfraredCustomEventTypeTextEditDone); } void infrared_popup_closed_callback(void* context) { furi_assert(context); - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event( infrared->view_dispatcher, InfraredCustomEventTypePopupClosed); } int32_t infrared_app(void* p) { - Infrared* infrared = infrared_alloc(); + InfraredApp* infrared = infrared_alloc(); infrared_make_app_folder(infrared); @@ -465,13 +486,15 @@ int32_t infrared_app(void* p) { rpc_system_app_send_started(infrared->rpc_ctx); is_rpc_mode = true; } else { - furi_string_set(infrared->file_path, (const char*)p); - is_remote_loaded = infrared_remote_load(infrared->remote, infrared->file_path); + const char* file_path = (const char*)p; + is_remote_loaded = infrared_remote_load(infrared->remote, file_path); + if(!is_remote_loaded) { - dialog_message_show_storage_error( - infrared->dialogs, "Failed to load\nselected remote"); + infrared_show_error_message(infrared, "Failed to load\n\"%s\"", file_path); return -1; } + + furi_string_set(infrared->file_path, file_path); } } diff --git a/applications/main/infrared/infrared_app.h b/applications/main/infrared/infrared_app.h new file mode 100644 index 000000000..a6f87402a --- /dev/null +++ b/applications/main/infrared/infrared_app.h @@ -0,0 +1,15 @@ +/** + * @file infrared_app.h + * @brief Infrared application - start here. + * + * @see infrared_app_i.h for the main application data structure and functions. + * @see infrared_signal.h for the infrared signal library - loading, storing and transmitting signals. + * @see infrared_remote.hl for the infrared remote library - loading, storing and manipulating remotes. + * @see infrared_brute_force.h for the infrared brute force - loading and transmitting multiple signals. + */ +#pragma once + +/** + * @brief InfraredApp opaque type declaration. + */ +typedef struct InfraredApp InfraredApp; diff --git a/applications/main/infrared/infrared_app_i.h b/applications/main/infrared/infrared_app_i.h new file mode 100644 index 000000000..354e6ca65 --- /dev/null +++ b/applications/main/infrared/infrared_app_i.h @@ -0,0 +1,292 @@ +/** + * @file infrared_app_i.h + * @brief Main Infrared application types and functions. + */ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include + +#include "infrared_app.h" +#include "infrared_remote.h" +#include "infrared_brute_force.h" +#include "infrared_custom_event.h" + +#include "scenes/infrared_scene.h" +#include "views/infrared_progress_view.h" +#include "views/infrared_debug_view.h" +#include "views/infrared_move_view.h" + +#include "rpc/rpc_app.h" + +#define INFRARED_FILE_NAME_SIZE 100 +#define INFRARED_TEXT_STORE_NUM 2 +#define INFRARED_TEXT_STORE_SIZE 128 + +#define INFRARED_MAX_BUTTON_NAME_LENGTH 22 +#define INFRARED_MAX_REMOTE_NAME_LENGTH 22 + +#define INFRARED_APP_FOLDER ANY_PATH("infrared") +#define INFRARED_APP_EXTENSION ".ir" + +#define INFRARED_DEFAULT_REMOTE_NAME "Remote" +#define INFRARED_LOG_TAG "InfraredApp" + +/** + * @brief Enumeration of invalid remote button indices. + */ +typedef enum { + InfraredButtonIndexNone = -1, /**< No button is currently selected. */ +} InfraredButtonIndex; + +/** + * @brief Enumeration of editing targets. + */ +typedef enum { + InfraredEditTargetNone, /**< No editing target is selected. */ + InfraredEditTargetRemote, /**< Whole remote is selected as editing target. */ + InfraredEditTargetButton, /**< Single button is selected as editing target. */ +} InfraredEditTarget; + +/** + * @brief Enumeration of editing modes. + */ +typedef enum { + InfraredEditModeNone, /**< No editing mode is selected. */ + InfraredEditModeRename, /**< Rename mode is selected. */ + InfraredEditModeDelete, /**< Delete mode is selected. */ +} InfraredEditMode; + +/** + * @brief Infrared application state type. + */ +typedef struct { + bool is_learning_new_remote; /**< Learning new remote or adding to an existing one. */ + bool is_debug_enabled; /**< Whether to enable or disable debugging features. */ + bool is_transmitting; /**< Whether a signal is currently being transmitted. */ + InfraredEditTarget edit_target : 8; /**< Selected editing target (a remote or a button). */ + InfraredEditMode edit_mode : 8; /**< Selected editing operation (rename or delete). */ + int32_t current_button_index; /**< Selected button index (move destination). */ + int32_t prev_button_index; /**< Previous button index (move source). */ + uint32_t last_transmit_time; /**< Lat time a signal was transmitted. */ +} InfraredAppState; + +/** + * @brief Infrared application type. + */ +struct InfraredApp { + SceneManager* scene_manager; /**< Pointer to a SceneManager instance. */ + ViewDispatcher* view_dispatcher; /**< Pointer to a ViewDispatcher instance. */ + + Gui* gui; /**< Pointer to a Gui instance. */ + Storage* storage; /**< Pointer to a Storage instance. */ + DialogsApp* dialogs; /**< Pointer to a DialogsApp instance. */ + NotificationApp* notifications; /**< Pointer to a NotificationApp instance. */ + InfraredWorker* worker; /**< Used to send or receive signals. */ + InfraredRemote* remote; /**< Holds the currently loaded remote. */ + InfraredSignal* current_signal; /**< Holds the currently loaded signal. */ + InfraredBruteForce* brute_force; /**< Used for the Universal Remote feature. */ + + Submenu* submenu; /**< Standard view for displaying application menus. */ + TextInput* text_input; /**< Standard view for receiving user text input. */ + DialogEx* dialog_ex; /**< Standard view for displaying dialogs. */ + ButtonMenu* button_menu; /**< Custom view for interacting with IR remotes. */ + Popup* popup; /**< Standard view for displaying messages. */ + VariableItemList* variable_item_list; + + ViewStack* view_stack; /**< Standard view for displaying stacked interfaces. */ + InfraredDebugView* debug_view; /**< Custom view for displaying debug information. */ + InfraredMoveView* move_view; /**< Custom view for rearranging buttons in a remote. */ + + ButtonPanel* button_panel; /**< Standard view for displaying control panels. */ + Loading* loading; /**< Standard view for informing about long operations. */ + InfraredProgressView* progress; /**< Custom view for showing brute force progress. */ + + FuriString* file_path; /**< Full path to the currently loaded file. */ + FuriString* button_name; /** Name of the button requested in RPC mode. */ + /** Arbitrary text storage for various inputs. */ + char text_store[INFRARED_TEXT_STORE_NUM][INFRARED_TEXT_STORE_SIZE + 1]; + InfraredAppState app_state; /**< Application state. */ + + void* rpc_ctx; /**< Pointer to the RPC context object. */ +}; + +/** + * @brief Enumeration of all used view types. + */ +typedef enum { + InfraredViewSubmenu, + InfraredViewTextInput, + InfraredViewDialogEx, + InfraredViewButtonMenu, + InfraredViewPopup, + InfraredViewStack, + InfraredViewDebugView, + InfraredViewMove, + InfraredViewVariableItemList, +} InfraredView; + +/** + * @brief Enumeration of all notification message types. + */ +typedef enum { + InfraredNotificationMessageSuccess, /**< Play a short happy tune. */ + InfraredNotificationMessageGreenOn, /**< Turn green LED on. */ + InfraredNotificationMessageGreenOff, /**< Turn green LED off. */ + InfraredNotificationMessageYellowOn, /**< Turn yellow LED on. */ + InfraredNotificationMessageYellowOff, /**< Turn yellow LED off. */ + InfraredNotificationMessageBlinkStartRead, /**< Blink the LED to indicate receiver mode. */ + InfraredNotificationMessageBlinkStartSend, /**< Blink the LED to indicate transmitter mode. */ + InfraredNotificationMessageBlinkStop, /**< Stop blinking the LED. */ + InfraredNotificationMessageCount, /**< Special value equal to the message type count. */ +} InfraredNotificationMessage; + +/** + * @brief Add a new remote with a single signal. + * + * The filename will be automatically generated depending on + * the names and number of other files in the infrared data directory. + * + * @param[in] infrared pointer to the application instance. + * @param[in] name pointer to a zero-terminated string containing the signal name. + * @param[in] signal pointer to the signal to be added. + * @return true if the remote was successfully created, false otherwise. + */ +bool infrared_add_remote_with_button( + const InfraredApp* infrared, + const char* name, + const InfraredSignal* signal); + +/** + * @brief Rename the currently loaded remote. + * + * @param[in] infrared pointer to the application instance. + * @param[in] new_name pointer to a zero-terminated string containing the new remote name. + * @return true if the remote was successfully renamed, false otherwise. + */ +bool infrared_rename_current_remote(const InfraredApp* infrared, const char* new_name); + +/** + * @brief Begin transmission of the currently loaded signal. + * + * The signal will be repeated indefinitely until stopped. + * + * @param[in,out] infrared pointer to the application instance. + */ +void infrared_tx_start(InfraredApp* infrared); + +/** + * @brief Load a signal under the given index and begin transmission. + * + * The signal will be repeated indefinitely until stopped. + * + * @param[in,out] infrared pointer to the application instance. + * @param[in] button_index index of the signal to be loaded. + * @returns true if the signal could be loaded, false otherwise. + */ +void infrared_tx_start_button_index(InfraredApp* infrared, size_t button_index); + +/** + * @brief Stop transmission of the currently loaded signal. + * + * @param[in,out] infrared pointer to the application instance. + */ +void infrared_tx_stop(InfraredApp* infrared); + +/** + * @brief Set the internal text store with formatted text. + * + * @param[in,out] infrared pointer to the application instance. + * @param[in] bank index of text store bank (0 or 1). + * @param[in] fmt pointer to a zero-terminated string containing the format text. + * @param[in] ... additional arguments. + */ +void infrared_text_store_set(InfraredApp* infrared, uint32_t bank, const char* fmt, ...) + _ATTRIBUTE((__format__(__printf__, 3, 4))); + +/** + * @brief Clear the internal text store. + * + * @param[in,out] infrared pointer to the application instance. + * @param[in] bank index of text store bank (0 or 1). + */ +void infrared_text_store_clear(InfraredApp* infrared, uint32_t bank); + +/** + * @brief Play a sound and/or blink the LED. + * + * @param[in] infrared pointer to the application instance. + * @param[in] message type of the message to play. + */ +void infrared_play_notification_message( + const InfraredApp* infrared, + InfraredNotificationMessage message); + +/** + * @brief Show a loading pop-up screen. + * + * In order for this to work, a Stack view must be currently active and + * the main view must be added to it. + * + * @param[in] infrared pointer to the application instance. + * @param[in] show whether to show or hide the pop-up. + */ +void infrared_show_loading_popup(const InfraredApp* infrared, bool show); + +/** + * @brief Show a formatted error messsage. + * + * @param[in] infrared pointer to the application instance. + * @param[in] fmt pointer to a zero-terminated string containing the format text. + * @param[in] ... additional arguments. + */ +void infrared_show_error_message(const InfraredApp* infrared, const char* fmt, ...) + _ATTRIBUTE((__format__(__printf__, 2, 3))); + +/** + * @brief Common received signal callback. + * + * Called when the worker has received a complete infrared signal. + * + * @param[in,out] context pointer to the user-specified context object. + * @param[in] received_signal pointer to the received signal. + */ +void infrared_signal_received_callback(void* context, InfraredWorkerSignal* received_signal); + +/** + * @brief Common text input callback. + * + * Called when the input has been accepted by the user. + * + * @param[in,out] context pointer to the user-specified context object. + */ +void infrared_text_input_callback(void* context); + +/** + * @brief Common popup close callback. + * + * Called when the popup has been closed either by the user or after a timeout. + * + * @param[in,out] context pointer to the user-specified context object. + */ +void infrared_popup_closed_callback(void* context); diff --git a/applications/main/infrared/infrared_brute_force.c b/applications/main/infrared/infrared_brute_force.c index 3ca5c409f..373c7270f 100644 --- a/applications/main/infrared/infrared_brute_force.c +++ b/applications/main/infrared/infrared_brute_force.c @@ -111,7 +111,7 @@ bool infrared_brute_force_start( return success; } -bool infrared_brute_force_is_started(InfraredBruteForce* brute_force) { +bool infrared_brute_force_is_started(const InfraredBruteForce* brute_force) { return brute_force->is_started; } @@ -128,8 +128,10 @@ void infrared_brute_force_stop(InfraredBruteForce* brute_force) { bool infrared_brute_force_send_next(InfraredBruteForce* brute_force) { furi_assert(brute_force->is_started); - const bool success = infrared_signal_search_and_read( - brute_force->current_signal, brute_force->ff, brute_force->current_record_name); + const bool success = infrared_signal_search_by_name_and_read( + brute_force->current_signal, + brute_force->ff, + furi_string_get_cstr(brute_force->current_record_name)); if(success) { infrared_signal_transmit(brute_force->current_signal); } diff --git a/applications/main/infrared/infrared_brute_force.h b/applications/main/infrared/infrared_brute_force.h index b6c48e3f6..33677d2ec 100644 --- a/applications/main/infrared/infrared_brute_force.h +++ b/applications/main/infrared/infrared_brute_force.h @@ -1,23 +1,110 @@ +/** + * @file infrared_brute_force.h + * @brief Infrared signal brute-forcing library. + * + * The BruteForce library is used to send large quantities of signals, + * sorted by a category. It is used to implement the Universal Remote + * feature. + */ #pragma once #include #include +/** + * @brief InfraredBruteForce opaque type declaration. + */ typedef struct InfraredBruteForce InfraredBruteForce; +/** + * @brief Create a new InfraredBruteForce instance. + * + * @returns pointer to the created instance. + */ InfraredBruteForce* infrared_brute_force_alloc(); + +/** + * @brief Delete an InfraredBruteForce instance. + * + * @param[in,out] brute_force pointer to the instance to be deleted. + */ void infrared_brute_force_free(InfraredBruteForce* brute_force); + +/** + * @brief Set an InfraredBruteForce instance to use a signal database contained in a file. + * + * @param[in,out] brute_force pointer to the instance to be configured. + * @param[in] db_filename pointer to a zero-terminated string containing a full path to the database file. + */ void infrared_brute_force_set_db_filename(InfraredBruteForce* brute_force, const char* db_filename); + +/** + * @brief Build a signal dictionary from a previously set database file. + * + * This function must be called each time after setting the database via + * a infrared_brute_force_set_db_filename() call. + * + * @param[in,out] brute_force pointer to the instance to be updated. + * @returns true on success, false otherwise. + */ bool infrared_brute_force_calculate_messages(InfraredBruteForce* brute_force); + +/** + * @brief Start transmitting signals from a category stored in an InfraredBruteForce's instance dictionary. + * + * @param[in,out] brute_force pointer to the instance to be started. + * @param[in] index index of the signal category in the dictionary. + * @returns true on success, false otherwise. + */ bool infrared_brute_force_start( InfraredBruteForce* brute_force, uint32_t index, uint32_t* record_count); -bool infrared_brute_force_is_started(InfraredBruteForce* brute_force); + +/** + * @brief Determine whether the transmission was started. + * + * @param[in] brute_force pointer to the instance to be tested. + * @returns true if transmission was started, false otherwise. + */ +bool infrared_brute_force_is_started(const InfraredBruteForce* brute_force); + +/** + * @brief Stop transmitting the signals. + * + * @param[in] brute_force pointer to the instance to be stopped. + */ void infrared_brute_force_stop(InfraredBruteForce* brute_force); + +/** + * @brief Send the next signal from the chosen category. + * + * This function is called repeatedly until no more signals are left + * in the chosen signal category. + * + * @warning Transmission must be started first by calling infrared_brute_force_start() + * before calling this function. + * + * @param[in,out] brute_force pointer to the instance to be used. + * @returns true if the next signal existed and could be transmitted, false otherwise. + */ bool infrared_brute_force_send_next(InfraredBruteForce* brute_force); -void infrared_brute_force_reset(InfraredBruteForce* brute_force); + +/** + * @brief Add a signal category to an InfraredBruteForce instance's dictionary. + * + * @param[in,out] brute_force pointer to the instance to be updated. + * @param[in] index index of the category to be added. + * @param[in] name name of the category to be added. + */ void infrared_brute_force_add_record( InfraredBruteForce* brute_force, uint32_t index, const char* name); + +/** + * @brief Reset an InfraredBruteForce instance. + * + * @param[in,out] brute_force pointer to the instance to be reset. + */ +void infrared_brute_force_reset(InfraredBruteForce* brute_force); diff --git a/applications/main/infrared/infrared_cli.c b/applications/main/infrared/infrared_cli.c index 54b5cabab..c960ffa28 100644 --- a/applications/main/infrared/infrared_cli.c +++ b/applications/main/infrared/infrared_cli.c @@ -202,7 +202,7 @@ static bool } static bool infrared_cli_decode_raw_signal( - InfraredRawSignal* raw_signal, + const InfraredRawSignal* raw_signal, InfraredDecoderHandler* decoder, FlipperFormat* output_file, const char* signal_name) { @@ -274,7 +274,7 @@ static bool infrared_cli_decode_file(FlipperFormat* input_file, FlipperFormat* o continue; } } - InfraredRawSignal* raw_signal = infrared_signal_get_raw_signal(signal); + const InfraredRawSignal* raw_signal = infrared_signal_get_raw_signal(signal); printf( "Raw signal: %s, %zu samples\r\n", furi_string_get_cstr(tmp), diff --git a/applications/main/infrared/infrared_custom_event.h b/applications/main/infrared/infrared_custom_event.h index 09440ddec..30bb0f729 100644 --- a/applications/main/infrared/infrared_custom_event.h +++ b/applications/main/infrared/infrared_custom_event.h @@ -15,9 +15,10 @@ enum InfraredCustomEventType { InfraredCustomEventTypeButtonSelected, InfraredCustomEventTypeBackPressed, - InfraredCustomEventTypeRpcLoad, + InfraredCustomEventTypeRpcLoadFile, InfraredCustomEventTypeRpcExit, - InfraredCustomEventTypeRpcButtonPress, + InfraredCustomEventTypeRpcButtonPressName, + InfraredCustomEventTypeRpcButtonPressIndex, InfraredCustomEventTypeRpcButtonRelease, InfraredCustomEventTypeRpcSessionClose, }; diff --git a/applications/main/infrared/infrared_i.h b/applications/main/infrared/infrared_i.h deleted file mode 100644 index 4e69b886e..000000000 --- a/applications/main/infrared/infrared_i.h +++ /dev/null @@ -1,149 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -#include - -#include "infrared.h" -#include "infrared_remote.h" -#include "infrared_brute_force.h" -#include "infrared_custom_event.h" - -#include "scenes/infrared_scene.h" -#include "views/infrared_progress_view.h" -#include "views/infrared_debug_view.h" -#include "views/infrared_move_view.h" - -#include "rpc/rpc_app.h" - -#define INFRARED_FILE_NAME_SIZE 100 -#define INFRARED_TEXT_STORE_NUM 2 -#define INFRARED_TEXT_STORE_SIZE 128 - -#define INFRARED_MAX_BUTTON_NAME_LENGTH 22 -#define INFRARED_MAX_REMOTE_NAME_LENGTH 22 - -#define INFRARED_APP_FOLDER ANY_PATH("infrared") -#define INFRARED_APP_EXTENSION ".ir" - -#define INFRARED_DEFAULT_REMOTE_NAME "Remote" -#define INFRARED_LOG_TAG "InfraredApp" - -typedef enum { - InfraredButtonIndexNone = -1, -} InfraredButtonIndex; - -typedef enum { - InfraredEditTargetNone, - InfraredEditTargetRemote, - InfraredEditTargetButton, -} InfraredEditTarget; - -typedef enum { - InfraredEditModeNone, - InfraredEditModeRename, - InfraredEditModeDelete, -} InfraredEditMode; - -typedef struct { - bool is_learning_new_remote; - bool is_debug_enabled; - bool is_transmitting; - InfraredEditTarget edit_target : 8; - InfraredEditMode edit_mode : 8; - int32_t current_button_index; - int32_t current_button_index_move_orig; - uint32_t last_transmit_time; -} InfraredAppState; - -struct Infrared { - SceneManager* scene_manager; - ViewDispatcher* view_dispatcher; - - Gui* gui; - Storage* storage; - DialogsApp* dialogs; - NotificationApp* notifications; - InfraredWorker* worker; - InfraredRemote* remote; - InfraredSignal* received_signal; - InfraredBruteForce* brute_force; - - Submenu* submenu; - TextInput* text_input; - VariableItemList* variable_item_list; - DialogEx* dialog_ex; - ButtonMenu* button_menu; - Popup* popup; - - ViewStack* view_stack; - InfraredDebugView* debug_view; - InfraredMoveView* move_view; - - ButtonPanel* button_panel; - Loading* loading; - InfraredProgressView* progress; - - FuriString* file_path; - char text_store[INFRARED_TEXT_STORE_NUM][INFRARED_TEXT_STORE_SIZE + 1]; - InfraredAppState app_state; - - void* rpc_ctx; -}; - -typedef enum { - InfraredViewSubmenu, - InfraredViewTextInput, - InfraredViewVariableItemList, - InfraredViewDialogEx, - InfraredViewButtonMenu, - InfraredViewPopup, - InfraredViewStack, - InfraredViewDebugView, - InfraredViewMove, -} InfraredView; - -typedef enum { - InfraredNotificationMessageSuccess, - InfraredNotificationMessageGreenOn, - InfraredNotificationMessageGreenOff, - InfraredNotificationMessageYellowOn, - InfraredNotificationMessageYellowOff, - InfraredNotificationMessageBlinkStartRead, - InfraredNotificationMessageBlinkStartSend, - InfraredNotificationMessageBlinkStop, -} InfraredNotificationMessage; - -bool infrared_add_remote_with_button(Infrared* infrared, const char* name, InfraredSignal* signal); -bool infrared_rename_current_remote(Infrared* infrared, const char* name); -void infrared_tx_start_signal(Infrared* infrared, InfraredSignal* signal); -void infrared_tx_start_button_index(Infrared* infrared, size_t button_index); -void infrared_tx_start_received(Infrared* infrared); -void infrared_tx_stop(Infrared* infrared); -void infrared_text_store_set(Infrared* infrared, uint32_t bank, const char* text, ...); -void infrared_text_store_clear(Infrared* infrared, uint32_t bank); -void infrared_play_notification_message(Infrared* infrared, uint32_t message); -void infrared_show_loading_popup(Infrared* infrared, bool show); - -void infrared_signal_received_callback(void* context, InfraredWorkerSignal* received_signal); -void infrared_text_input_callback(void* context); -void infrared_popup_closed_callback(void* context); diff --git a/applications/main/infrared/infrared_remote.c b/applications/main/infrared/infrared_remote.c index 70d1b59ef..cab241c12 100644 --- a/applications/main/infrared/infrared_remote.c +++ b/applications/main/infrared/infrared_remote.c @@ -1,197 +1,427 @@ #include "infrared_remote.h" -#include -#include -#include #include + +#include #include #include -#include #define TAG "InfraredRemote" -ARRAY_DEF(InfraredButtonArray, InfraredRemoteButton*, M_PTR_OPLIST); +#define INFRARED_FILE_HEADER "IR signals file" +#define INFRARED_FILE_VERSION (1) + +ARRAY_DEF(StringArray, const char*, M_CSTR_DUP_OPLIST); //-V575 struct InfraredRemote { - InfraredButtonArray_t buttons; + StringArray_t signal_names; FuriString* name; FuriString* path; }; -static void infrared_remote_clear_buttons(InfraredRemote* remote) { - InfraredButtonArray_it_t it; - for(InfraredButtonArray_it(it, remote->buttons); !InfraredButtonArray_end_p(it); - InfraredButtonArray_next(it)) { - infrared_remote_button_free(*InfraredButtonArray_cref(it)); - } - InfraredButtonArray_reset(remote->buttons); -} +typedef struct { + InfraredRemote* remote; + FlipperFormat* ff_in; + FlipperFormat* ff_out; + FuriString* signal_name; + InfraredSignal* signal; + size_t signal_index; +} InfraredBatch; + +typedef struct { + size_t signal_index; + const char* signal_name; + const InfraredSignal* signal; +} InfraredBatchTarget; + +typedef bool ( + *InfraredBatchCallback)(const InfraredBatch* batch, const InfraredBatchTarget* target); InfraredRemote* infrared_remote_alloc() { InfraredRemote* remote = malloc(sizeof(InfraredRemote)); - InfraredButtonArray_init(remote->buttons); + StringArray_init(remote->signal_names); remote->name = furi_string_alloc(); remote->path = furi_string_alloc(); return remote; } void infrared_remote_free(InfraredRemote* remote) { - infrared_remote_clear_buttons(remote); - InfraredButtonArray_clear(remote->buttons); + StringArray_clear(remote->signal_names); furi_string_free(remote->path); furi_string_free(remote->name); free(remote); } void infrared_remote_reset(InfraredRemote* remote) { - infrared_remote_clear_buttons(remote); + StringArray_reset(remote->signal_names); furi_string_reset(remote->name); furi_string_reset(remote->path); } -void infrared_remote_set_name(InfraredRemote* remote, const char* name) { - furi_string_set(remote->name, name); -} - -const char* infrared_remote_get_name(InfraredRemote* remote) { +const char* infrared_remote_get_name(const InfraredRemote* remote) { return furi_string_get_cstr(remote->name); } -void infrared_remote_set_path(InfraredRemote* remote, const char* path) { +static void infrared_remote_set_path(InfraredRemote* remote, const char* path) { furi_string_set(remote->path, path); + path_extract_filename(remote->path, remote->name, true); } -const char* infrared_remote_get_path(InfraredRemote* remote) { +const char* infrared_remote_get_path(const InfraredRemote* remote) { return furi_string_get_cstr(remote->path); } -size_t infrared_remote_get_button_count(InfraredRemote* remote) { - return InfraredButtonArray_size(remote->buttons); +size_t infrared_remote_get_signal_count(const InfraredRemote* remote) { + return StringArray_size(remote->signal_names); } -InfraredRemoteButton* infrared_remote_get_button(InfraredRemote* remote, size_t index) { - furi_assert(index < InfraredButtonArray_size(remote->buttons)); - return *InfraredButtonArray_get(remote->buttons, index); +const char* infrared_remote_get_signal_name(const InfraredRemote* remote, size_t index) { + furi_assert(index < infrared_remote_get_signal_count(remote)); + return *StringArray_cget(remote->signal_names, index); } -bool infrared_remote_find_button_by_name(InfraredRemote* remote, const char* name, size_t* index) { - for(size_t i = 0; i < InfraredButtonArray_size(remote->buttons); i++) { - InfraredRemoteButton* button = *InfraredButtonArray_get(remote->buttons, i); - if(!strcmp(infrared_remote_button_get_name(button), name)) { +bool infrared_remote_load_signal( + const InfraredRemote* remote, + InfraredSignal* signal, + size_t index) { + furi_assert(index < infrared_remote_get_signal_count(remote)); + + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_buffered_file_alloc(storage); + + bool success = false; + + do { + const char* path = furi_string_get_cstr(remote->path); + if(!flipper_format_buffered_file_open_existing(ff, path)) break; + + if(!infrared_signal_search_by_index_and_read(signal, ff, index)) { + const char* signal_name = infrared_remote_get_signal_name(remote, index); + FURI_LOG_E(TAG, "Failed to load signal '%s' from file '%s'", signal_name, path); + break; + } + + success = true; + } while(false); + + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + return success; +} + +bool infrared_remote_get_signal_index( + const InfraredRemote* remote, + const char* name, + size_t* index) { + uint32_t i = 0; + StringArray_it_t it; + + for(StringArray_it(it, remote->signal_names); !StringArray_end_p(it); + StringArray_next(it), ++i) { + if(strcmp(*StringArray_cref(it), name) == 0) { *index = i; return true; } } + return false; } -bool infrared_remote_add_button(InfraredRemote* remote, const char* name, InfraredSignal* signal) { - InfraredRemoteButton* button = infrared_remote_button_alloc(); - infrared_remote_button_set_name(button, name); - infrared_remote_button_set_signal(button, signal); - InfraredButtonArray_push_back(remote->buttons, button); - return infrared_remote_store(remote); -} - -bool infrared_remote_rename_button(InfraredRemote* remote, const char* new_name, size_t index) { - furi_assert(index < InfraredButtonArray_size(remote->buttons)); - InfraredRemoteButton* button = *InfraredButtonArray_get(remote->buttons, index); - infrared_remote_button_set_name(button, new_name); - return infrared_remote_store(remote); -} - -bool infrared_remote_delete_button(InfraredRemote* remote, size_t index) { - furi_assert(index < InfraredButtonArray_size(remote->buttons)); - InfraredRemoteButton* button; - InfraredButtonArray_pop_at(&button, remote->buttons, index); - infrared_remote_button_free(button); - return infrared_remote_store(remote); -} - -void infrared_remote_move_button(InfraredRemote* remote, size_t index_orig, size_t index_dest) { - furi_assert(index_orig < InfraredButtonArray_size(remote->buttons)); - furi_assert(index_dest < InfraredButtonArray_size(remote->buttons)); - - InfraredRemoteButton* button; - InfraredButtonArray_pop_at(&button, remote->buttons, index_orig); - InfraredButtonArray_push_at(remote->buttons, index_dest, button); -} - -bool infrared_remote_store(InfraredRemote* remote) { +bool infrared_remote_append_signal( + InfraredRemote* remote, + const InfraredSignal* signal, + const char* name) { Storage* storage = furi_record_open(RECORD_STORAGE); FlipperFormat* ff = flipper_format_file_alloc(storage); + + bool success = false; const char* path = furi_string_get_cstr(remote->path); - FURI_LOG_I(TAG, "store file: \'%s\'", path); - - bool success = flipper_format_file_open_always(ff, path) && - flipper_format_write_header_cstr(ff, "IR signals file", 1); - if(success) { - InfraredButtonArray_it_t it; - for(InfraredButtonArray_it(it, remote->buttons); !InfraredButtonArray_end_p(it); - InfraredButtonArray_next(it)) { - InfraredRemoteButton* button = *InfraredButtonArray_cref(it); - success = infrared_signal_save( - infrared_remote_button_get_signal(button), - ff, - infrared_remote_button_get_name(button)); - if(!success) { - break; - } - } - } - - flipper_format_free(ff); - furi_record_close(RECORD_STORAGE); - return success; -} - -bool infrared_remote_load(InfraredRemote* remote, FuriString* path) { - Storage* storage = furi_record_open(RECORD_STORAGE); - FlipperFormat* ff = flipper_format_buffered_file_alloc(storage); - - FuriString* buf; - buf = furi_string_alloc(); - - FURI_LOG_I(TAG, "load file: \'%s\'", furi_string_get_cstr(path)); - bool success = false; - do { - if(!flipper_format_buffered_file_open_existing(ff, furi_string_get_cstr(path))) break; - uint32_t version; - if(!flipper_format_read_header(ff, buf, &version)) break; - if(!furi_string_equal(buf, "IR signals file") || (version != 1)) break; + if(!flipper_format_file_open_append(ff, path)) break; + if(!infrared_signal_save(signal, ff, name)) break; - path_extract_filename(path, buf, true); - infrared_remote_clear_buttons(remote); - infrared_remote_set_name(remote, furi_string_get_cstr(buf)); - infrared_remote_set_path(remote, furi_string_get_cstr(path)); - - for(bool can_read = true; can_read;) { - InfraredRemoteButton* button = infrared_remote_button_alloc(); - can_read = infrared_signal_read(infrared_remote_button_get_signal(button), ff, buf); - if(can_read) { - infrared_remote_button_set_name(button, furi_string_get_cstr(buf)); - InfraredButtonArray_push_back(remote->buttons, button); - } else { - infrared_remote_button_free(button); - } - } + StringArray_push_back(remote->signal_names, name); success = true; } while(false); - furi_string_free(buf); flipper_format_free(ff); furi_record_close(RECORD_STORAGE); + + return success; +} + +static bool infrared_remote_batch_start( + InfraredRemote* remote, + InfraredBatchCallback batch_callback, + const InfraredBatchTarget* target) { + FuriString* tmp = furi_string_alloc(); + Storage* storage = furi_record_open(RECORD_STORAGE); + + InfraredBatch batch_context = { + .remote = remote, + .ff_in = flipper_format_buffered_file_alloc(storage), + .ff_out = flipper_format_buffered_file_alloc(storage), + .signal_name = furi_string_alloc(), + .signal = infrared_signal_alloc(), + .signal_index = 0, + }; + + const char* path_in = furi_string_get_cstr(remote->path); + const char* path_out; + + FS_Error status; + + do { + furi_string_printf(tmp, "%s.temp%08x.swp", path_in, rand()); + path_out = furi_string_get_cstr(tmp); + status = storage_common_stat(storage, path_out, NULL); + } while(status == FSE_OK || status == FSE_EXIST); + + bool success = false; + + do { + if(!flipper_format_buffered_file_open_existing(batch_context.ff_in, path_in)) break; + if(!flipper_format_buffered_file_open_always(batch_context.ff_out, path_out)) break; + if(!flipper_format_write_header_cstr( + batch_context.ff_out, INFRARED_FILE_HEADER, INFRARED_FILE_VERSION)) + break; + + const size_t signal_count = infrared_remote_get_signal_count(remote); + + for(; batch_context.signal_index < signal_count; ++batch_context.signal_index) { + if(!infrared_signal_read( + batch_context.signal, batch_context.ff_in, batch_context.signal_name)) + break; + if(!batch_callback(&batch_context, target)) break; + } + + if(batch_context.signal_index != signal_count) break; + + if(!flipper_format_buffered_file_close(batch_context.ff_out)) break; + if(!flipper_format_buffered_file_close(batch_context.ff_in)) break; + + const FS_Error status = storage_common_rename(storage, path_out, path_in); + success = (status == FSE_OK || status == FSE_EXIST); + } while(false); + + infrared_signal_free(batch_context.signal); + furi_string_free(batch_context.signal_name); + flipper_format_free(batch_context.ff_out); + flipper_format_free(batch_context.ff_in); + furi_string_free(tmp); + + furi_record_close(RECORD_STORAGE); + + return success; +} + +static bool infrared_remote_insert_signal_callback( + const InfraredBatch* batch, + const InfraredBatchTarget* target) { + // Insert a signal under the specified index + if(batch->signal_index == target->signal_index) { + if(!infrared_signal_save(target->signal, batch->ff_out, target->signal_name)) return false; + StringArray_push_at( + batch->remote->signal_names, target->signal_index, target->signal_name); + } + + // Write the rest normally + return infrared_signal_save( + batch->signal, batch->ff_out, furi_string_get_cstr(batch->signal_name)); +} + +bool infrared_remote_insert_signal( + InfraredRemote* remote, + const InfraredSignal* signal, + const char* name, + size_t index) { + if(index >= infrared_remote_get_signal_count(remote)) { + return infrared_remote_append_signal(remote, signal, name); + } + + const InfraredBatchTarget insert_target = { + .signal_index = index, + .signal_name = name, + .signal = signal, + }; + + return infrared_remote_batch_start( + remote, infrared_remote_insert_signal_callback, &insert_target); +} + +static bool infrared_remote_rename_signal_callback( + const InfraredBatch* batch, + const InfraredBatchTarget* target) { + const char* signal_name; + + if(batch->signal_index == target->signal_index) { + // Rename the signal at requested index + signal_name = target->signal_name; + StringArray_set_at(batch->remote->signal_names, batch->signal_index, signal_name); + } else { + // Use the original name otherwise + signal_name = furi_string_get_cstr(batch->signal_name); + } + + return infrared_signal_save(batch->signal, batch->ff_out, signal_name); +} + +bool infrared_remote_rename_signal(InfraredRemote* remote, size_t index, const char* new_name) { + furi_assert(index < infrared_remote_get_signal_count(remote)); + + const InfraredBatchTarget rename_target = { + .signal_index = index, + .signal_name = new_name, + .signal = NULL, + }; + + return infrared_remote_batch_start( + remote, infrared_remote_rename_signal_callback, &rename_target); +} + +static bool infrared_remote_delete_signal_callback( + const InfraredBatch* batch, + const InfraredBatchTarget* target) { + if(batch->signal_index == target->signal_index) { + // Do not save the signal to be deleted, remove it from the signal name list instead + StringArray_remove_v( + batch->remote->signal_names, batch->signal_index, batch->signal_index + 1); + } else { + // Pass other signals through + return infrared_signal_save( + batch->signal, batch->ff_out, furi_string_get_cstr(batch->signal_name)); + } + + return true; +} + +bool infrared_remote_delete_signal(InfraredRemote* remote, size_t index) { + furi_assert(index < infrared_remote_get_signal_count(remote)); + + const InfraredBatchTarget delete_target = { + .signal_index = index, + .signal_name = NULL, + .signal = NULL, + }; + + return infrared_remote_batch_start( + remote, infrared_remote_delete_signal_callback, &delete_target); +} + +bool infrared_remote_move_signal(InfraredRemote* remote, size_t index, size_t new_index) { + const size_t signal_count = infrared_remote_get_signal_count(remote); + furi_assert(index < signal_count); + furi_assert(new_index < signal_count); + + if(index == new_index) return true; + + InfraredSignal* signal = infrared_signal_alloc(); + char* signal_name = strdup(infrared_remote_get_signal_name(remote, index)); + + bool success = false; + + do { + if(!infrared_remote_load_signal(remote, signal, index)) break; + if(!infrared_remote_delete_signal(remote, index)) break; + if(!infrared_remote_insert_signal(remote, signal, signal_name, new_index)) break; + + success = true; + } while(false); + + free(signal_name); + infrared_signal_free(signal); + + return success; +} + +bool infrared_remote_create(InfraredRemote* remote, const char* path) { + FURI_LOG_I(TAG, "Creating new file: '%s'", path); + + infrared_remote_reset(remote); + infrared_remote_set_path(remote, path); + + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_file_alloc(storage); + + bool success = false; + + do { + if(!flipper_format_file_open_always(ff, path)) break; + if(!flipper_format_write_header_cstr(ff, INFRARED_FILE_HEADER, INFRARED_FILE_VERSION)) + break; + + success = true; + } while(false); + + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + return success; +} + +bool infrared_remote_load(InfraredRemote* remote, const char* path) { + FURI_LOG_I(TAG, "Loading file: '%s'", path); + + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_buffered_file_alloc(storage); + + FuriString* tmp = furi_string_alloc(); + bool success = false; + + do { + if(!flipper_format_buffered_file_open_existing(ff, path)) break; + + uint32_t version; + if(!flipper_format_read_header(ff, tmp, &version)) break; + + if(!furi_string_equal(tmp, INFRARED_FILE_HEADER) || (version != INFRARED_FILE_VERSION)) + break; + + infrared_remote_set_path(remote, path); + StringArray_reset(remote->signal_names); + + while(infrared_signal_read_name(ff, tmp)) { + StringArray_push_back(remote->signal_names, furi_string_get_cstr(tmp)); + } + + success = true; + } while(false); + + furi_string_free(tmp); + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + return success; +} + +bool infrared_remote_rename(InfraredRemote* remote, const char* new_path) { + const char* old_path = infrared_remote_get_path(remote); + + Storage* storage = furi_record_open(RECORD_STORAGE); + const FS_Error status = storage_common_rename(storage, old_path, new_path); + furi_record_close(RECORD_STORAGE); + + const bool success = (status == FSE_OK || status == FSE_EXIST); + + if(success) { + infrared_remote_set_path(remote, new_path); + } + return success; } bool infrared_remote_remove(InfraredRemote* remote) { Storage* storage = furi_record_open(RECORD_STORAGE); - - FS_Error status = storage_common_remove(storage, furi_string_get_cstr(remote->path)); - infrared_remote_reset(remote); - + const FS_Error status = storage_common_remove(storage, infrared_remote_get_path(remote)); furi_record_close(RECORD_STORAGE); - return (status == FSE_OK || status == FSE_NOT_EXIST); + + const bool success = (status == FSE_OK || status == FSE_NOT_EXIST); + + if(success) { + infrared_remote_reset(remote); + } + + return success; } diff --git a/applications/main/infrared/infrared_remote.h b/applications/main/infrared/infrared_remote.h index 47aa77e2e..7477cd3b5 100644 --- a/applications/main/infrared/infrared_remote.h +++ b/applications/main/infrared/infrared_remote.h @@ -1,30 +1,229 @@ +/** + * @file infrared_remote.h + * @brief Infrared remote library. + * + * An infrared remote contains zero or more infrared signals which + * have a (possibly non-unique) name each. + * + * The current implementation does load only the names into the memory, + * while the signals themselves are loaded on-demand one by one. In theory, + * this should allow for quite large remotes with relatively bulky signals. + */ #pragma once -#include - -#include "infrared_remote_button.h" +#include "infrared_signal.h" +/** + * @brief InfraredRemote opaque type declaration. + */ typedef struct InfraredRemote InfraredRemote; +/** + * @brief Create a new InfraredRemote instance. + * + * @returns pointer to the created instance. + */ InfraredRemote* infrared_remote_alloc(); + +/** + * @brief Delete an InfraredRemote instance. + * + * @param[in,out] remote pointer to the instance to be deleted. + */ void infrared_remote_free(InfraredRemote* remote); + +/** + * @brief Reset an InfraredRemote instance. + * + * Resetting a remote clears its signal name list and + * the associated file path. + * + * @param[in,out] remote pointer to the instance to be deleted. + */ void infrared_remote_reset(InfraredRemote* remote); -void infrared_remote_set_name(InfraredRemote* remote, const char* name); -const char* infrared_remote_get_name(InfraredRemote* remote); +/** + * @brief Get an InfraredRemote instance's name. + * + * The name is deduced from the file path. + * + * The return value remains valid unless one of the following functions is called: + * - infrared_remote_reset() + * - infrared_remote_load() + * - infrared_remote_create() + * + * @param[in] remote pointer to the instance to be queried. + * @returns pointer to a zero-terminated string containing the name. + */ +const char* infrared_remote_get_name(const InfraredRemote* remote); -void infrared_remote_set_path(InfraredRemote* remote, const char* path); -const char* infrared_remote_get_path(InfraredRemote* remote); +/** + * @brief Get an InfraredRemote instance's file path. + * + * Same return value validity considerations as infrared_remote_get_name(). + * + * @param[in] remote pointer to the instance to be queried. + * @returns pointer to a zero-terminated string containing the path. + */ +const char* infrared_remote_get_path(const InfraredRemote* remote); -size_t infrared_remote_get_button_count(InfraredRemote* remote); -InfraredRemoteButton* infrared_remote_get_button(InfraredRemote* remote, size_t index); -bool infrared_remote_find_button_by_name(InfraredRemote* remote, const char* name, size_t* index); +/** + * @brief Get the number of signals listed in an InfraredRemote instance. + * + * @param[in] remote pointer to the instance to be queried. + * @returns number of signals, zero or more + */ +size_t infrared_remote_get_signal_count(const InfraredRemote* remote); -bool infrared_remote_add_button(InfraredRemote* remote, const char* name, InfraredSignal* signal); -bool infrared_remote_rename_button(InfraredRemote* remote, const char* new_name, size_t index); -bool infrared_remote_delete_button(InfraredRemote* remote, size_t index); -void infrared_remote_move_button(InfraredRemote* remote, size_t index_orig, size_t index_dest); +/** + * @brief Get the name of a signal listed in an InfraredRemote instance. + * + * @param[in] remote pointer to the instance to be queried. + * @param[in] index index of the signal in question. Must be less than the total signal count. + */ +const char* infrared_remote_get_signal_name(const InfraredRemote* remote, size_t index); -bool infrared_remote_store(InfraredRemote* remote); -bool infrared_remote_load(InfraredRemote* remote, FuriString* path); +/** + * @brief Get the index of a signal listed in an InfraredRemote instance by its name. + * + * @param[in] remote pointer to the instance to be queried. + * @param[in] name pointer to a zero-terminated string containig the name of the signal in question. + * @param[out] index pointer to the variable to hold the signal index. + * @returns true if a signal with the given name was found, false otherwise. + */ +bool infrared_remote_get_signal_index( + const InfraredRemote* remote, + const char* name, + size_t* index); + +/** + * @brief Load a signal listed in an InfraredRemote instance. + * + * As mentioned above, the signals are loaded on-demand. The user code must call this function + * each time it wants to interact with a new signal. + * + * @param[in] remote pointer to the instance to load from. + * @param[out] signal pointer to the signal to load into. Must be allocated. + * @param[in] index index of the signal to be loaded. Must be less than the total signal count. + * @return true if the signal was successfully loaded, false otherwise. + */ +bool infrared_remote_load_signal( + const InfraredRemote* remote, + InfraredSignal* signal, + size_t index); + +/** + * @brief Append a signal to the file associated with an InfraredRemote instance. + * + * The file path must be somehow initialised first by calling either infrared_remote_load() or + * infrared_remote_create(). As the name suggests, the signal will be put in the end of the file. + * + * @param[in,out] remote pointer to the instance to append to. + * @param[in] signal pointer to the signal to be appended. + * @param[in] name pointer to a zero-terminated string containing the name of the signal. + * @returns true if the signal was successfully appended, false otherwise. + */ +bool infrared_remote_append_signal( + InfraredRemote* remote, + const InfraredSignal* signal, + const char* name); + +/** + * @brief Insert a signal to the file associated with an InfraredRemote instance. + * + * Same behaviour as infrared_remote_append_signal(), but the user code can decide where to + * put the signal in the file. + * + * Index values equal to or greater than the total signal count will result in behaviour + * identical to infrared_remote_append_signal(). + * + * @param[in,out] remote pointer to the instance to insert to. + * @param[in] signal pointer to the signal to be inserted. + * @param[in] name pointer to a zero-terminated string containing the name of the signal. + * @param[in] index the index under which the signal shall be inserted. + * @returns true if the signal was successfully inserted, false otherwise. + */ +bool infrared_remote_insert_signal( + InfraredRemote* remote, + const InfraredSignal* signal, + const char* name, + size_t index); + +/** + * @brief Rename a signal in the file associated with an InfraredRemote instance. + * + * Only changes the signal's name, but neither its position nor contents. + * + * @param[in,out] remote pointer to the instance to be modified. + * @param[in] index index of the signal to be renamed. Must be less than the total signal count. + * @param[in] new_name pointer to a zero-terminated string containig the signal's new name. + * @returns true if the signal was successfully renamed, false otherwise. + */ +bool infrared_remote_rename_signal(InfraredRemote* remote, size_t index, const char* new_name); + +/** + * @brief Change a signal's position in the file associated with an InfraredRemote instance. + * + * Only changes the signal's position (index), but neither its name nor contents. + * + * @param[in,out] remote pointer to the instance to be modified. + * @param[in] index index of the signal to be moved. Must be less than the total signal count. + * @param[in] new_index index of the signal to be moved. Must be less than the total signal count. + */ +bool infrared_remote_move_signal(InfraredRemote* remote, size_t index, size_t new_index); + +/** + * @brief Delete a signal in the file associated with an InfraredRemote instance. + * + * @param[in,out] remote pointer to the instance to be modified. + * @param[in] index index of the signal to be deleted. Must be less than the total signal count. + * @returns true if the signal was successfully deleted, false otherwise. + */ +bool infrared_remote_delete_signal(InfraredRemote* remote, size_t index); + +/** + * @brief Create a new file and associate it with an InfraredRemote instance. + * + * The instance will be reset and given a new empty file with just the header. + * + * @param[in,out] remote pointer to the instance to be assigned with a new file. + * @param[in] path pointer to a zero-terminated string containing the full file path. + * @returns true if the file was successfully created, false otherwise. + */ +bool infrared_remote_create(InfraredRemote* remote, const char* path); + +/** + * @brief Associate an InfraredRemote instance with a file and load the signal names from it. + * + * The instance will be reset and fill its signal name list from the given file. + * The file must already exist and be valid. + * + * @param[in,out] remote pointer to the instance to be assigned with an existing file. + * @param[in] path pointer to a zero-terminated string containing the full file path. + * @returns true if the file was successfully loaded, false otherwise. + */ +bool infrared_remote_load(InfraredRemote* remote, const char* path); + +/** + * @brief Rename the file associated with an InfraredRemote instance. + * + * Only renames the file, no signals are added, moved or deleted. + * + * @param[in,out] remote pointer to the instance to be modified. + * @param[in] new_path pointer to a zero-terminated string containing the new full file path. + * @returns true if the file was successfully renamed, false otherwise. + */ +bool infrared_remote_rename(InfraredRemote* remote, const char* new_path); + +/** + * @brief Remove the file associated with an InfraredRemote instance. + * + * This operation is irreversible and fully deletes the remote file + * from the underlying filesystem. + * After calling this function, the instance becomes invalid until + * infrared_remote_create() or infrared_remote_load() are successfully executed. + * + * @param[in,out] remote pointer to the instance to be modified. + * @returns true if the file was successfully removed, false otherwise. + */ bool infrared_remote_remove(InfraredRemote* remote); diff --git a/applications/main/infrared/infrared_remote_button.c b/applications/main/infrared/infrared_remote_button.c deleted file mode 100644 index 1f6315ec5..000000000 --- a/applications/main/infrared/infrared_remote_button.c +++ /dev/null @@ -1,37 +0,0 @@ -#include "infrared_remote_button.h" - -#include - -struct InfraredRemoteButton { - FuriString* name; - InfraredSignal* signal; -}; - -InfraredRemoteButton* infrared_remote_button_alloc() { - InfraredRemoteButton* button = malloc(sizeof(InfraredRemoteButton)); - button->name = furi_string_alloc(); - button->signal = infrared_signal_alloc(); - return button; -} - -void infrared_remote_button_free(InfraredRemoteButton* button) { - furi_string_free(button->name); - infrared_signal_free(button->signal); - free(button); -} - -void infrared_remote_button_set_name(InfraredRemoteButton* button, const char* name) { - furi_string_set(button->name, name); -} - -const char* infrared_remote_button_get_name(InfraredRemoteButton* button) { - return furi_string_get_cstr(button->name); -} - -void infrared_remote_button_set_signal(InfraredRemoteButton* button, InfraredSignal* signal) { - infrared_signal_set_signal(button->signal, signal); -} - -InfraredSignal* infrared_remote_button_get_signal(InfraredRemoteButton* button) { - return button->signal; -} diff --git a/applications/main/infrared/infrared_remote_button.h b/applications/main/infrared/infrared_remote_button.h deleted file mode 100644 index f25b759b5..000000000 --- a/applications/main/infrared/infrared_remote_button.h +++ /dev/null @@ -1,14 +0,0 @@ -#pragma once - -#include "infrared_signal.h" - -typedef struct InfraredRemoteButton InfraredRemoteButton; - -InfraredRemoteButton* infrared_remote_button_alloc(); -void infrared_remote_button_free(InfraredRemoteButton* button); - -void infrared_remote_button_set_name(InfraredRemoteButton* button, const char* name); -const char* infrared_remote_button_get_name(InfraredRemoteButton* button); - -void infrared_remote_button_set_signal(InfraredRemoteButton* button, InfraredSignal* signal); -InfraredSignal* infrared_remote_button_get_signal(InfraredRemoteButton* button); diff --git a/applications/main/infrared/infrared_signal.c b/applications/main/infrared/infrared_signal.c index 3f9a51908..1bd4780d6 100644 --- a/applications/main/infrared/infrared_signal.c +++ b/applications/main/infrared/infrared_signal.c @@ -8,6 +8,8 @@ #define TAG "InfraredSignal" +#define INFRARED_SIGNAL_NAME_KEY "name" + struct InfraredSignal { bool is_raw; union { @@ -24,7 +26,7 @@ static void infrared_signal_clear_timings(InfraredSignal* signal) { } } -static bool infrared_signal_is_message_valid(InfraredMessage* message) { +static bool infrared_signal_is_message_valid(const InfraredMessage* message) { if(!infrared_is_protocol_valid(message->protocol)) { FURI_LOG_E(TAG, "Unknown protocol"); return false; @@ -57,7 +59,7 @@ static bool infrared_signal_is_message_valid(InfraredMessage* message) { return true; } -static bool infrared_signal_is_raw_valid(InfraredRawSignal* raw) { +static bool infrared_signal_is_raw_valid(const InfraredRawSignal* raw) { if((raw->frequency > INFRARED_MAX_FREQUENCY) || (raw->frequency < INFRARED_MIN_FREQUENCY)) { FURI_LOG_E( TAG, @@ -83,7 +85,8 @@ static bool infrared_signal_is_raw_valid(InfraredRawSignal* raw) { return true; } -static inline bool infrared_signal_save_message(InfraredMessage* message, FlipperFormat* ff) { +static inline bool + infrared_signal_save_message(const InfraredMessage* message, FlipperFormat* ff) { const char* protocol_name = infrared_get_protocol_name(message->protocol); return flipper_format_write_string_cstr(ff, "type", "parsed") && flipper_format_write_string_cstr(ff, "protocol", protocol_name) && @@ -91,7 +94,7 @@ static inline bool infrared_signal_save_message(InfraredMessage* message, Flippe flipper_format_write_hex(ff, "command", (uint8_t*)&message->command, 4); } -static inline bool infrared_signal_save_raw(InfraredRawSignal* raw, FlipperFormat* ff) { +static inline bool infrared_signal_save_raw(const InfraredRawSignal* raw, FlipperFormat* ff) { furi_assert(raw->timings_size <= MAX_TIMINGS_AMOUNT); return flipper_format_write_string_cstr(ff, "type", "raw") && flipper_format_write_uint32(ff, "frequency", &raw->frequency, 1) && @@ -180,11 +183,11 @@ void infrared_signal_free(InfraredSignal* signal) { free(signal); } -bool infrared_signal_is_raw(InfraredSignal* signal) { +bool infrared_signal_is_raw(const InfraredSignal* signal) { return signal->is_raw; } -bool infrared_signal_is_valid(InfraredSignal* signal) { +bool infrared_signal_is_valid(const InfraredSignal* signal) { return signal->is_raw ? infrared_signal_is_raw_valid(&signal->payload.raw) : infrared_signal_is_message_valid(&signal->payload.message); } @@ -233,7 +236,7 @@ void infrared_signal_set_raw_signal( memcpy(signal->payload.raw.timings, timings, timings_size * sizeof(uint32_t)); } -InfraredRawSignal* infrared_signal_get_raw_signal(InfraredSignal* signal) { +const InfraredRawSignal* infrared_signal_get_raw_signal(const InfraredSignal* signal) { furi_assert(signal->is_raw); return &signal->payload.raw; } @@ -245,14 +248,14 @@ void infrared_signal_set_message(InfraredSignal* signal, const InfraredMessage* signal->payload.message = *message; } -InfraredMessage* infrared_signal_get_message(InfraredSignal* signal) { +const InfraredMessage* infrared_signal_get_message(const InfraredSignal* signal) { furi_assert(!signal->is_raw); return &signal->payload.message; } -bool infrared_signal_save(InfraredSignal* signal, FlipperFormat* ff, const char* name) { +bool infrared_signal_save(const InfraredSignal* signal, FlipperFormat* ff, const char* name) { if(!flipper_format_write_comment_cstr(ff, "") || - !flipper_format_write_string_cstr(ff, "name", name)) { + !flipper_format_write_string_cstr(ff, INFRARED_SIGNAL_NAME_KEY, name)) { return false; } else if(signal->is_raw) { return infrared_signal_save_raw(&signal->payload.raw, ff); @@ -262,46 +265,61 @@ bool infrared_signal_save(InfraredSignal* signal, FlipperFormat* ff, const char* } bool infrared_signal_read(InfraredSignal* signal, FlipperFormat* ff, FuriString* name) { - FuriString* tmp = furi_string_alloc(); - bool success = false; do { - if(!flipper_format_read_string(ff, "name", tmp)) break; - furi_string_set(name, tmp); + if(!infrared_signal_read_name(ff, name)) break; if(!infrared_signal_read_body(signal, ff)) break; - success = true; - } while(0); - furi_string_free(tmp); - return success; -} - -bool infrared_signal_search_and_read( - InfraredSignal* signal, - FlipperFormat* ff, - const FuriString* name) { - bool success = false; - FuriString* tmp = furi_string_alloc(); - - do { - bool is_name_found = false; - while(flipper_format_read_string(ff, "name", tmp)) { - is_name_found = furi_string_equal(name, tmp); - if(is_name_found) break; - } - if(!is_name_found) break; //-V547 - if(!infrared_signal_read_body(signal, ff)) break; //-V779 - success = true; + success = true; //-V779 } while(false); + return success; +} + +bool infrared_signal_read_name(FlipperFormat* ff, FuriString* name) { + return flipper_format_read_string(ff, INFRARED_SIGNAL_NAME_KEY, name); +} + +bool infrared_signal_search_by_name_and_read( + InfraredSignal* signal, + FlipperFormat* ff, + const char* name) { + bool success = false; + FuriString* tmp = furi_string_alloc(); + + while(infrared_signal_read_name(ff, tmp)) { + if(furi_string_equal(tmp, name)) { + success = infrared_signal_read_body(signal, ff); + break; + } + } + furi_string_free(tmp); return success; } -void infrared_signal_transmit(InfraredSignal* signal) { +bool infrared_signal_search_by_index_and_read( + InfraredSignal* signal, + FlipperFormat* ff, + size_t index) { + bool success = false; + FuriString* tmp = furi_string_alloc(); + + for(uint32_t i = 0; infrared_signal_read_name(ff, tmp); ++i) { + if(i == index) { + success = infrared_signal_read_body(signal, ff); + break; + } + } + + furi_string_free(tmp); + return success; +} + +void infrared_signal_transmit(const InfraredSignal* signal) { if(signal->is_raw) { - InfraredRawSignal* raw_signal = &signal->payload.raw; + const InfraredRawSignal* raw_signal = &signal->payload.raw; infrared_send_raw_ext( raw_signal->timings, raw_signal->timings_size, @@ -309,7 +327,7 @@ void infrared_signal_transmit(InfraredSignal* signal) { raw_signal->frequency, raw_signal->duty_cycle); } else { - InfraredMessage* message = &signal->payload.message; + const InfraredMessage* message = &signal->payload.message; infrared_send(message, 1); } } diff --git a/applications/main/infrared/infrared_signal.h b/applications/main/infrared/infrared_signal.h index 29c661938..cfa4cfa94 100644 --- a/applications/main/infrared/infrared_signal.h +++ b/applications/main/infrared/infrared_signal.h @@ -1,45 +1,205 @@ +/** + * @file infrared_signal.h + * @brief Infrared signal library. + * + * Infrared signals may be of two types: + * - known to the infrared signal decoder, or *parsed* signals + * - the rest, or *raw* signals, which are treated merely as a set of timings. + */ #pragma once -#include -#include -#include - -#include #include +#include +/** + * @brief InfraredSignal opaque type declaration. + */ typedef struct InfraredSignal InfraredSignal; +/** + * @brief Raw signal type definition. + * + * Measurement units used: + * - time: microseconds (uS) + * - frequency: Hertz (Hz) + * - duty_cycle: no units, fraction between 0 and 1. + */ typedef struct { - size_t timings_size; - uint32_t* timings; - uint32_t frequency; - float duty_cycle; + size_t timings_size; /**< Number of elements in the timings array. */ + uint32_t* timings; /**< Pointer to an array of timings describing the signal. */ + uint32_t frequency; /**< Carrier frequency of the signal. */ + float duty_cycle; /**< Duty cycle of the signal. */ } InfraredRawSignal; +/** + * @brief Create a new InfraredSignal instance. + * + * @returns pointer to the instance created. + */ InfraredSignal* infrared_signal_alloc(); + +/** + * @brief Delete an InfraredSignal instance. + * + * @param[in,out] signal pointer to the instance to be deleted. + */ void infrared_signal_free(InfraredSignal* signal); -bool infrared_signal_is_raw(InfraredSignal* signal); -bool infrared_signal_is_valid(InfraredSignal* signal); +/** + * @brief Test whether an InfraredSignal instance holds a raw signal. + * + * @param[in] signal pointer to the instance to be tested. + * @returns true if the instance holds a raw signal, false otherwise. + */ +bool infrared_signal_is_raw(const InfraredSignal* signal); +/** + * @brief Test whether an InfraredSignal instance holds any signal. + * + * @param[in] signal pointer to the instance to be tested. + * @returns true if the instance holds raw signal, false otherwise. + */ +bool infrared_signal_is_valid(const InfraredSignal* signal); + +/** + * @brief Set an InfraredInstance to hold the signal from another one. + * + * Any instance's previous contents will be automatically deleted before + * copying the source instance's contents. + * + * @param[in,out] signal pointer to the destination instance. + * @param[in] other pointer to the source instance. + */ void infrared_signal_set_signal(InfraredSignal* signal, const InfraredSignal* other); +/** + * @brief Set an InfraredInstance to hold a raw signal. + * + * Any instance's previous contents will be automatically deleted before + * copying the raw signal. + * + * After this call, infrared_signal_is_raw() will return true. + * + * @param[in,out] signal pointer to the destination instance. + * @param[in] timings pointer to an array containing the raw signal timings. + * @param[in] timings_size number of elements in the timings array. + * @param[in] frequency signal carrier frequency, in Hertz. + * @param[in] duty_cycle signal duty cycle, fraction between 0 and 1. + */ void infrared_signal_set_raw_signal( InfraredSignal* signal, const uint32_t* timings, size_t timings_size, uint32_t frequency, float duty_cycle); -InfraredRawSignal* infrared_signal_get_raw_signal(InfraredSignal* signal); +/** + * @brief Get the raw signal held by an InfraredSignal instance. + * + * @warning the instance MUST hold a *raw* signal, otherwise undefined behaviour will occur. + * + * @param[in] signal pointer to the instance to be queried. + * @returns pointer to the raw signal structure held by the instance. + */ +const InfraredRawSignal* infrared_signal_get_raw_signal(const InfraredSignal* signal); + +/** + * @brief Set an InfraredInstance to hold a parsed signal. + * + * Any instance's previous contents will be automatically deleted before + * copying the raw signal. + * + * After this call, infrared_signal_is_raw() will return false. + * + * @param[in,out] signal pointer to the destination instance. + * @param[in] message pointer to the message containing the parsed signal. + */ void infrared_signal_set_message(InfraredSignal* signal, const InfraredMessage* message); -InfraredMessage* infrared_signal_get_message(InfraredSignal* signal); -bool infrared_signal_save(InfraredSignal* signal, FlipperFormat* ff, const char* name); +/** + * @brief Get the parsed signal held by an InfraredSignal instance. + * + * @warning the instance MUST hold a *parsed* signal, otherwise undefined behaviour will occur. + * + * @param[in] signal pointer to the instance to be queried. + * @returns pointer to the parsed signal structure held by the instance. + */ +const InfraredMessage* infrared_signal_get_message(const InfraredSignal* signal); + +/** + * @brief Read a signal from a FlipperFormat file into an InfraredSignal instance. + * + * The file must be allocated and open prior to this call. The seek position determines + * which signal will be read (if there is more than one in the file). Calling this function + * repeatedly will result in all signals in the file to be read until no more are left. + * + * @param[in,out] signal pointer to the instance to be read into. + * @param[in,out] ff pointer to the FlipperFormat file instance to read from. + * @param[out] name pointer to the string to hold the signal name. Must be properly allocated. + * @returns true if a signal was successfully read, false otherwise (e.g. no more signals to read). + */ bool infrared_signal_read(InfraredSignal* signal, FlipperFormat* ff, FuriString* name); -bool infrared_signal_search_and_read( + +/** + * @brief Read a signal name from a FlipperFormat file. + * + * Same behaviour as infrared_signal_read(), but only the name is read. + * + * @param[in,out] ff pointer to the FlipperFormat file instance to read from. + * @param[out] name pointer to the string to hold the signal name. Must be properly allocated. + * @returns true if a signal name was successfully read, false otherwise (e.g. no more signals to read). + */ +bool infrared_signal_read_name(FlipperFormat* ff, FuriString* name); + +/** + * @brief Read a signal with a particular name from a FlipperFormat file into an InfraredSignal instance. + * + * This function will look for a signal with the given name and if found, attempt to read it. + * Same considerations apply as to infrared_signal_read(). + * + * @param[in,out] signal pointer to the instance to be read into. + * @param[in,out] ff pointer to the FlipperFormat file instance to read from. + * @param[in] name pointer to a zero-terminated string containing the requested signal name. + * @returns true if a signal was found and successfully read, false otherwise (e.g. the signal was not found). + */ +bool infrared_signal_search_by_name_and_read( InfraredSignal* signal, FlipperFormat* ff, - const FuriString* name); + const char* name); -void infrared_signal_transmit(InfraredSignal* signal); +/** + * @brief Read a signal with a particular index from a FlipperFormat file into an InfraredSignal instance. + * + * This function will look for a signal with the given index and if found, attempt to read it. + * Same considerations apply as to infrared_signal_read(). + * + * @param[in,out] signal pointer to the instance to be read into. + * @param[in,out] ff pointer to the FlipperFormat file instance to read from. + * @param[in] index the requested signal index. + * @returns true if a signal was found and successfully read, false otherwise (e.g. the signal was not found). + */ +bool infrared_signal_search_by_index_and_read( + InfraredSignal* signal, + FlipperFormat* ff, + size_t index); + +/** + * @brief Save a signal contained in an InfraredSignal instance to a FlipperFormat file. + * + * The file must be allocated and open prior to this call. Additionally, an appropriate header + * must be already written into the file. + * + * @param[in] signal pointer to the instance holding the signal to be saved. + * @param[in,out] ff pointer to the FlipperFormat file instance to write to. + * @param[in] name pointer to a zero-terminated string contating the name of the signal. + */ +bool infrared_signal_save(const InfraredSignal* signal, FlipperFormat* ff, const char* name); + +/** + * @brief Transmit a signal contained in an InfraredSignal instance. + * + * The transmission happens once per call using the built-in hardware (via HAL calls). + * + * @param[in] signal pointer to the instance holding the signal to be transmitted. + */ +void infrared_signal_transmit(const InfraredSignal* signal); diff --git a/assets/resources/infrared/assets/ac.ir b/applications/main/infrared/resources/infrared/assets/ac.ir similarity index 100% rename from assets/resources/infrared/assets/ac.ir rename to applications/main/infrared/resources/infrared/assets/ac.ir diff --git a/assets/resources/infrared/assets/audio.ir b/applications/main/infrared/resources/infrared/assets/audio.ir similarity index 100% rename from assets/resources/infrared/assets/audio.ir rename to applications/main/infrared/resources/infrared/assets/audio.ir diff --git a/assets/resources/infrared/assets/fans.ir b/applications/main/infrared/resources/infrared/assets/fans.ir similarity index 100% rename from assets/resources/infrared/assets/fans.ir rename to applications/main/infrared/resources/infrared/assets/fans.ir diff --git a/assets/resources/infrared/assets/projectors.ir b/applications/main/infrared/resources/infrared/assets/projectors.ir similarity index 100% rename from assets/resources/infrared/assets/projectors.ir rename to applications/main/infrared/resources/infrared/assets/projectors.ir diff --git a/assets/resources/infrared/assets/tv.ir b/applications/main/infrared/resources/infrared/assets/tv.ir similarity index 97% rename from assets/resources/infrared/assets/tv.ir rename to applications/main/infrared/resources/infrared/assets/tv.ir index e7a7525fe..d2164b16d 100755 --- a/assets/resources/infrared/assets/tv.ir +++ b/applications/main/infrared/resources/infrared/assets/tv.ir @@ -1,7 +1,7 @@ Filetype: IR library file Version: 1 -# Last Updated 1st Oct, 2023 -# Last Checked 1st Oct, 2023 +# Last Updated 29th Oct, 2023 +# Last Checked 29th Oct, 2023 # name: Power type: parsed @@ -2393,3 +2393,69 @@ type: parsed protocol: NECext address: 69 69 00 00 command: 0E F1 00 00 +# +name: Power +type: parsed +protocol: NECext +address: 01 3E 00 00 +command: 0A F5 00 00 +# +name: Mute +type: parsed +protocol: NECext +address: 01 3E 00 00 +command: 0B F4 00 00 +# +name: Vol_up +type: parsed +protocol: NECext +address: 01 3E 00 00 +command: 1E E1 00 00 +# +name: Vol_dn +type: parsed +protocol: NECext +address: 01 3E 00 00 +command: 5F A0 00 00 +# +name: Ch_next +type: parsed +protocol: NECext +address: 01 3E 00 00 +command: 1F E0 00 00 +# +name: Ch_prev +type: parsed +protocol: NECext +address: 01 3E 00 00 +command: 5C A3 00 00 +# +name: Power +type: parsed +protocol: NEC +address: 38 00 00 00 +command: 01 00 00 00 +# +name: Vol_up +type: parsed +protocol: NEC +address: 38 00 00 00 +command: 0C 00 00 00 +# +name: Vol_dn +type: parsed +protocol: NEC +address: 38 00 00 00 +command: 10 00 00 00 +# +name: Ch_next +type: parsed +protocol: NEC +address: 38 00 00 00 +command: 18 00 00 00 +# +name: Ch_prev +type: parsed +protocol: NEC +address: 38 00 00 00 +command: 1C 00 00 00 diff --git a/applications/main/infrared/scenes/common/infrared_scene_universal_common.c b/applications/main/infrared/scenes/common/infrared_scene_universal_common.c index 96f28cc48..4967d1956 100644 --- a/applications/main/infrared/scenes/common/infrared_scene_universal_common.c +++ b/applications/main/infrared/scenes/common/infrared_scene_universal_common.c @@ -1,20 +1,21 @@ -#include "../../infrared_i.h" +#include "../../infrared_app_i.h" #include void infrared_scene_universal_common_item_callback(void* context, uint32_t index) { - Infrared* infrared = context; + InfraredApp* infrared = context; uint32_t event = infrared_custom_event_pack(InfraredCustomEventTypeButtonSelected, index); view_dispatcher_send_custom_event(infrared->view_dispatcher, event); } static void infrared_scene_universal_common_progress_back_callback(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; uint32_t event = infrared_custom_event_pack(InfraredCustomEventTypeBackPressed, -1); view_dispatcher_send_custom_event(infrared->view_dispatcher, event); } -static void infrared_scene_universal_common_show_popup(Infrared* infrared, uint32_t record_count) { +static void + infrared_scene_universal_common_show_popup(InfraredApp* infrared, uint32_t record_count) { ViewStack* view_stack = infrared->view_stack; InfraredProgressView* progress = infrared->progress; infrared_progress_view_set_progress_total(progress, record_count); @@ -24,7 +25,7 @@ static void infrared_scene_universal_common_show_popup(Infrared* infrared, uint3 infrared_play_notification_message(infrared, InfraredNotificationMessageBlinkStartSend); } -static void infrared_scene_universal_common_hide_popup(Infrared* infrared) { +static void infrared_scene_universal_common_hide_popup(InfraredApp* infrared) { ViewStack* view_stack = infrared->view_stack; InfraredProgressView* progress = infrared->progress; view_stack_remove_view(view_stack, infrared_progress_view_get_view(progress)); @@ -32,12 +33,12 @@ static void infrared_scene_universal_common_hide_popup(Infrared* infrared) { } void infrared_scene_universal_common_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_stack_add_view(infrared->view_stack, button_panel_get_view(infrared->button_panel)); } bool infrared_scene_universal_common_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; InfraredBruteForce* brute_force = infrared->brute_force; bool consumed = false; @@ -84,7 +85,7 @@ bool infrared_scene_universal_common_on_event(void* context, SceneManagerEvent e } void infrared_scene_universal_common_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; ButtonPanel* button_panel = infrared->button_panel; view_stack_remove_view(infrared->view_stack, button_panel_get_view(button_panel)); infrared_brute_force_reset(infrared->brute_force); diff --git a/applications/main/infrared/scenes/infrared_scene_ask_back.c b/applications/main/infrared/scenes/infrared_scene_ask_back.c index 77fc97f98..f97a38bb0 100644 --- a/applications/main/infrared/scenes/infrared_scene_ask_back.c +++ b/applications/main/infrared/scenes/infrared_scene_ask_back.c @@ -1,12 +1,12 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" static void infrared_scene_dialog_result_callback(DialogExResult result, void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event(infrared->view_dispatcher, result); } void infrared_scene_ask_back_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; DialogEx* dialog_ex = infrared->dialog_ex; if(infrared->app_state.is_learning_new_remote) { @@ -28,7 +28,7 @@ void infrared_scene_ask_back_on_enter(void* context) { } bool infrared_scene_ask_back_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; bool consumed = false; @@ -54,6 +54,6 @@ bool infrared_scene_ask_back_on_event(void* context, SceneManagerEvent event) { } void infrared_scene_ask_back_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; dialog_ex_reset(infrared->dialog_ex); } diff --git a/applications/main/infrared/scenes/infrared_scene_ask_retry.c b/applications/main/infrared/scenes/infrared_scene_ask_retry.c index 602e470c7..365ed5c81 100644 --- a/applications/main/infrared/scenes/infrared_scene_ask_retry.c +++ b/applications/main/infrared/scenes/infrared_scene_ask_retry.c @@ -1,12 +1,12 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" static void infrared_scene_dialog_result_callback(DialogExResult result, void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event(infrared->view_dispatcher, result); } void infrared_scene_ask_retry_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; DialogEx* dialog_ex = infrared->dialog_ex; dialog_ex_set_header(dialog_ex, "Retry Reading?", 64, 11, AlignCenter, AlignTop); @@ -23,7 +23,7 @@ void infrared_scene_ask_retry_on_enter(void* context) { } bool infrared_scene_ask_retry_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; bool consumed = false; @@ -43,6 +43,6 @@ bool infrared_scene_ask_retry_on_event(void* context, SceneManagerEvent event) { } void infrared_scene_ask_retry_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; dialog_ex_reset(infrared->dialog_ex); } diff --git a/applications/main/infrared/scenes/infrared_scene_debug.c b/applications/main/infrared/scenes/infrared_scene_debug.c index 204978697..adffbc83a 100644 --- a/applications/main/infrared/scenes/infrared_scene_debug.c +++ b/applications/main/infrared/scenes/infrared_scene_debug.c @@ -1,7 +1,7 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" void infrared_scene_debug_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; InfraredWorker* worker = infrared->worker; infrared_worker_rx_set_received_signal_callback( @@ -14,16 +14,16 @@ void infrared_scene_debug_on_enter(void* context) { } bool infrared_scene_debug_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == InfraredCustomEventTypeSignalReceived) { InfraredDebugView* debug_view = infrared->debug_view; - InfraredSignal* signal = infrared->received_signal; + InfraredSignal* signal = infrared->current_signal; if(infrared_signal_is_raw(signal)) { - InfraredRawSignal* raw = infrared_signal_get_raw_signal(signal); + const InfraredRawSignal* raw = infrared_signal_get_raw_signal(signal); infrared_debug_view_set_text(debug_view, "RAW\n%d samples\n", raw->timings_size); printf("RAW, %zu samples:\r\n", raw->timings_size); @@ -33,7 +33,7 @@ bool infrared_scene_debug_on_event(void* context, SceneManagerEvent event) { printf("\r\n"); } else { - InfraredMessage* message = infrared_signal_get_message(signal); + const InfraredMessage* message = infrared_signal_get_message(signal); infrared_debug_view_set_text( debug_view, "%s\nA:0x%0*lX\nC:0x%0*lX\n%s\n", @@ -61,7 +61,7 @@ bool infrared_scene_debug_on_event(void* context, SceneManagerEvent event) { } void infrared_scene_debug_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; InfraredWorker* worker = infrared->worker; infrared_worker_rx_stop(worker); infrared_worker_rx_enable_blink_on_receiving(worker, false); diff --git a/applications/main/infrared/scenes/infrared_scene_debug_settings.c b/applications/main/infrared/scenes/infrared_scene_debug_settings.c index bef666275..badfd172a 100644 --- a/applications/main/infrared/scenes/infrared_scene_debug_settings.c +++ b/applications/main/infrared/scenes/infrared_scene_debug_settings.c @@ -1,4 +1,4 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include uint8_t value_index_ir; @@ -10,7 +10,7 @@ const char* const infrared_debug_cfg_variables_text[] = { }; static void infrared_scene_debug_settings_changed(VariableItem* item) { - Infrared* infrared = variable_item_get_context(item); + InfraredApp* infrared = variable_item_get_context(item); value_index_ir = variable_item_get_current_value_index(item); UNUSED(infrared); @@ -35,12 +35,12 @@ static void infrared_scene_debug_settings_power_changed(VariableItem* item) { } static void infrared_debug_settings_start_var_list_enter_callback(void* context, uint32_t index) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event(infrared->view_dispatcher, index); } void infrared_scene_debug_settings_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; VariableItemList* variable_item_list = infrared->variable_item_list; @@ -72,7 +72,7 @@ void infrared_scene_debug_settings_on_enter(void* context) { } bool infrared_scene_debug_settings_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; UNUSED(infrared); UNUSED(event); @@ -80,6 +80,6 @@ bool infrared_scene_debug_settings_on_event(void* context, SceneManagerEvent eve } void infrared_scene_debug_settings_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; variable_item_list_reset(infrared->variable_item_list); } diff --git a/applications/main/infrared/scenes/infrared_scene_edit.c b/applications/main/infrared/scenes/infrared_scene_edit.c index 02bba7a3f..c22e95396 100644 --- a/applications/main/infrared/scenes/infrared_scene_edit.c +++ b/applications/main/infrared/scenes/infrared_scene_edit.c @@ -1,4 +1,4 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" typedef enum { SubmenuIndexAddButton, @@ -10,12 +10,12 @@ typedef enum { } SubmenuIndex; static void infrared_scene_edit_submenu_callback(void* context, uint32_t index) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event(infrared->view_dispatcher, index); } void infrared_scene_edit_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Submenu* submenu = infrared->submenu; SceneManager* scene_manager = infrared->scene_manager; @@ -64,7 +64,7 @@ void infrared_scene_edit_on_enter(void* context) { } bool infrared_scene_edit_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; bool consumed = false; @@ -106,6 +106,6 @@ bool infrared_scene_edit_on_event(void* context, SceneManagerEvent event) { } void infrared_scene_edit_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; submenu_reset(infrared->submenu); } diff --git a/applications/main/infrared/scenes/infrared_scene_edit_button_select.c b/applications/main/infrared/scenes/infrared_scene_edit_button_select.c index 5f5a1d8fa..3fd59b579 100644 --- a/applications/main/infrared/scenes/infrared_scene_edit_button_select.c +++ b/applications/main/infrared/scenes/infrared_scene_edit_button_select.c @@ -1,12 +1,12 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" static void infrared_scene_edit_button_select_submenu_callback(void* context, uint32_t index) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event(infrared->view_dispatcher, index); } void infrared_scene_edit_button_select_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Submenu* submenu = infrared->submenu; InfraredRemote* remote = infrared->remote; InfraredAppState* app_state = &infrared->app_state; @@ -16,16 +16,16 @@ void infrared_scene_edit_button_select_on_enter(void* context) { "Delete Button:"; submenu_set_header(submenu, header); - const size_t button_count = infrared_remote_get_button_count(remote); + const size_t button_count = infrared_remote_get_signal_count(remote); for(size_t i = 0; i < button_count; ++i) { - InfraredRemoteButton* button = infrared_remote_get_button(remote, i); submenu_add_item( submenu, - infrared_remote_button_get_name(button), + infrared_remote_get_signal_name(remote, i), i, infrared_scene_edit_button_select_submenu_callback, context); } + if(button_count && app_state->current_button_index != InfraredButtonIndexNone) { submenu_set_selected_item(submenu, app_state->current_button_index); app_state->current_button_index = InfraredButtonIndexNone; @@ -35,7 +35,7 @@ void infrared_scene_edit_button_select_on_enter(void* context) { } bool infrared_scene_edit_button_select_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; InfraredAppState* app_state = &infrared->app_state; SceneManager* scene_manager = infrared->scene_manager; bool consumed = false; @@ -48,7 +48,7 @@ bool infrared_scene_edit_button_select_on_event(void* context, SceneManagerEvent } else if(edit_mode == InfraredEditModeDelete) { scene_manager_next_scene(scene_manager, InfraredSceneEditDelete); } else { - furi_assert(0); + furi_crash(); } consumed = true; } @@ -57,6 +57,6 @@ bool infrared_scene_edit_button_select_on_event(void* context, SceneManagerEvent } void infrared_scene_edit_button_select_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; submenu_reset(infrared->submenu); } diff --git a/applications/main/infrared/scenes/infrared_scene_edit_delete.c b/applications/main/infrared/scenes/infrared_scene_edit_delete.c index 4dfc054fb..0cb88efdb 100644 --- a/applications/main/infrared/scenes/infrared_scene_edit_delete.c +++ b/applications/main/infrared/scenes/infrared_scene_edit_delete.c @@ -1,42 +1,49 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" static void infrared_scene_edit_delete_dialog_result_callback(DialogExResult result, void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event(infrared->view_dispatcher, result); } void infrared_scene_edit_delete_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; DialogEx* dialog_ex = infrared->dialog_ex; InfraredRemote* remote = infrared->remote; const InfraredEditTarget edit_target = infrared->app_state.edit_target; if(edit_target == InfraredEditTargetButton) { - int32_t current_button_index = infrared->app_state.current_button_index; - furi_assert(current_button_index != InfraredButtonIndexNone); - dialog_ex_set_header(dialog_ex, "Delete Button?", 64, 0, AlignCenter, AlignTop); - InfraredRemoteButton* current_button = - infrared_remote_get_button(remote, current_button_index); - InfraredSignal* signal = infrared_remote_button_get_signal(current_button); - if(infrared_signal_is_raw(signal)) { - const InfraredRawSignal* raw = infrared_signal_get_raw_signal(signal); + const int32_t current_button_index = infrared->app_state.current_button_index; + furi_check(current_button_index != InfraredButtonIndexNone); + + if(!infrared_remote_load_signal(remote, infrared->current_signal, current_button_index)) { + infrared_show_error_message( + infrared, + "Failed to load\n\"%s\"", + infrared_remote_get_signal_name(remote, current_button_index)); + scene_manager_previous_scene(infrared->scene_manager); + return; + } + + if(infrared_signal_is_raw(infrared->current_signal)) { + const InfraredRawSignal* raw = + infrared_signal_get_raw_signal(infrared->current_signal); infrared_text_store_set( infrared, 0, - "%s\nRAW\n%ld samples", - infrared_remote_button_get_name(current_button), + "%s\nRAW\n%zu samples", + infrared_remote_get_signal_name(remote, current_button_index), raw->timings_size); } else { - const InfraredMessage* message = infrared_signal_get_message(signal); + const InfraredMessage* message = infrared_signal_get_message(infrared->current_signal); infrared_text_store_set( infrared, 0, "%s\n%s\nA=0x%0*lX C=0x%0*lX", - infrared_remote_button_get_name(current_button), + infrared_remote_get_signal_name(remote, current_button_index), infrared_get_protocol_name(message->protocol), ROUND_UP_TO(infrared_get_protocol_address_length(message->protocol), 4), message->address, @@ -49,11 +56,11 @@ void infrared_scene_edit_delete_on_enter(void* context) { infrared_text_store_set( infrared, 0, - "%s\n with %lu buttons", + "%s\n with %zu buttons", infrared_remote_get_name(remote), - infrared_remote_get_button_count(remote)); + infrared_remote_get_signal_count(remote)); } else { - furi_assert(0); + furi_crash(); } dialog_ex_set_text(dialog_ex, infrared->text_store[0], 64, 31, AlignCenter, AlignCenter); @@ -63,11 +70,14 @@ void infrared_scene_edit_delete_on_enter(void* context) { dialog_ex_set_result_callback(dialog_ex, infrared_scene_edit_delete_dialog_result_callback); dialog_ex_set_context(dialog_ex, context); - view_dispatcher_switch_to_view(infrared->view_dispatcher, InfraredViewDialogEx); + view_set_orientation(view_stack_get_view(infrared->view_stack), ViewOrientationHorizontal); + view_stack_add_view(infrared->view_stack, dialog_ex_get_view(infrared->dialog_ex)); + + view_dispatcher_switch_to_view(infrared->view_dispatcher, InfraredViewStack); } bool infrared_scene_edit_delete_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; bool consumed = false; @@ -83,18 +93,24 @@ bool infrared_scene_edit_delete_on_event(void* context, SceneManagerEvent event) if(edit_target == InfraredEditTargetButton) { furi_assert(app_state->current_button_index != InfraredButtonIndexNone); - success = infrared_remote_delete_button(remote, app_state->current_button_index); + infrared_show_loading_popup(infrared, true); + success = infrared_remote_delete_signal(remote, app_state->current_button_index); + infrared_show_loading_popup(infrared, false); app_state->current_button_index = InfraredButtonIndexNone; } else if(edit_target == InfraredEditTargetRemote) { success = infrared_remote_remove(remote); app_state->current_button_index = InfraredButtonIndexNone; } else { - furi_assert(0); + furi_crash(); } if(success) { scene_manager_next_scene(scene_manager, InfraredSceneEditDeleteDone); } else { + infrared_show_error_message( + infrared, + "Failed to\ndelete %s", + edit_target == InfraredEditTargetButton ? "button" : "file"); const uint32_t possible_scenes[] = {InfraredSceneRemoteList, InfraredSceneStart}; scene_manager_search_and_switch_to_previous_scene_one_of( scene_manager, possible_scenes, COUNT_OF(possible_scenes)); @@ -107,6 +123,6 @@ bool infrared_scene_edit_delete_on_event(void* context, SceneManagerEvent event) } void infrared_scene_edit_delete_on_exit(void* context) { - Infrared* infrared = context; - UNUSED(infrared); + InfraredApp* infrared = context; + view_stack_remove_view(infrared->view_stack, dialog_ex_get_view(infrared->dialog_ex)); } diff --git a/applications/main/infrared/scenes/infrared_scene_edit_delete_done.c b/applications/main/infrared/scenes/infrared_scene_edit_delete_done.c index 49a299d2a..9205db4c4 100644 --- a/applications/main/infrared/scenes/infrared_scene_edit_delete_done.c +++ b/applications/main/infrared/scenes/infrared_scene_edit_delete_done.c @@ -1,7 +1,7 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" void infrared_scene_edit_delete_done_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Popup* popup = infrared->popup; popup_set_icon(popup, 0, 2, &I_DolphinMafia_115x62); @@ -16,7 +16,7 @@ void infrared_scene_edit_delete_done_on_enter(void* context) { } bool infrared_scene_edit_delete_done_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; bool consumed = false; @@ -33,7 +33,7 @@ bool infrared_scene_edit_delete_done_on_event(void* context, SceneManagerEvent e view_dispatcher_stop(infrared->view_dispatcher); } } else { - furi_assert(0); + furi_crash(); } consumed = true; } @@ -43,6 +43,6 @@ bool infrared_scene_edit_delete_done_on_event(void* context, SceneManagerEvent e } void infrared_scene_edit_delete_done_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; UNUSED(infrared); } diff --git a/applications/main/infrared/scenes/infrared_scene_edit_move.c b/applications/main/infrared/scenes/infrared_scene_edit_move.c index 370c352db..4959a8310 100644 --- a/applications/main/infrared/scenes/infrared_scene_edit_move.c +++ b/applications/main/infrared/scenes/infrared_scene_edit_move.c @@ -1,44 +1,69 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" -static void infrared_scene_move_button(uint32_t index_old, uint32_t index_new, void* context) { - InfraredRemote* remote = context; - furi_assert(remote); - infrared_remote_move_button(remote, index_old, index_new); -} +static void infrared_scene_edit_move_button_callback( + uint32_t index_old, + uint32_t index_new, + void* context) { + InfraredApp* infrared = context; + furi_assert(infrared); -static const char* infrared_scene_get_btn_name(uint32_t index, void* context) { - InfraredRemote* remote = context; - furi_assert(remote); - InfraredRemoteButton* button = infrared_remote_get_button(remote, index); - return (infrared_remote_button_get_name(button)); + infrared->app_state.prev_button_index = index_old; + infrared->app_state.current_button_index = index_new; + + view_dispatcher_send_custom_event( + infrared->view_dispatcher, InfraredCustomEventTypeButtonSelected); } void infrared_scene_edit_move_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; InfraredRemote* remote = infrared->remote; - infrared_move_view_set_callback(infrared->move_view, infrared_scene_move_button); + for(size_t i = 0; i < infrared_remote_get_signal_count(remote); ++i) { + infrared_move_view_add_item( + infrared->move_view, infrared_remote_get_signal_name(remote, i)); + } - uint32_t btn_count = infrared_remote_get_button_count(remote); - infrared_move_view_list_init( - infrared->move_view, btn_count, infrared_scene_get_btn_name, remote); - infrared_move_view_list_update(infrared->move_view); + infrared_move_view_set_callback( + infrared->move_view, infrared_scene_edit_move_button_callback, infrared); - view_dispatcher_switch_to_view(infrared->view_dispatcher, InfraredViewMove); + view_set_orientation(view_stack_get_view(infrared->view_stack), ViewOrientationHorizontal); + view_stack_add_view(infrared->view_stack, infrared_move_view_get_view(infrared->move_view)); + + view_dispatcher_switch_to_view(infrared->view_dispatcher, InfraredViewStack); } bool infrared_scene_edit_move_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; bool consumed = false; - UNUSED(event); - UNUSED(infrared); + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == InfraredCustomEventTypeButtonSelected) { + infrared_show_loading_popup(infrared, true); + const bool button_moved = infrared_remote_move_signal( + infrared->remote, + infrared->app_state.prev_button_index, + infrared->app_state.current_button_index); + infrared_show_loading_popup(infrared, false); + + if(!button_moved) { + infrared_show_error_message( + infrared, + "Failed to move\n\"%s\"", + infrared_remote_get_signal_name( + infrared->remote, infrared->app_state.current_button_index)); + scene_manager_search_and_switch_to_previous_scene( + infrared->scene_manager, InfraredSceneRemoteList); + } + + consumed = true; + } + } return consumed; } void infrared_scene_edit_move_on_exit(void* context) { - Infrared* infrared = context; - InfraredRemote* remote = infrared->remote; - infrared_remote_store(remote); + InfraredApp* infrared = context; + view_stack_remove_view(infrared->view_stack, infrared_move_view_get_view(infrared->move_view)); + infrared_move_view_reset(infrared->move_view); } diff --git a/applications/main/infrared/scenes/infrared_scene_edit_rename.c b/applications/main/infrared/scenes/infrared_scene_edit_rename.c index a2199215d..178690926 100644 --- a/applications/main/infrared/scenes/infrared_scene_edit_rename.c +++ b/applications/main/infrared/scenes/infrared_scene_edit_rename.c @@ -1,10 +1,10 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include #include void infrared_scene_edit_rename_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; InfraredRemote* remote = infrared->remote; TextInput* text_input = infrared->text_input; size_t enter_name_length = 0; @@ -14,14 +14,12 @@ void infrared_scene_edit_rename_on_enter(void* context) { text_input_set_header_text(text_input, "Name the button"); const int32_t current_button_index = infrared->app_state.current_button_index; - furi_assert(current_button_index != InfraredButtonIndexNone); + furi_check(current_button_index != InfraredButtonIndexNone); - InfraredRemoteButton* current_button = - infrared_remote_get_button(remote, current_button_index); enter_name_length = INFRARED_MAX_BUTTON_NAME_LENGTH; strncpy( infrared->text_store[0], - infrared_remote_button_get_name(current_button), + infrared_remote_get_signal_name(remote, current_button_index), enter_name_length); } else if(edit_target == InfraredEditTargetRemote) { @@ -44,7 +42,7 @@ void infrared_scene_edit_rename_on_enter(void* context) { furi_string_free(folder_path); } else { - furi_assert(0); + furi_crash(); } text_input_set_result_callback( @@ -55,11 +53,14 @@ void infrared_scene_edit_rename_on_enter(void* context) { enter_name_length, false); - view_dispatcher_switch_to_view(infrared->view_dispatcher, InfraredViewTextInput); + view_set_orientation(view_stack_get_view(infrared->view_stack), ViewOrientationHorizontal); + view_stack_add_view(infrared->view_stack, text_input_get_view(infrared->text_input)); + + view_dispatcher_switch_to_view(infrared->view_dispatcher, InfraredViewStack); } bool infrared_scene_edit_rename_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; InfraredRemote* remote = infrared->remote; SceneManager* scene_manager = infrared->scene_manager; InfraredAppState* app_state = &infrared->app_state; @@ -72,18 +73,24 @@ bool infrared_scene_edit_rename_on_event(void* context, SceneManagerEvent event) if(edit_target == InfraredEditTargetButton) { const int32_t current_button_index = app_state->current_button_index; furi_assert(current_button_index != InfraredButtonIndexNone); - success = infrared_remote_rename_button( - remote, infrared->text_store[0], current_button_index); + infrared_show_loading_popup(infrared, true); + success = infrared_remote_rename_signal( + remote, current_button_index, infrared->text_store[0]); + infrared_show_loading_popup(infrared, false); app_state->current_button_index = InfraredButtonIndexNone; } else if(edit_target == InfraredEditTargetRemote) { success = infrared_rename_current_remote(infrared, infrared->text_store[0]); } else { - furi_assert(0); + furi_crash(); } if(success) { scene_manager_next_scene(scene_manager, InfraredSceneEditRenameDone); } else { + infrared_show_error_message( + infrared, + "Failed to\nrename %s", + edit_target == InfraredEditTargetButton ? "button" : "file"); scene_manager_search_and_switch_to_previous_scene( scene_manager, InfraredSceneRemoteList); } @@ -95,9 +102,11 @@ bool infrared_scene_edit_rename_on_event(void* context, SceneManagerEvent event) } void infrared_scene_edit_rename_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; TextInput* text_input = infrared->text_input; + view_stack_remove_view(infrared->view_stack, text_input_get_view(text_input)); + void* validator_context = text_input_get_validator_callback_context(text_input); text_input_set_validator(text_input, NULL, NULL); diff --git a/applications/main/infrared/scenes/infrared_scene_edit_rename_done.c b/applications/main/infrared/scenes/infrared_scene_edit_rename_done.c index 6c7096e17..35f515989 100644 --- a/applications/main/infrared/scenes/infrared_scene_edit_rename_done.c +++ b/applications/main/infrared/scenes/infrared_scene_edit_rename_done.c @@ -1,7 +1,7 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" void infrared_scene_edit_rename_done_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Popup* popup = infrared->popup; popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); @@ -16,7 +16,7 @@ void infrared_scene_edit_rename_done_on_enter(void* context) { } bool infrared_scene_edit_rename_done_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { @@ -33,6 +33,6 @@ bool infrared_scene_edit_rename_done_on_event(void* context, SceneManagerEvent e } void infrared_scene_edit_rename_done_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; UNUSED(infrared); } diff --git a/applications/main/infrared/scenes/infrared_scene_error_databases.c b/applications/main/infrared/scenes/infrared_scene_error_databases.c index 4ed4dee58..f51f83f25 100644 --- a/applications/main/infrared/scenes/infrared_scene_error_databases.c +++ b/applications/main/infrared/scenes/infrared_scene_error_databases.c @@ -1,7 +1,7 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" void infrared_scene_error_databases_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Popup* popup = infrared->popup; popup_set_icon(popup, 5, 11, &I_SDQuestion_35x43); @@ -16,7 +16,7 @@ void infrared_scene_error_databases_on_enter(void* context) { } bool infrared_scene_error_databases_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { @@ -31,7 +31,7 @@ bool infrared_scene_error_databases_on_event(void* context, SceneManagerEvent ev } void infrared_scene_error_databases_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; popup_reset(infrared->popup); infrared_play_notification_message(infrared, InfraredNotificationMessageYellowOff); } diff --git a/applications/main/infrared/scenes/infrared_scene_learn.c b/applications/main/infrared/scenes/infrared_scene_learn.c index 46646c6d6..bcd0a2cd0 100644 --- a/applications/main/infrared/scenes/infrared_scene_learn.c +++ b/applications/main/infrared/scenes/infrared_scene_learn.c @@ -1,8 +1,8 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include void infrared_scene_learn_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Popup* popup = infrared->popup; InfraredWorker* worker = infrared->worker; @@ -21,7 +21,7 @@ void infrared_scene_learn_on_enter(void* context) { } bool infrared_scene_learn_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { @@ -37,7 +37,7 @@ bool infrared_scene_learn_on_event(void* context, SceneManagerEvent event) { } void infrared_scene_learn_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Popup* popup = infrared->popup; infrared_worker_rx_set_received_signal_callback(infrared->worker, NULL, NULL); infrared_worker_rx_stop(infrared->worker); diff --git a/applications/main/infrared/scenes/infrared_scene_learn_done.c b/applications/main/infrared/scenes/infrared_scene_learn_done.c index 54b7da724..b4eb38331 100644 --- a/applications/main/infrared/scenes/infrared_scene_learn_done.c +++ b/applications/main/infrared/scenes/infrared_scene_learn_done.c @@ -1,7 +1,7 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" void infrared_scene_learn_done_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Popup* popup = infrared->popup; popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); @@ -21,7 +21,7 @@ void infrared_scene_learn_done_on_enter(void* context) { } bool infrared_scene_learn_done_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { @@ -38,7 +38,7 @@ bool infrared_scene_learn_done_on_event(void* context, SceneManagerEvent event) } void infrared_scene_learn_done_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; infrared->app_state.is_learning_new_remote = false; popup_set_header(infrared->popup, NULL, 0, 0, AlignLeft, AlignTop); } diff --git a/applications/main/infrared/scenes/infrared_scene_learn_enter_name.c b/applications/main/infrared/scenes/infrared_scene_learn_enter_name.c index 104a4cb7b..be46a8691 100644 --- a/applications/main/infrared/scenes/infrared_scene_learn_enter_name.c +++ b/applications/main/infrared/scenes/infrared_scene_learn_enter_name.c @@ -1,16 +1,16 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include void infrared_scene_learn_enter_name_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; TextInput* text_input = infrared->text_input; - InfraredSignal* signal = infrared->received_signal; + InfraredSignal* signal = infrared->current_signal; if(infrared_signal_is_raw(signal)) { - InfraredRawSignal* raw = infrared_signal_get_raw_signal(signal); - infrared_text_store_set(infrared, 0, "RAW_%d", raw->timings_size); + const InfraredRawSignal* raw = infrared_signal_get_raw_signal(signal); + infrared_text_store_set(infrared, 0, "RAW_%zu", raw->timings_size); } else { - InfraredMessage* message = infrared_signal_get_message(signal); + const InfraredMessage* message = infrared_signal_get_message(signal); infrared_text_store_set( infrared, 0, @@ -28,31 +28,32 @@ void infrared_scene_learn_enter_name_on_enter(void* context) { infrared->text_store[0], INFRARED_MAX_BUTTON_NAME_LENGTH, true); + view_dispatcher_switch_to_view(infrared->view_dispatcher, InfraredViewTextInput); } bool infrared_scene_learn_enter_name_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; - InfraredSignal* signal = infrared->received_signal; + InfraredApp* infrared = context; + InfraredSignal* signal = infrared->current_signal; SceneManager* scene_manager = infrared->scene_manager; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == InfraredCustomEventTypeTextEditDone) { - bool success = false; - if(infrared->app_state.is_learning_new_remote) { - success = - infrared_add_remote_with_button(infrared, infrared->text_store[0], signal); - } else { - success = - infrared_remote_add_button(infrared->remote, infrared->text_store[0], signal); - } + const char* signal_name = infrared->text_store[0]; + const bool success = + infrared->app_state.is_learning_new_remote ? + infrared_add_remote_with_button(infrared, signal_name, signal) : + infrared_remote_append_signal(infrared->remote, signal, signal_name); if(success) { scene_manager_next_scene(scene_manager, InfraredSceneLearnDone); dolphin_deed(DolphinDeedIrSave); } else { - dialog_message_show_storage_error(infrared->dialogs, "Failed to save file"); + infrared_show_error_message( + infrared, + "Failed to\n%s", + infrared->app_state.is_learning_new_remote ? "create file" : "add signal"); const uint32_t possible_scenes[] = {InfraredSceneRemoteList, InfraredSceneStart}; scene_manager_search_and_switch_to_previous_scene_one_of( scene_manager, possible_scenes, COUNT_OF(possible_scenes)); @@ -65,6 +66,6 @@ bool infrared_scene_learn_enter_name_on_event(void* context, SceneManagerEvent e } void infrared_scene_learn_enter_name_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; UNUSED(infrared); } diff --git a/applications/main/infrared/scenes/infrared_scene_learn_success.c b/applications/main/infrared/scenes/infrared_scene_learn_success.c index 469d4de9e..deb54bb5e 100644 --- a/applications/main/infrared/scenes/infrared_scene_learn_success.c +++ b/applications/main/infrared/scenes/infrared_scene_learn_success.c @@ -1,26 +1,26 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" static void infrared_scene_learn_success_dialog_result_callback(DialogExResult result, void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event(infrared->view_dispatcher, result); } void infrared_scene_learn_success_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; DialogEx* dialog_ex = infrared->dialog_ex; - InfraredSignal* signal = infrared->received_signal; + InfraredSignal* signal = infrared->current_signal; infrared_play_notification_message(infrared, InfraredNotificationMessageGreenOn); if(infrared_signal_is_raw(signal)) { - InfraredRawSignal* raw = infrared_signal_get_raw_signal(signal); + const InfraredRawSignal* raw = infrared_signal_get_raw_signal(signal); dialog_ex_set_header(dialog_ex, "Unknown", 95, 10, AlignCenter, AlignCenter); - infrared_text_store_set(infrared, 0, "%d samples", raw->timings_size); + infrared_text_store_set(infrared, 0, "%zu samples", raw->timings_size); dialog_ex_set_text(dialog_ex, infrared->text_store[0], 75, 23, AlignLeft, AlignTop); } else { - InfraredMessage* message = infrared_signal_get_message(signal); + const InfraredMessage* message = infrared_signal_get_message(signal); uint8_t addr_digits = ROUND_UP_TO(infrared_get_protocol_address_length(message->protocol), 4); uint8_t cmd_digits = @@ -56,7 +56,7 @@ void infrared_scene_learn_success_on_enter(void* context) { } bool infrared_scene_learn_success_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; const bool is_transmitter_idle = !infrared->app_state.is_transmitting; bool consumed = false; @@ -84,7 +84,7 @@ bool infrared_scene_learn_success_on_event(void* context, SceneManagerEvent even consumed = true; } else if(event.event == DialogExPressCenter) { infrared_play_notification_message(infrared, InfraredNotificationMessageGreenOff); - infrared_tx_start_received(infrared); + infrared_tx_start(infrared); consumed = true; } else if(event.event == DialogExReleaseCenter) { infrared_tx_stop(infrared); @@ -96,7 +96,7 @@ bool infrared_scene_learn_success_on_event(void* context, SceneManagerEvent even } void infrared_scene_learn_success_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; dialog_ex_reset(infrared->dialog_ex); infrared_play_notification_message(infrared, InfraredNotificationMessageGreenOff); } diff --git a/applications/main/infrared/scenes/infrared_scene_remote.c b/applications/main/infrared/scenes/infrared_scene_remote.c index c1f5b6627..6c1d1ec4e 100644 --- a/applications/main/infrared/scenes/infrared_scene_remote.c +++ b/applications/main/infrared/scenes/infrared_scene_remote.c @@ -1,14 +1,14 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" typedef enum { - ButtonIndexPlus = -2, + ButtonIndexLearn = -2, ButtonIndexEdit = -1, ButtonIndexNA = 0, } ButtonIndex; static void infrared_scene_remote_button_menu_callback(void* context, int32_t index, InputType type) { - Infrared* infrared = context; + InfraredApp* infrared = context; uint16_t custom_type; if(type == InputTypePress) { @@ -26,17 +26,15 @@ static void } void infrared_scene_remote_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; InfraredRemote* remote = infrared->remote; ButtonMenu* button_menu = infrared->button_menu; SceneManager* scene_manager = infrared->scene_manager; - size_t button_count = infrared_remote_get_button_count(remote); - for(size_t i = 0; i < button_count; ++i) { - InfraredRemoteButton* button = infrared_remote_get_button(remote, i); + for(size_t i = 0; i < infrared_remote_get_signal_count(remote); ++i) { button_menu_add_item( button_menu, - infrared_remote_button_get_name(button), + infrared_remote_get_signal_name(remote, i), i, infrared_scene_remote_button_menu_callback, ButtonMenuItemTypeCommon, @@ -46,7 +44,7 @@ void infrared_scene_remote_on_enter(void* context) { button_menu_add_item( button_menu, "+", - ButtonIndexPlus, + ButtonIndexLearn, infrared_scene_remote_button_menu_callback, ButtonMenuItemTypeControl, context); @@ -68,7 +66,7 @@ void infrared_scene_remote_on_enter(void* context) { } bool infrared_scene_remote_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; const bool is_transmitter_idle = !infrared->app_state.is_transmitting; bool consumed = false; @@ -97,7 +95,7 @@ bool infrared_scene_remote_on_event(void* context, SceneManagerEvent event) { if(is_transmitter_idle) { scene_manager_set_scene_state( scene_manager, InfraredSceneRemote, (unsigned)button_index); - if(button_index == ButtonIndexPlus) { + if(button_index == ButtonIndexLearn) { infrared->app_state.is_learning_new_remote = false; scene_manager_next_scene(scene_manager, InfraredSceneLearn); consumed = true; @@ -116,6 +114,6 @@ bool infrared_scene_remote_on_event(void* context, SceneManagerEvent event) { } void infrared_scene_remote_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; button_menu_reset(infrared->button_menu); } diff --git a/applications/main/infrared/scenes/infrared_scene_remote_list.c b/applications/main/infrared/scenes/infrared_scene_remote_list.c index 55f14416b..2276e270a 100644 --- a/applications/main/infrared/scenes/infrared_scene_remote_list.c +++ b/applications/main/infrared/scenes/infrared_scene_remote_list.c @@ -1,31 +1,34 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" void infrared_scene_remote_list_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; ViewDispatcher* view_dispatcher = infrared->view_dispatcher; + view_set_orientation(view_stack_get_view(infrared->view_stack), ViewOrientationVertical); + view_dispatcher_switch_to_view(view_dispatcher, InfraredViewStack); + DialogsFileBrowserOptions browser_options; dialog_file_browser_set_basic_options(&browser_options, INFRARED_APP_EXTENSION, &I_ir_10px); browser_options.base_path = INFRARED_APP_FOLDER; - bool success = dialog_file_browser_show( - infrared->dialogs, infrared->file_path, infrared->file_path, &browser_options); - - if(success) { - view_set_orientation(view_stack_get_view(infrared->view_stack), ViewOrientationVertical); - view_dispatcher_switch_to_view(view_dispatcher, InfraredViewStack); + while(dialog_file_browser_show( + infrared->dialogs, infrared->file_path, infrared->file_path, &browser_options)) { + const char* file_path = furi_string_get_cstr(infrared->file_path); infrared_show_loading_popup(infrared, true); - success = infrared_remote_load(infrared->remote, infrared->file_path); + const bool remote_loaded = infrared_remote_load(infrared->remote, file_path); infrared_show_loading_popup(infrared, false); + + if(remote_loaded) { + scene_manager_next_scene(scene_manager, InfraredSceneRemote); + return; + } else { + infrared_show_error_message(infrared, "Failed to load\n\"%s\"", file_path); + } } - if(success) { - scene_manager_next_scene(scene_manager, InfraredSceneRemote); - } else { - scene_manager_previous_scene(scene_manager); - } + scene_manager_previous_scene(scene_manager); } bool infrared_scene_remote_list_on_event(void* context, SceneManagerEvent event) { diff --git a/applications/main/infrared/scenes/infrared_scene_rpc.c b/applications/main/infrared/scenes/infrared_scene_rpc.c index 04f17416d..f3408fba4 100644 --- a/applications/main/infrared/scenes/infrared_scene_rpc.c +++ b/applications/main/infrared/scenes/infrared_scene_rpc.c @@ -1,6 +1,8 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include +#define TAG "InfraredApp" + typedef enum { InfraredRpcStateIdle, InfraredRpcStateLoaded, @@ -8,7 +10,7 @@ typedef enum { } InfraredRpcState; void infrared_scene_rpc_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Popup* popup = infrared->popup; popup_set_header(popup, "Infrared", 89, 42, AlignCenter, AlignBottom); @@ -27,7 +29,7 @@ void infrared_scene_rpc_on_enter(void* context) { } bool infrared_scene_rpc_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { @@ -38,12 +40,11 @@ bool infrared_scene_rpc_on_event(void* context, SceneManagerEvent event) { view_dispatcher_stop(infrared->view_dispatcher); } else if(event.event == InfraredCustomEventTypePopupClosed) { view_dispatcher_stop(infrared->view_dispatcher); - } else if(event.event == InfraredCustomEventTypeRpcLoad) { + } else if(event.event == InfraredCustomEventTypeRpcLoadFile) { bool result = false; - const char* arg = rpc_system_app_get_data(infrared->rpc_ctx); - if(arg && (state == InfraredRpcStateIdle)) { - furi_string_set(infrared->file_path, arg); - result = infrared_remote_load(infrared->remote, infrared->file_path); + if(state == InfraredRpcStateIdle) { + result = infrared_remote_load( + infrared->remote, furi_string_get_cstr(infrared->file_path)); if(result) { scene_manager_set_scene_state( infrared->scene_manager, InfraredSceneRpc, InfraredRpcStateLoaded); @@ -55,20 +56,35 @@ bool infrared_scene_rpc_on_event(void* context, SceneManagerEvent event) { popup_set_text( infrared->popup, infrared->text_store[0], 89, 44, AlignCenter, AlignTop); - rpc_system_app_confirm(infrared->rpc_ctx, RpcAppEventLoadFile, result); - } else if(event.event == InfraredCustomEventTypeRpcButtonPress) { + rpc_system_app_confirm(infrared->rpc_ctx, result); + } else if( + event.event == InfraredCustomEventTypeRpcButtonPressName || + event.event == InfraredCustomEventTypeRpcButtonPressIndex) { bool result = false; - const char* arg = rpc_system_app_get_data(infrared->rpc_ctx); - if(arg && (state == InfraredRpcStateLoaded)) { - size_t button_index = 0; - if(infrared_remote_find_button_by_name(infrared->remote, arg, &button_index)) { - infrared_tx_start_button_index(infrared, button_index); - result = true; + if(state == InfraredRpcStateLoaded) { + if(event.event == InfraredCustomEventTypeRpcButtonPressName) { + const char* button_name = furi_string_get_cstr(infrared->button_name); + size_t index; + const bool index_found = + infrared_remote_get_signal_index(infrared->remote, button_name, &index); + infrared->app_state.current_button_index = + index_found ? (signed)index : InfraredButtonIndexNone; + FURI_LOG_D(TAG, "Sending signal with name \"%s\"", button_name); + } else { + FURI_LOG_D( + TAG, + "Sending signal with index \"%ld\"", + infrared->app_state.current_button_index); + } + if(infrared->app_state.current_button_index != InfraredButtonIndexNone) { + infrared_tx_start_button_index( + infrared, infrared->app_state.current_button_index); scene_manager_set_scene_state( infrared->scene_manager, InfraredSceneRpc, InfraredRpcStateSending); + result = true; } } - rpc_system_app_confirm(infrared->rpc_ctx, RpcAppEventButtonRelease, result); + rpc_system_app_confirm(infrared->rpc_ctx, result); } else if(event.event == InfraredCustomEventTypeRpcButtonRelease) { bool result = false; if(state == InfraredRpcStateSending) { @@ -77,11 +93,11 @@ bool infrared_scene_rpc_on_event(void* context, SceneManagerEvent event) { scene_manager_set_scene_state( infrared->scene_manager, InfraredSceneRpc, InfraredRpcStateLoaded); } - rpc_system_app_confirm(infrared->rpc_ctx, RpcAppEventButtonRelease, result); + rpc_system_app_confirm(infrared->rpc_ctx, result); } else if(event.event == InfraredCustomEventTypeRpcExit) { scene_manager_stop(infrared->scene_manager); view_dispatcher_stop(infrared->view_dispatcher); - rpc_system_app_confirm(infrared->rpc_ctx, RpcAppEventAppExit, true); + rpc_system_app_confirm(infrared->rpc_ctx, true); } else if(event.event == InfraredCustomEventTypeRpcSessionClose) { scene_manager_stop(infrared->scene_manager); view_dispatcher_stop(infrared->view_dispatcher); @@ -91,7 +107,7 @@ bool infrared_scene_rpc_on_event(void* context, SceneManagerEvent event) { } void infrared_scene_rpc_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; if(scene_manager_get_scene_state(infrared->scene_manager, InfraredSceneRpc) == InfraredRpcStateSending) { infrared_tx_stop(infrared); diff --git a/applications/main/infrared/scenes/infrared_scene_start.c b/applications/main/infrared/scenes/infrared_scene_start.c index a89974ba2..c27be304e 100644 --- a/applications/main/infrared/scenes/infrared_scene_start.c +++ b/applications/main/infrared/scenes/infrared_scene_start.c @@ -1,4 +1,4 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" enum SubmenuIndex { SubmenuIndexUniversalRemotes, @@ -10,12 +10,12 @@ enum SubmenuIndex { }; static void infrared_scene_start_submenu_callback(void* context, uint32_t index) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event(infrared->view_dispatcher, index); } void infrared_scene_start_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Submenu* submenu = infrared->submenu; SceneManager* scene_manager = infrared->scene_manager; @@ -68,7 +68,7 @@ void infrared_scene_start_on_enter(void* context) { } bool infrared_scene_start_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; bool consumed = false; @@ -107,6 +107,6 @@ bool infrared_scene_start_on_event(void* context, SceneManagerEvent event) { } void infrared_scene_start_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; submenu_reset(infrared->submenu); } diff --git a/applications/main/infrared/scenes/infrared_scene_universal.c b/applications/main/infrared/scenes/infrared_scene_universal.c index b6c1ac983..a288716c7 100644 --- a/applications/main/infrared/scenes/infrared_scene_universal.c +++ b/applications/main/infrared/scenes/infrared_scene_universal.c @@ -1,4 +1,4 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" typedef enum { SubmenuIndexUniversalTV, @@ -9,12 +9,12 @@ typedef enum { } SubmenuIndex; static void infrared_scene_universal_submenu_callback(void* context, uint32_t index) { - Infrared* infrared = context; + InfraredApp* infrared = context; view_dispatcher_send_custom_event(infrared->view_dispatcher, index); } void infrared_scene_universal_on_enter(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; Submenu* submenu = infrared->submenu; submenu_add_item( @@ -59,7 +59,7 @@ void infrared_scene_universal_on_enter(void* context) { } bool infrared_scene_universal_on_event(void* context, SceneManagerEvent event) { - Infrared* infrared = context; + InfraredApp* infrared = context; SceneManager* scene_manager = infrared->scene_manager; bool consumed = false; @@ -87,6 +87,6 @@ bool infrared_scene_universal_on_event(void* context, SceneManagerEvent event) { } void infrared_scene_universal_on_exit(void* context) { - Infrared* infrared = context; + InfraredApp* infrared = context; submenu_reset(infrared->submenu); } diff --git a/applications/main/infrared/scenes/infrared_scene_universal_ac.c b/applications/main/infrared/scenes/infrared_scene_universal_ac.c index 5f762d122..764a95189 100644 --- a/applications/main/infrared/scenes/infrared_scene_universal_ac.c +++ b/applications/main/infrared/scenes/infrared_scene_universal_ac.c @@ -1,11 +1,11 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include "common/infrared_scene_universal_common.h" void infrared_scene_universal_ac_on_enter(void* context) { infrared_scene_universal_common_on_enter(context); - Infrared* infrared = context; + InfraredApp* infrared = context; ButtonPanel* button_panel = infrared->button_panel; InfraredBruteForce* brute_force = infrared->brute_force; diff --git a/applications/main/infrared/scenes/infrared_scene_universal_audio.c b/applications/main/infrared/scenes/infrared_scene_universal_audio.c index 3938b6080..241a22bcb 100644 --- a/applications/main/infrared/scenes/infrared_scene_universal_audio.c +++ b/applications/main/infrared/scenes/infrared_scene_universal_audio.c @@ -1,11 +1,11 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include "common/infrared_scene_universal_common.h" void infrared_scene_universal_audio_on_enter(void* context) { infrared_scene_universal_common_on_enter(context); - Infrared* infrared = context; + InfraredApp* infrared = context; ButtonPanel* button_panel = infrared->button_panel; InfraredBruteForce* brute_force = infrared->brute_force; diff --git a/applications/main/infrared/scenes/infrared_scene_universal_fan.c b/applications/main/infrared/scenes/infrared_scene_universal_fan.c index 1622c5458..9074b5508 100644 --- a/applications/main/infrared/scenes/infrared_scene_universal_fan.c +++ b/applications/main/infrared/scenes/infrared_scene_universal_fan.c @@ -1,11 +1,11 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include "common/infrared_scene_universal_common.h" void infrared_scene_universal_fan_on_enter(void* context) { infrared_scene_universal_common_on_enter(context); - Infrared* infrared = context; + InfraredApp* infrared = context; ButtonPanel* button_panel = infrared->button_panel; InfraredBruteForce* brute_force = infrared->brute_force; diff --git a/applications/main/infrared/scenes/infrared_scene_universal_projector.c b/applications/main/infrared/scenes/infrared_scene_universal_projector.c index 9db51b70e..f874d62e2 100644 --- a/applications/main/infrared/scenes/infrared_scene_universal_projector.c +++ b/applications/main/infrared/scenes/infrared_scene_universal_projector.c @@ -1,11 +1,11 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include "common/infrared_scene_universal_common.h" void infrared_scene_universal_projector_on_enter(void* context) { infrared_scene_universal_common_on_enter(context); - Infrared* infrared = context; + InfraredApp* infrared = context; ButtonPanel* button_panel = infrared->button_panel; InfraredBruteForce* brute_force = infrared->brute_force; diff --git a/applications/main/infrared/scenes/infrared_scene_universal_tv.c b/applications/main/infrared/scenes/infrared_scene_universal_tv.c index f2958d887..6031205f5 100644 --- a/applications/main/infrared/scenes/infrared_scene_universal_tv.c +++ b/applications/main/infrared/scenes/infrared_scene_universal_tv.c @@ -1,11 +1,11 @@ -#include "../infrared_i.h" +#include "../infrared_app_i.h" #include "common/infrared_scene_universal_common.h" void infrared_scene_universal_tv_on_enter(void* context) { infrared_scene_universal_common_on_enter(context); - Infrared* infrared = context; + InfraredApp* infrared = context; ButtonPanel* button_panel = infrared->button_panel; InfraredBruteForce* brute_force = infrared->brute_force; diff --git a/applications/main/infrared/views/infrared_move_view.c b/applications/main/infrared/views/infrared_move_view.c index d838a5f82..374a65a44 100644 --- a/applications/main/infrared/views/infrared_move_view.c +++ b/applications/main/infrared/views/infrared_move_view.c @@ -1,10 +1,11 @@ #include "infrared_move_view.h" +#include + #include #include -#include -#include +#include #define LIST_ITEMS 4U #define LIST_LINE_H 13U @@ -13,42 +14,41 @@ struct InfraredMoveView { View* view; - InfraredMoveCallback move_cb; - void* cb_context; + InfraredMoveCallback callback; + void* callback_context; }; -typedef struct { - const char** btn_names; - uint32_t btn_number; - int32_t list_offset; - int32_t item_idx; - bool is_moving; +ARRAY_DEF(InfraredMoveViewItemArray, const char*, M_CSTR_DUP_OPLIST); //-V575 - InfraredMoveGetItemCallback get_item_cb; +typedef struct { + InfraredMoveViewItemArray_t labels; + int32_t list_offset; + int32_t current_idx; + int32_t start_idx; + bool is_moving; } InfraredMoveViewModel; static void infrared_move_view_draw_callback(Canvas* canvas, void* _model) { InfraredMoveViewModel* model = _model; - UNUSED(model); - canvas_set_color(canvas, ColorBlack); canvas_set_font(canvas, FontPrimary); elements_multiline_text_aligned( canvas, canvas_width(canvas) / 2, 0, AlignCenter, AlignTop, "Select a button to move"); - bool show_scrollbar = model->btn_number > LIST_ITEMS; + const size_t btn_number = InfraredMoveViewItemArray_size(model->labels); + const bool show_scrollbar = btn_number > LIST_ITEMS; canvas_set_font(canvas, FontSecondary); - for(uint32_t i = 0; i < MIN(model->btn_number, LIST_ITEMS); i++) { - int32_t idx = CLAMP((uint32_t)(i + model->list_offset), model->btn_number, 0u); - uint8_t x_offset = (model->is_moving && model->item_idx == idx) ? MOVE_X_OFFSET : 0; + for(uint32_t i = 0; i < MIN(btn_number, LIST_ITEMS); i++) { + int32_t idx = CLAMP((uint32_t)(i + model->list_offset), btn_number, 0U); + uint8_t x_offset = (model->is_moving && model->current_idx == idx) ? MOVE_X_OFFSET : 0; uint8_t y_offset = HEADER_H + i * LIST_LINE_H; uint8_t box_end_x = canvas_width(canvas) - (show_scrollbar ? 6 : 1); canvas_set_color(canvas, ColorBlack); - if(model->item_idx == idx) { + if(model->current_idx == idx) { canvas_draw_box(canvas, x_offset, y_offset, box_end_x - x_offset, LIST_LINE_H); canvas_set_color(canvas, ColorWhite); @@ -60,7 +60,12 @@ static void infrared_move_view_draw_callback(Canvas* canvas, void* _model) { canvas_draw_dot(canvas, box_end_x - 1, y_offset + LIST_LINE_H - 1); } canvas_draw_str_aligned( - canvas, x_offset + 3, y_offset + 3, AlignLeft, AlignTop, model->btn_names[idx]); + canvas, + x_offset + 3, + y_offset + 3, + AlignLeft, + AlignTop, + *InfraredMoveViewItemArray_cget(model->labels, idx)); } if(show_scrollbar) { @@ -69,22 +74,22 @@ static void infrared_move_view_draw_callback(Canvas* canvas, void* _model) { canvas_width(canvas), HEADER_H, canvas_height(canvas) - HEADER_H, - model->item_idx, - model->btn_number); + model->current_idx, + btn_number); } } static void update_list_offset(InfraredMoveViewModel* model) { - int32_t bounds = model->btn_number > (LIST_ITEMS - 1) ? 2 : model->btn_number; + const size_t btn_number = InfraredMoveViewItemArray_size(model->labels); + const int32_t bounds = btn_number > (LIST_ITEMS - 1) ? 2 : btn_number; - if((model->btn_number > (LIST_ITEMS - 1)) && - (model->item_idx >= ((int32_t)model->btn_number - 1))) { - model->list_offset = model->item_idx - (LIST_ITEMS - 1); - } else if(model->list_offset < model->item_idx - bounds) { - model->list_offset = CLAMP( - model->item_idx - (int32_t)(LIST_ITEMS - 2), (int32_t)model->btn_number - bounds, 0); - } else if(model->list_offset > model->item_idx - bounds) { - model->list_offset = CLAMP(model->item_idx - 1, (int32_t)model->btn_number - bounds, 0); + if((btn_number > (LIST_ITEMS - 1)) && (model->current_idx >= ((int32_t)btn_number - 1))) { + model->list_offset = model->current_idx - (LIST_ITEMS - 1); + } else if(model->list_offset < model->current_idx - bounds) { + model->list_offset = + CLAMP(model->current_idx - (int32_t)(LIST_ITEMS - 2), (int32_t)btn_number - bounds, 0); + } else if(model->list_offset > model->current_idx - bounds) { + model->list_offset = CLAMP(model->current_idx - 1, (int32_t)btn_number - bounds, 0); } } @@ -95,117 +100,130 @@ static bool infrared_move_view_input_callback(InputEvent* event, void* context) if(((event->type == InputTypeShort || event->type == InputTypeRepeat)) && ((event->key == InputKeyUp) || (event->key == InputKeyDown))) { - bool is_moving = false; - uint32_t index_old = 0; - uint32_t index_new = 0; with_view_model( move_view->view, InfraredMoveViewModel * model, { - is_moving = model->is_moving; - index_old = model->item_idx; + const size_t btn_number = InfraredMoveViewItemArray_size(model->labels); + const int32_t item_idx_prev = model->current_idx; + if(event->key == InputKeyUp) { - if(model->item_idx <= 0) { - model->item_idx = model->btn_number; + if(model->current_idx <= 0) { + model->current_idx = btn_number; } - model->item_idx--; + model->current_idx--; + } else if(event->key == InputKeyDown) { - model->item_idx++; - if(model->item_idx >= (int32_t)(model->btn_number)) { - model->item_idx = 0; + model->current_idx++; + if(model->current_idx >= (int32_t)(btn_number)) { + model->current_idx = 0; } } - index_new = model->item_idx; + + if(model->is_moving) { + InfraredMoveViewItemArray_swap_at( + model->labels, item_idx_prev, model->current_idx); + } + update_list_offset(model); }, - !is_moving); - if((is_moving) && (move_view->move_cb)) { - move_view->move_cb(index_old, index_new, move_view->cb_context); - infrared_move_view_list_update(move_view); - } - consumed = true; - } + true); - if((event->key == InputKeyOk) && (event->type == InputTypeShort)) { + consumed = true; + + } else if((event->key == InputKeyOk) && (event->type == InputTypeShort)) { with_view_model( move_view->view, InfraredMoveViewModel * model, - { model->is_moving = !(model->is_moving); }, + { + if(!model->is_moving) { + model->start_idx = model->current_idx; + } else if(move_view->callback) { + move_view->callback( + model->start_idx, model->current_idx, move_view->callback_context); + } + model->is_moving = !(model->is_moving); + }, true); + consumed = true; + + } else if(event->key == InputKeyBack) { + with_view_model( + move_view->view, + InfraredMoveViewModel * model, + { + if(model->is_moving && move_view->callback) { + move_view->callback( + model->start_idx, model->current_idx, move_view->callback_context); + } + model->is_moving = false; + }, + false); + + // Not consuming, Back event is passed thru } + return consumed; } -static void infrared_move_view_on_exit(void* context) { - furi_assert(context); - InfraredMoveView* move_view = context; - - with_view_model( - move_view->view, - InfraredMoveViewModel * model, - { - if(model->btn_names) { - free(model->btn_names); - model->btn_names = NULL; - } - model->btn_number = 0; - model->get_item_cb = NULL; - }, - false); - move_view->cb_context = NULL; -} - -void infrared_move_view_set_callback(InfraredMoveView* move_view, InfraredMoveCallback callback) { - furi_assert(move_view); - move_view->move_cb = callback; -} - -void infrared_move_view_list_init( +void infrared_move_view_set_callback( InfraredMoveView* move_view, - uint32_t item_count, - InfraredMoveGetItemCallback load_cb, + InfraredMoveCallback callback, void* context) { furi_assert(move_view); - move_view->cb_context = context; - with_view_model( - move_view->view, - InfraredMoveViewModel * model, - { - furi_assert(model->btn_names == NULL); - model->btn_names = malloc(sizeof(char*) * item_count); - model->btn_number = item_count; - model->get_item_cb = load_cb; - }, - false); + move_view->callback = callback; + move_view->callback_context = context; } -void infrared_move_view_list_update(InfraredMoveView* move_view) { - furi_assert(move_view); +void infrared_move_view_add_item(InfraredMoveView* move_view, const char* label) { + with_view_model( + move_view->view, + InfraredMoveViewModel * model, + { InfraredMoveViewItemArray_push_back(model->labels, label); }, + true); +} + +void infrared_move_view_reset(InfraredMoveView* move_view) { with_view_model( move_view->view, InfraredMoveViewModel * model, { - for(uint32_t i = 0; i < model->btn_number; i++) { - if(!model->get_item_cb) break; - model->btn_names[i] = model->get_item_cb(i, move_view->cb_context); - } + InfraredMoveViewItemArray_reset(model->labels); + model->list_offset = 0; + model->start_idx = 0; + model->current_idx = 0; + model->is_moving = false; }, - true); + false); + move_view->callback_context = NULL; } InfraredMoveView* infrared_move_view_alloc(void) { InfraredMoveView* move_view = malloc(sizeof(InfraredMoveView)); + move_view->view = view_alloc(); view_allocate_model(move_view->view, ViewModelTypeLocking, sizeof(InfraredMoveViewModel)); view_set_draw_callback(move_view->view, infrared_move_view_draw_callback); view_set_input_callback(move_view->view, infrared_move_view_input_callback); - view_set_exit_callback(move_view->view, infrared_move_view_on_exit); view_set_context(move_view->view, move_view); + + with_view_model( + move_view->view, + InfraredMoveViewModel * model, + { InfraredMoveViewItemArray_init(model->labels); }, + true); + return move_view; } void infrared_move_view_free(InfraredMoveView* move_view) { + with_view_model( + move_view->view, + InfraredMoveViewModel * model, + { InfraredMoveViewItemArray_clear(model->labels); }, + true); + view_free(move_view->view); free(move_view); } diff --git a/applications/main/infrared/views/infrared_move_view.h b/applications/main/infrared/views/infrared_move_view.h index b9b0cd864..0ab15ce0d 100644 --- a/applications/main/infrared/views/infrared_move_view.h +++ b/applications/main/infrared/views/infrared_move_view.h @@ -6,20 +6,17 @@ typedef struct InfraredMoveView InfraredMoveView; typedef void (*InfraredMoveCallback)(uint32_t index_old, uint32_t index_new, void* context); -typedef const char* (*InfraredMoveGetItemCallback)(uint32_t index, void* context); - InfraredMoveView* infrared_move_view_alloc(void); void infrared_move_view_free(InfraredMoveView* debug_view); View* infrared_move_view_get_view(InfraredMoveView* debug_view); -void infrared_move_view_set_callback(InfraredMoveView* move_view, InfraredMoveCallback callback); - -void infrared_move_view_list_init( +void infrared_move_view_set_callback( InfraredMoveView* move_view, - uint32_t item_count, - InfraredMoveGetItemCallback load_cb, + InfraredMoveCallback callback, void* context); -void infrared_move_view_list_update(InfraredMoveView* move_view); \ No newline at end of file +void infrared_move_view_add_item(InfraredMoveView* move_view, const char* label); + +void infrared_move_view_reset(InfraredMoveView* move_view); diff --git a/applications/main/lfrfid/application.fam b/applications/main/lfrfid/application.fam index cad07fbf7..c067d786f 100644 --- a/applications/main/lfrfid/application.fam +++ b/applications/main/lfrfid/application.fam @@ -17,5 +17,6 @@ App( targets=["f7"], apptype=FlipperAppType.STARTUP, entry_point="lfrfid_on_system_start", + sources=["lfrfid_cli.c"], order=50, ) diff --git a/applications/main/lfrfid/lfrfid.c b/applications/main/lfrfid/lfrfid.c index d4e3436d6..8eb78a9c7 100644 --- a/applications/main/lfrfid/lfrfid.c +++ b/applications/main/lfrfid/lfrfid.c @@ -13,21 +13,23 @@ static bool lfrfid_debug_back_event_callback(void* context) { return scene_manager_handle_back_event(app->scene_manager); } -static void rpc_command_callback(RpcAppSystemEvent rpc_event, void* context) { +static void rpc_command_callback(const RpcAppSystemEvent* event, void* context) { furi_assert(context); LfRfid* app = (LfRfid*)context; - if(rpc_event == RpcAppEventSessionClose) { + if(event->type == RpcAppEventTypeSessionClose) { view_dispatcher_send_custom_event(app->view_dispatcher, LfRfidEventRpcSessionClose); // Detach RPC rpc_system_app_set_callback(app->rpc_ctx, NULL, NULL); app->rpc_ctx = NULL; - } else if(rpc_event == RpcAppEventAppExit) { + } else if(event->type == RpcAppEventTypeAppExit) { view_dispatcher_send_custom_event(app->view_dispatcher, LfRfidEventExit); - } else if(rpc_event == RpcAppEventLoadFile) { + } else if(event->type == RpcAppEventTypeLoadFile) { + furi_assert(event->data.type == RpcAppSystemEventDataTypeString); + furi_string_set(app->file_path, event->data.string); view_dispatcher_send_custom_event(app->view_dispatcher, LfRfidEventRpcLoadFile); } else { - rpc_system_app_confirm(app->rpc_ctx, rpc_event, false); + rpc_system_app_confirm(app->rpc_ctx, false); } } diff --git a/applications/main/lfrfid/scenes/lfrfid_scene_rpc.c b/applications/main/lfrfid/scenes/lfrfid_scene_rpc.c index 156dd97af..906218d74 100644 --- a/applications/main/lfrfid/scenes/lfrfid_scene_rpc.c +++ b/applications/main/lfrfid/scenes/lfrfid_scene_rpc.c @@ -24,17 +24,15 @@ bool lfrfid_scene_rpc_on_event(void* context, SceneManagerEvent event) { if(event.type == SceneManagerEventTypeCustom) { consumed = true; if(event.event == LfRfidEventExit) { - rpc_system_app_confirm(app->rpc_ctx, RpcAppEventAppExit, true); + rpc_system_app_confirm(app->rpc_ctx, true); scene_manager_stop(app->scene_manager); view_dispatcher_stop(app->view_dispatcher); } else if(event.event == LfRfidEventRpcSessionClose) { scene_manager_stop(app->scene_manager); view_dispatcher_stop(app->view_dispatcher); } else if(event.event == LfRfidEventRpcLoadFile) { - const char* arg = rpc_system_app_get_data(app->rpc_ctx); bool result = false; - if(arg && (app->rpc_state == LfRfidRpcStateIdle)) { - furi_string_set(app->file_path, arg); + if(app->rpc_state == LfRfidRpcStateIdle) { if(lfrfid_load_key_data(app, app->file_path, false)) { lfrfid_worker_start_thread(app->lfworker); lfrfid_worker_emulate_start(app->lfworker, (LFRFIDProtocol)app->protocol_id); @@ -48,7 +46,7 @@ bool lfrfid_scene_rpc_on_event(void* context, SceneManagerEvent event) { result = true; } } - rpc_system_app_confirm(app->rpc_ctx, RpcAppEventLoadFile, result); + rpc_system_app_confirm(app->rpc_ctx, result); } } return consumed; diff --git a/applications/main/nfc/application.fam b/applications/main/nfc/application.fam index bc34d4e65..33a2011a7 100644 --- a/applications/main/nfc/application.fam +++ b/applications/main/nfc/application.fam @@ -7,15 +7,78 @@ App( icon="A_NFC_14", stack_size=5 * 1024, order=30, + resources="resources", + sources=[ + "*.c", + "!plugins", + "!nfc_cli.c", + ], fap_libs=["assets"], fap_icon="icon.png", fap_category="NFC", ) +# Parser plugins + +App( + appid="all_in_one_parser", + apptype=FlipperAppType.PLUGIN, + entry_point="all_in_one_plugin_ep", + targets=["f7"], + requires=["nfc"], + sources=["plugins/supported_cards/all_in_one.c"], +) + +App( + appid="opal_parser", + apptype=FlipperAppType.PLUGIN, + entry_point="opal_plugin_ep", + targets=["f7"], + requires=["nfc"], + sources=["plugins/supported_cards/opal.c"], +) + +App( + appid="myki_parser", + apptype=FlipperAppType.PLUGIN, + entry_point="myki_plugin_ep", + targets=["f7"], + requires=["nfc"], + sources=["plugins/supported_cards/myki.c"], +) + +App( + appid="troika_parser", + apptype=FlipperAppType.PLUGIN, + entry_point="troika_plugin_ep", + targets=["f7"], + requires=["nfc"], + sources=["plugins/supported_cards/troika.c"], +) + +App( + appid="plantain_parser", + apptype=FlipperAppType.PLUGIN, + entry_point="plantain_plugin_ep", + targets=["f7"], + requires=["nfc"], + sources=["plugins/supported_cards/plantain.c"], +) + +App( + appid="two_cities_parser", + apptype=FlipperAppType.PLUGIN, + entry_point="two_cities_plugin_ep", + targets=["f7"], + requires=["nfc"], + sources=["plugins/supported_cards/two_cities.c"], +) + App( appid="nfc_start", targets=["f7"], apptype=FlipperAppType.STARTUP, entry_point="nfc_on_system_start", + sources=["nfc_cli.c"], order=30, ) diff --git a/applications/main/nfc/helpers/mf_classic_key_cache.c b/applications/main/nfc/helpers/mf_classic_key_cache.c new file mode 100644 index 000000000..5127e6452 --- /dev/null +++ b/applications/main/nfc/helpers/mf_classic_key_cache.c @@ -0,0 +1,212 @@ +#include "mf_classic_key_cache.h" + +#include +#include + +#define NFC_APP_KEYS_EXTENSION ".keys" +#define NFC_APP_KEY_CACHE_FOLDER "/ext/nfc/.cache" + +static const char* mf_classic_key_cache_file_header = "Flipper NFC keys"; +static const uint32_t mf_classic_key_cache_file_version = 1; + +struct MfClassicKeyCache { + MfClassicDeviceKeys keys; + MfClassicKeyType current_key_type; + uint8_t current_sector; +}; + +static void nfc_get_key_cache_file_path(const uint8_t* uid, size_t uid_len, FuriString* path) { + furi_string_printf(path, "%s/", NFC_APP_KEY_CACHE_FOLDER); + for(size_t i = 0; i < uid_len; i++) { + furi_string_cat_printf(path, "%02X", uid[i]); + } + furi_string_cat_printf(path, "%s", NFC_APP_KEYS_EXTENSION); +} + +MfClassicKeyCache* mf_classic_key_cache_alloc() { + MfClassicKeyCache* instance = malloc(sizeof(MfClassicKeyCache)); + + return instance; +} + +void mf_classic_key_cache_free(MfClassicKeyCache* instance) { + furi_assert(instance); + + free(instance); +} + +bool mf_classic_key_cache_save(MfClassicKeyCache* instance, const MfClassicData* data) { + UNUSED(instance); + furi_assert(data); + + size_t uid_len = 0; + const uint8_t* uid = mf_classic_get_uid(data, &uid_len); + FuriString* file_path = furi_string_alloc(); + nfc_get_key_cache_file_path(uid, uid_len, file_path); + + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_buffered_file_alloc(storage); + + FuriString* temp_str = furi_string_alloc(); + bool save_success = false; + do { + if(!storage_simply_mkdir(storage, NFC_APP_KEY_CACHE_FOLDER)) break; + if(!storage_simply_remove(storage, furi_string_get_cstr(file_path))) break; + if(!flipper_format_buffered_file_open_always(ff, furi_string_get_cstr(file_path))) break; + + if(!flipper_format_write_header_cstr( + ff, mf_classic_key_cache_file_header, mf_classic_key_cache_file_version)) + break; + if(!flipper_format_write_string_cstr( + ff, "Mifare Classic type", mf_classic_get_device_name(data, NfcDeviceNameTypeShort))) + break; + if(!flipper_format_write_hex_uint64(ff, "Key A map", &data->key_a_mask, 1)) break; + if(!flipper_format_write_hex_uint64(ff, "Key B map", &data->key_b_mask, 1)) break; + + uint8_t sector_num = mf_classic_get_total_sectors_num(data->type); + bool key_save_success = true; + for(size_t i = 0; (i < sector_num) && (key_save_success); i++) { + MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, i); + if(FURI_BIT(data->key_a_mask, i)) { + furi_string_printf(temp_str, "Key A sector %d", i); + key_save_success = flipper_format_write_hex( + ff, furi_string_get_cstr(temp_str), sec_tr->key_a.data, sizeof(MfClassicKey)); + } + if(!key_save_success) break; + if(FURI_BIT(data->key_b_mask, i)) { + furi_string_printf(temp_str, "Key B sector %d", i); + key_save_success = flipper_format_write_hex( + ff, furi_string_get_cstr(temp_str), sec_tr->key_b.data, sizeof(MfClassicKey)); + } + } + save_success = key_save_success; + } while(false); + + flipper_format_free(ff); + furi_string_free(temp_str); + furi_string_free(file_path); + furi_record_close(RECORD_STORAGE); + + return save_success; +} + +bool mf_classic_key_cache_load(MfClassicKeyCache* instance, const uint8_t* uid, size_t uid_len) { + furi_assert(instance); + furi_assert(uid); + + mf_classic_key_cache_reset(instance); + + FuriString* file_path = furi_string_alloc(); + nfc_get_key_cache_file_path(uid, uid_len, file_path); + + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_buffered_file_alloc(storage); + + FuriString* temp_str = furi_string_alloc(); + bool load_success = false; + do { + if(!flipper_format_buffered_file_open_existing(ff, furi_string_get_cstr(file_path))) break; + + uint32_t version = 0; + if(!flipper_format_read_header(ff, temp_str, &version)) break; + if(furi_string_cmp_str(temp_str, mf_classic_key_cache_file_header)) break; + if(version != mf_classic_key_cache_file_version) break; + + if(!flipper_format_read_hex_uint64(ff, "Key A map", &instance->keys.key_a_mask, 1)) break; + if(!flipper_format_read_hex_uint64(ff, "Key B map", &instance->keys.key_b_mask, 1)) break; + + bool key_read_success = true; + for(size_t i = 0; (i < MF_CLASSIC_TOTAL_SECTORS_MAX) && (key_read_success); i++) { + if(FURI_BIT(instance->keys.key_a_mask, i)) { + furi_string_printf(temp_str, "Key A sector %d", i); + key_read_success = flipper_format_read_hex( + ff, + furi_string_get_cstr(temp_str), + instance->keys.key_a[i].data, + sizeof(MfClassicKey)); + } + if(!key_read_success) break; + if(FURI_BIT(instance->keys.key_b_mask, i)) { + furi_string_printf(temp_str, "Key B sector %d", i); + key_read_success = flipper_format_read_hex( + ff, + furi_string_get_cstr(temp_str), + instance->keys.key_b[i].data, + sizeof(MfClassicKey)); + } + } + load_success = key_read_success; + } while(false); + + flipper_format_buffered_file_close(ff); + flipper_format_free(ff); + furi_string_free(temp_str); + furi_string_free(file_path); + furi_record_close(RECORD_STORAGE); + + return load_success; +} + +void mf_classic_key_cache_load_from_data(MfClassicKeyCache* instance, const MfClassicData* data) { + furi_assert(instance); + furi_assert(data); + + mf_classic_key_cache_reset(instance); + instance->keys.key_a_mask = data->key_a_mask; + instance->keys.key_b_mask = data->key_b_mask; + for(size_t i = 0; i < MF_CLASSIC_TOTAL_SECTORS_MAX; i++) { + MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, i); + + if(FURI_BIT(data->key_a_mask, i)) { + instance->keys.key_a[i] = sec_tr->key_a; + } + if(FURI_BIT(data->key_b_mask, i)) { + instance->keys.key_b[i] = sec_tr->key_b; + } + } +} + +bool mf_classic_key_cahce_get_next_key( + MfClassicKeyCache* instance, + uint8_t* sector_num, + MfClassicKey* key, + MfClassicKeyType* key_type) { + furi_assert(instance); + furi_assert(sector_num); + furi_assert(key); + furi_assert(key_type); + + bool next_key_found = false; + for(uint8_t i = instance->current_sector; i < MF_CLASSIC_TOTAL_SECTORS_MAX; i++) { + if(FURI_BIT(instance->keys.key_a_mask, i)) { + FURI_BIT_CLEAR(instance->keys.key_a_mask, i); + *key = instance->keys.key_a[i]; + *key_type = MfClassicKeyTypeA; + *sector_num = i; + + next_key_found = true; + break; + } + if(FURI_BIT(instance->keys.key_b_mask, i)) { + FURI_BIT_CLEAR(instance->keys.key_b_mask, i); + *key = instance->keys.key_b[i]; + *key_type = MfClassicKeyTypeB; + *sector_num = i; + + next_key_found = true; + instance->current_sector = i; + break; + } + } + + return next_key_found; +} + +void mf_classic_key_cache_reset(MfClassicKeyCache* instance) { + furi_assert(instance); + + instance->current_key_type = MfClassicKeyTypeA; + instance->current_sector = 0; + instance->keys.key_a_mask = 0; + instance->keys.key_b_mask = 0; +} diff --git a/applications/main/nfc/helpers/mf_classic_key_cache.h b/applications/main/nfc/helpers/mf_classic_key_cache.h new file mode 100644 index 000000000..407c6e28b --- /dev/null +++ b/applications/main/nfc/helpers/mf_classic_key_cache.h @@ -0,0 +1,31 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct MfClassicKeyCache MfClassicKeyCache; + +MfClassicKeyCache* mf_classic_key_cache_alloc(); + +void mf_classic_key_cache_free(MfClassicKeyCache* instance); + +bool mf_classic_key_cache_load(MfClassicKeyCache* instance, const uint8_t* uid, size_t uid_len); + +void mf_classic_key_cache_load_from_data(MfClassicKeyCache* instance, const MfClassicData* data); + +bool mf_classic_key_cahce_get_next_key( + MfClassicKeyCache* instance, + uint8_t* sector_num, + MfClassicKey* key, + MfClassicKeyType* key_type); + +bool mf_classic_key_cache_save(MfClassicKeyCache* instance, const MfClassicData* data); + +void mf_classic_key_cache_reset(MfClassicKeyCache* instance); + +#ifdef __cplusplus +} +#endif diff --git a/applications/main/nfc/helpers/mf_ultralight_auth.c b/applications/main/nfc/helpers/mf_ultralight_auth.c new file mode 100644 index 000000000..5e0c67887 --- /dev/null +++ b/applications/main/nfc/helpers/mf_ultralight_auth.c @@ -0,0 +1,58 @@ +#include "mf_ultralight_auth.h" + +#include +#include + +MfUltralightAuth* mf_ultralight_auth_alloc() { + MfUltralightAuth* instance = malloc(sizeof(MfUltralightAuth)); + + return instance; +} + +void mf_ultralight_auth_free(MfUltralightAuth* instance) { + furi_assert(instance); + + free(instance); +} + +void mf_ultralight_auth_reset(MfUltralightAuth* instance) { + furi_assert(instance); + + instance->type = MfUltralightAuthTypeNone; + memset(&instance->password, 0, sizeof(MfUltralightAuthPassword)); + memset(&instance->pack, 0, sizeof(MfUltralightAuthPack)); +} + +bool mf_ultralight_generate_amiibo_pass(MfUltralightAuth* instance, uint8_t* uid, uint16_t uid_len) { + furi_assert(instance); + furi_assert(uid); + + bool generated = false; + if(uid_len == 7) { + instance->password.data[0] = uid[1] ^ uid[3] ^ 0xAA; + instance->password.data[1] = uid[2] ^ uid[4] ^ 0x55; + instance->password.data[2] = uid[3] ^ uid[5] ^ 0xAA; + instance->password.data[3] = uid[4] ^ uid[6] ^ 0x55; + generated = true; + } + + return generated; +} + +bool mf_ultralight_generate_xiaomi_pass(MfUltralightAuth* instance, uint8_t* uid, uint16_t uid_len) { + furi_assert(instance); + furi_assert(uid); + + uint8_t hash[20]; + bool generated = false; + if(uid_len == 7) { + mbedtls_sha1(uid, uid_len, hash); + instance->password.data[0] = (hash[hash[0] % 20]); + instance->password.data[1] = (hash[(hash[0] + 5) % 20]); + instance->password.data[2] = (hash[(hash[0] + 13) % 20]); + instance->password.data[3] = (hash[(hash[0] + 17) % 20]); + generated = true; + } + + return generated; +} diff --git a/applications/main/nfc/helpers/mf_ultralight_auth.h b/applications/main/nfc/helpers/mf_ultralight_auth.h new file mode 100644 index 000000000..2ddfcafe1 --- /dev/null +++ b/applications/main/nfc/helpers/mf_ultralight_auth.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + MfUltralightAuthTypeNone, + MfUltralightAuthTypeReader, + MfUltralightAuthTypeManual, + MfUltralightAuthTypeXiaomi, + MfUltralightAuthTypeAmiibo, +} MfUltralightAuthType; + +typedef struct { + MfUltralightAuthType type; + MfUltralightAuthPassword password; + MfUltralightAuthPack pack; +} MfUltralightAuth; + +MfUltralightAuth* mf_ultralight_auth_alloc(); + +void mf_ultralight_auth_free(MfUltralightAuth* instance); + +void mf_ultralight_auth_reset(MfUltralightAuth* instance); + +bool mf_ultralight_generate_amiibo_pass(MfUltralightAuth* instance, uint8_t* uid, uint16_t uid_len); + +bool mf_ultralight_generate_xiaomi_pass(MfUltralightAuth* instance, uint8_t* uid, uint16_t uid_len); + +#ifdef __cplusplus +} +#endif diff --git a/applications/main/nfc/helpers/mf_user_dict.c b/applications/main/nfc/helpers/mf_user_dict.c new file mode 100644 index 000000000..09f0c1506 --- /dev/null +++ b/applications/main/nfc/helpers/mf_user_dict.c @@ -0,0 +1,83 @@ +#include "mf_user_dict.h" + +#include +#include +#include + +#define NFC_APP_FOLDER ANY_PATH("nfc") +#define NFC_APP_MF_CLASSIC_DICT_USER_PATH (NFC_APP_FOLDER "/assets/mf_classic_dict_user.nfc") + +struct MfUserDict { + size_t keys_num; + MfClassicKey* keys_arr; +}; + +MfUserDict* mf_user_dict_alloc(size_t max_keys_to_load) { + MfUserDict* instance = malloc(sizeof(MfUserDict)); + + NfcDict* dict = nfc_dict_alloc( + NFC_APP_MF_CLASSIC_DICT_USER_PATH, NfcDictModeOpenAlways, sizeof(MfClassicKey)); + furi_assert(dict); + + size_t dict_keys_num = nfc_dict_get_total_keys(dict); + instance->keys_num = MIN(max_keys_to_load, dict_keys_num); + + if(instance->keys_num > 0) { + instance->keys_arr = malloc(instance->keys_num * sizeof(MfClassicKey)); + for(size_t i = 0; i < instance->keys_num; i++) { + bool key_loaded = + nfc_dict_get_next_key(dict, instance->keys_arr[i].data, sizeof(MfClassicKey)); + furi_assert(key_loaded); + } + } + nfc_dict_free(dict); + + return instance; +} + +void mf_user_dict_free(MfUserDict* instance) { + furi_assert(instance); + + if(instance->keys_num > 0) { + free(instance->keys_arr); + } + free(instance); +} + +size_t mf_user_dict_get_keys_cnt(MfUserDict* instance) { + furi_assert(instance); + + return instance->keys_num; +} + +void mf_user_dict_get_key_str(MfUserDict* instance, uint32_t index, FuriString* str) { + furi_assert(instance); + furi_assert(str); + furi_assert(index < instance->keys_num); + furi_assert(instance->keys_arr); + + furi_string_reset(str); + for(size_t i = 0; i < sizeof(MfClassicKey); i++) { + furi_string_cat_printf(str, "%02X", instance->keys_arr[index].data[i]); + } +} + +bool mf_user_dict_delete_key(MfUserDict* instance, uint32_t index) { + furi_assert(instance); + furi_assert(index < instance->keys_num); + furi_assert(instance->keys_arr); + + NfcDict* dict = nfc_dict_alloc( + NFC_APP_MF_CLASSIC_DICT_USER_PATH, NfcDictModeOpenAlways, sizeof(MfClassicKey)); + furi_assert(dict); + + bool key_delete_success = + nfc_dict_delete_key(dict, instance->keys_arr[index].data, sizeof(MfClassicKey)); + nfc_dict_free(dict); + + if(key_delete_success) { + instance->keys_num--; + } + + return key_delete_success; +} diff --git a/applications/main/nfc/helpers/mf_user_dict.h b/applications/main/nfc/helpers/mf_user_dict.h new file mode 100644 index 000000000..d482d2d5f --- /dev/null +++ b/applications/main/nfc/helpers/mf_user_dict.h @@ -0,0 +1,23 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct MfUserDict MfUserDict; + +MfUserDict* mf_user_dict_alloc(size_t max_keys_to_load); + +void mf_user_dict_free(MfUserDict* instance); + +size_t mf_user_dict_get_keys_cnt(MfUserDict* instance); + +void mf_user_dict_get_key_str(MfUserDict* instance, uint32_t index, FuriString* str); + +bool mf_user_dict_delete_key(MfUserDict* instance, uint32_t index); + +#ifdef __cplusplus +} +#endif diff --git a/applications/main/nfc/helpers/mfkey32_logger.c b/applications/main/nfc/helpers/mfkey32_logger.c new file mode 100644 index 000000000..8024179f8 --- /dev/null +++ b/applications/main/nfc/helpers/mfkey32_logger.c @@ -0,0 +1,173 @@ +#include "mfkey32_logger.h" + +#include + +#include +#include +#include + +#define MFKEY32_LOGGER_MAX_NONCES_SAVED (100) + +typedef struct { + bool is_filled; + uint32_t cuid; + uint8_t sector_num; + MfClassicKeyType key_type; + uint32_t nt0; + uint32_t nr0; + uint32_t ar0; + uint32_t nt1; + uint32_t nr1; + uint32_t ar1; +} Mfkey32LoggerParams; + +ARRAY_DEF(Mfkey32LoggerParams, Mfkey32LoggerParams, M_POD_OPLIST); + +struct Mfkey32Logger { + uint32_t cuid; + Mfkey32LoggerParams_t params_arr; + size_t nonces_saves; + size_t params_collected; +}; + +Mfkey32Logger* mfkey32_logger_alloc(uint32_t cuid) { + Mfkey32Logger* instance = malloc(sizeof(Mfkey32Logger)); + instance->cuid = cuid; + Mfkey32LoggerParams_init(instance->params_arr); + + return instance; +} + +void mfkey32_logger_free(Mfkey32Logger* instance) { + furi_assert(instance); + furi_assert(instance->params_arr); + + Mfkey32LoggerParams_clear(instance->params_arr); + free(instance); +} + +static bool mfkey32_logger_add_nonce_to_existing_params( + Mfkey32Logger* instance, + MfClassicAuthContext* auth_context) { + bool nonce_added = false; + do { + if(Mfkey32LoggerParams_size(instance->params_arr) == 0) break; + + Mfkey32LoggerParams_it_t it; + for(Mfkey32LoggerParams_it(it, instance->params_arr); !Mfkey32LoggerParams_end_p(it); + Mfkey32LoggerParams_next(it)) { + Mfkey32LoggerParams* params = Mfkey32LoggerParams_ref(it); + if(params->is_filled) continue; + + uint8_t sector_num = mf_classic_get_sector_by_block(auth_context->block_num); + if(params->sector_num != sector_num) continue; + if(params->key_type != auth_context->key_type) continue; + + params->nt1 = nfc_util_bytes2num(auth_context->nt.data, sizeof(MfClassicNt)); + params->nr1 = nfc_util_bytes2num(auth_context->nr.data, sizeof(MfClassicNr)); + params->ar1 = nfc_util_bytes2num(auth_context->ar.data, sizeof(MfClassicAr)); + params->is_filled = true; + + instance->params_collected++; + nonce_added = true; + break; + } + + } while(false); + + return nonce_added; +} + +void mfkey32_logger_add_nonce(Mfkey32Logger* instance, MfClassicAuthContext* auth_context) { + furi_assert(instance); + furi_assert(auth_context); + + bool nonce_added = mfkey32_logger_add_nonce_to_existing_params(instance, auth_context); + if(!nonce_added && (instance->nonces_saves < MFKEY32_LOGGER_MAX_NONCES_SAVED)) { + uint8_t sector_num = mf_classic_get_sector_by_block(auth_context->block_num); + Mfkey32LoggerParams params = { + .is_filled = false, + .cuid = instance->cuid, + .sector_num = sector_num, + .key_type = auth_context->key_type, + .nt0 = nfc_util_bytes2num(auth_context->nt.data, sizeof(MfClassicNt)), + .nr0 = nfc_util_bytes2num(auth_context->nr.data, sizeof(MfClassicNr)), + .ar0 = nfc_util_bytes2num(auth_context->ar.data, sizeof(MfClassicAr)), + }; + Mfkey32LoggerParams_push_back(instance->params_arr, params); + instance->nonces_saves++; + } +} + +size_t mfkey32_logger_get_params_num(Mfkey32Logger* instance) { + furi_assert(instance); + + return instance->params_collected; +} + +bool mfkey32_logger_save_params(Mfkey32Logger* instance, const char* path) { + furi_assert(instance); + furi_assert(path); + furi_assert(instance->params_collected > 0); + furi_assert(instance->params_arr); + + bool params_saved = false; + Storage* storage = furi_record_open(RECORD_STORAGE); + Stream* stream = buffered_file_stream_alloc(storage); + FuriString* temp_str = furi_string_alloc(); + + do { + if(!buffered_file_stream_open(stream, path, FSAM_WRITE, FSOM_OPEN_APPEND)) break; + + bool params_write_success = true; + Mfkey32LoggerParams_it_t it; + for(Mfkey32LoggerParams_it(it, instance->params_arr); !Mfkey32LoggerParams_end_p(it); + Mfkey32LoggerParams_next(it)) { + Mfkey32LoggerParams* params = Mfkey32LoggerParams_ref(it); + if(!params->is_filled) continue; + furi_string_printf( + temp_str, + "Sec %d key %c cuid %08lx nt0 %08lx nr0 %08lx ar0 %08lx nt1 %08lx nr1 %08lx ar1 %08lx\n", + params->sector_num, + params->key_type == MfClassicKeyTypeA ? 'A' : 'B', + params->cuid, + params->nt0, + params->nr0, + params->ar0, + params->nt1, + params->nr1, + params->ar1); + if(!stream_write_string(stream, temp_str)) { + params_write_success = false; + break; + } + } + if(!params_write_success) break; + + params_saved = true; + } while(false); + + furi_string_free(temp_str); + buffered_file_stream_close(stream); + stream_free(stream); + furi_record_close(RECORD_STORAGE); + + return params_saved; +} + +void mfkey32_logger_get_params_data(Mfkey32Logger* instance, FuriString* str) { + furi_assert(instance); + furi_assert(str); + furi_assert(instance->params_collected > 0); + + furi_string_reset(str); + Mfkey32LoggerParams_it_t it; + for(Mfkey32LoggerParams_it(it, instance->params_arr); !Mfkey32LoggerParams_end_p(it); + Mfkey32LoggerParams_next(it)) { + Mfkey32LoggerParams* params = Mfkey32LoggerParams_ref(it); + if(!params->is_filled) continue; + + char key_char = params->key_type == MfClassicKeyTypeA ? 'A' : 'B'; + furi_string_cat_printf(str, "Sector %d, key %c\n", params->sector_num, key_char); + } +} diff --git a/applications/main/nfc/helpers/mfkey32_logger.h b/applications/main/nfc/helpers/mfkey32_logger.h new file mode 100644 index 000000000..12b42e1fb --- /dev/null +++ b/applications/main/nfc/helpers/mfkey32_logger.h @@ -0,0 +1,25 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Mfkey32Logger Mfkey32Logger; + +Mfkey32Logger* mfkey32_logger_alloc(uint32_t cuid); + +void mfkey32_logger_free(Mfkey32Logger* instance); + +void mfkey32_logger_add_nonce(Mfkey32Logger* instance, MfClassicAuthContext* auth_context); + +size_t mfkey32_logger_get_params_num(Mfkey32Logger* instance); + +bool mfkey32_logger_save_params(Mfkey32Logger* instance, const char* path); + +void mfkey32_logger_get_params_data(Mfkey32Logger* instance, FuriString* str); + +#ifdef __cplusplus +} +#endif diff --git a/applications/main/nfc/helpers/nfc_custom_event.h b/applications/main/nfc/helpers/nfc_custom_event.h index 00feb8484..16fbc4749 100644 --- a/applications/main/nfc/helpers/nfc_custom_event.h +++ b/applications/main/nfc/helpers/nfc_custom_event.h @@ -1,17 +1,33 @@ #pragma once -enum NfcCustomEvent { +typedef enum { // Reserve first 100 events for button types and indexes, starting from 0 NfcCustomEventReserved = 100, + // Mf classic dict attack events + NfcCustomEventDictAttackComplete, + NfcCustomEventDictAttackSkip, + NfcCustomEventDictAttackDataUpdate, + + NfcCustomEventCardDetected, + NfcCustomEventCardLost, + NfcCustomEventViewExit, NfcCustomEventWorkerExit, + NfcCustomEventWorkerUpdate, + NfcCustomEventWrongCard, + NfcCustomEventTimerExpired, NfcCustomEventByteInputDone, NfcCustomEventTextInputDone, NfcCustomEventDictAttackDone, - NfcCustomEventDictAttackSkip, - NfcCustomEventRpcLoad, + + NfcCustomEventRpcLoadFile, + NfcCustomEventRpcExit, NfcCustomEventRpcSessionClose, - NfcCustomEventUpdateLog, - NfcCustomEventSaveShadow, -}; \ No newline at end of file + + NfcCustomEventPollerSuccess, + NfcCustomEventPollerIncomplete, + NfcCustomEventPollerFailure, + + NfcCustomEventListenerUpdate, +} NfcCustomEvent; diff --git a/applications/main/nfc/helpers/nfc_supported_cards.c b/applications/main/nfc/helpers/nfc_supported_cards.c new file mode 100644 index 000000000..a242ba3ae --- /dev/null +++ b/applications/main/nfc/helpers/nfc_supported_cards.c @@ -0,0 +1,147 @@ +#include "nfc_supported_cards.h" +#include "../plugins/supported_cards/nfc_supported_card_plugin.h" + +#include +#include +#include + +#include +#include + +#define TAG "NfcSupportedCards" + +#define NFC_SUPPORTED_CARDS_PLUGINS_PATH APP_DATA_PATH("plugins") +#define NFC_SUPPORTED_CARDS_PLUGIN_SUFFIX "_parser.fal" + +typedef struct { + Storage* storage; + File* directory; + FuriString* file_path; + char file_name[256]; + FlipperApplication* app; +} NfcSupportedCards; + +static NfcSupportedCards* nfc_supported_cards_alloc() { + NfcSupportedCards* instance = malloc(sizeof(NfcSupportedCards)); + + instance->storage = furi_record_open(RECORD_STORAGE); + instance->directory = storage_file_alloc(instance->storage); + instance->file_path = furi_string_alloc(); + + if(!storage_dir_open(instance->directory, NFC_SUPPORTED_CARDS_PLUGINS_PATH)) { + FURI_LOG_D(TAG, "Failed to open directory: %s", NFC_SUPPORTED_CARDS_PLUGINS_PATH); + } + + return instance; +} + +static void nfc_supported_cards_free(NfcSupportedCards* instance) { + if(instance->app) { + flipper_application_free(instance->app); + } + + furi_string_free(instance->file_path); + + storage_dir_close(instance->directory); + storage_file_free(instance->directory); + + furi_record_close(RECORD_STORAGE); + free(instance); +} + +static const NfcSupportedCardsPlugin* + nfc_supported_cards_get_next_plugin(NfcSupportedCards* instance) { + const NfcSupportedCardsPlugin* plugin = NULL; + + do { + if(!storage_file_is_open(instance->directory)) break; + if(!storage_dir_read( + instance->directory, NULL, instance->file_name, sizeof(instance->file_name))) + break; + + furi_string_set(instance->file_path, instance->file_name); + if(!furi_string_end_with_str(instance->file_path, NFC_SUPPORTED_CARDS_PLUGIN_SUFFIX)) + continue; + + path_concat(NFC_SUPPORTED_CARDS_PLUGINS_PATH, instance->file_name, instance->file_path); + + if(instance->app) flipper_application_free(instance->app); + instance->app = flipper_application_alloc(instance->storage, firmware_api_interface); + + if(flipper_application_preload(instance->app, furi_string_get_cstr(instance->file_path)) != + FlipperApplicationPreloadStatusSuccess) + continue; + if(!flipper_application_is_plugin(instance->app)) continue; + + if(flipper_application_map_to_memory(instance->app) != FlipperApplicationLoadStatusSuccess) + continue; + + const FlipperAppPluginDescriptor* descriptor = + flipper_application_plugin_get_descriptor(instance->app); + + if(descriptor == NULL) continue; + + if(strcmp(descriptor->appid, NFC_SUPPORTED_CARD_PLUGIN_APP_ID) != 0) continue; + if(descriptor->ep_api_version != NFC_SUPPORTED_CARD_PLUGIN_API_VERSION) continue; + + plugin = descriptor->entry_point; + } while(plugin == NULL); //-V654 + + return plugin; +} + +bool nfc_supported_cards_read(NfcDevice* device, Nfc* nfc) { + furi_assert(device); + furi_assert(nfc); + + bool card_read = false; + + NfcSupportedCards* supported_cards = nfc_supported_cards_alloc(); + + do { + const NfcSupportedCardsPlugin* plugin = + nfc_supported_cards_get_next_plugin(supported_cards); + if(plugin == NULL) break; //-V547 + + const NfcProtocol protocol = nfc_device_get_protocol(device); //-V779 + if(plugin->protocol != protocol) continue; + + if(plugin->verify) { + if(!plugin->verify(nfc)) continue; + } + + if(plugin->read) { + card_read = plugin->read(nfc, device); + } + + } while(!card_read); + + nfc_supported_cards_free(supported_cards); + return card_read; +} + +bool nfc_supported_cards_parse(const NfcDevice* device, FuriString* parsed_data) { + furi_assert(device); + furi_assert(parsed_data); + + bool parsed = false; + + NfcSupportedCards* supported_cards = nfc_supported_cards_alloc(); + + do { + const NfcSupportedCardsPlugin* plugin = + nfc_supported_cards_get_next_plugin(supported_cards); + if(plugin == NULL) break; //-V547 + + const NfcProtocol protocol = nfc_device_get_protocol(device); //-V779 + if(plugin->protocol != protocol) continue; + + if(plugin->parse) { + parsed = plugin->parse(device, parsed_data); + } + + } while(!parsed); + + nfc_supported_cards_free(supported_cards); + return parsed; +} diff --git a/applications/main/nfc/helpers/nfc_supported_cards.h b/applications/main/nfc/helpers/nfc_supported_cards.h new file mode 100644 index 000000000..0c25a5b11 --- /dev/null +++ b/applications/main/nfc/helpers/nfc_supported_cards.h @@ -0,0 +1,50 @@ +/** + * @file nfc_supported_cards.h + * @brief Supported card plugin loader interface. + * + * @see nfc_supported_card_plugin.h for instructions on adding a new plugin. + */ +#pragma once + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Read the card using a custom procedure. + * + * This function will load all suitable supported card plugins one by one and + * try to execute the custom read procedure specified in each. Upon first success, + * no further attempts will be made and the function will return. + * + * @param[in,out] device pointer to a device instance to hold the read data. + * @param[in,out] nfc pointer to an Nfc instance. + * @returns true if the card was successfully read, false otherwise. + * + * @see NfcSupportedCardPluginRead for detailed description. + */ +bool nfc_supported_cards_read(NfcDevice* device, Nfc* nfc); + +/** + * @brief Parse raw data into human-readable representation. + * + * This function will load all suitable supported card plugins one by one and + * try to parse the data according to each implementation. Upon first success, + * no further attempts will be made and the function will return. + * + * @param[in] device pointer to a device instance holding the data is to be parsed. + * @param[out] parsed_data pointer to the string to contain the formatted result. + * @returns true if the card was successfully parsed, false otherwise. + * + * @see NfcSupportedCardPluginParse for detailed description. + */ +bool nfc_supported_cards_parse(const NfcDevice* device, FuriString* parsed_data); + +#ifdef __cplusplus +} +#endif diff --git a/applications/main/nfc/helpers/protocol_support/felica/felica.c b/applications/main/nfc/helpers/protocol_support/felica/felica.c new file mode 100644 index 000000000..b3e629f4a --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/felica/felica.c @@ -0,0 +1,108 @@ +#include "felica.h" +#include "felica_render.h" + +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" + +static void nfc_scene_info_on_enter_felica(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const FelicaData* data = nfc_device_get_data(device, NfcProtocolFelica); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_felica_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 64, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand nfc_scene_read_poller_callback_felica(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolFelica); + + NfcApp* instance = context; + const FelicaPollerEvent* felica_event = event.event_data; + + if(felica_event->type == FelicaPollerEventTypeReady) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolFelica, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_felica(NfcApp* instance) { + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_felica, instance); +} + +static void nfc_scene_read_success_on_enter_felica(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const FelicaData* data = nfc_device_get_data(device, NfcProtocolFelica); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_felica_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static bool nfc_scene_saved_menu_on_event_felica(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexCommonEdit) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSetUid); + return true; + } + + return false; +} + +const NfcProtocolSupportBase nfc_protocol_support_felica = { + .features = NfcProtocolFeatureNone, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_felica, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_felica, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_felica, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_scene_saved_menu_on_event_felica, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/felica/felica.h b/applications/main/nfc/helpers/protocol_support/felica/felica.h new file mode 100644 index 000000000..e581b6709 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/felica/felica.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_felica; diff --git a/applications/main/nfc/helpers/protocol_support/felica/felica_render.c b/applications/main/nfc/helpers/protocol_support/felica/felica_render.c new file mode 100644 index 000000000..3142b2c6d --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/felica/felica_render.c @@ -0,0 +1,19 @@ +#include "felica_render.h" + +void nfc_render_felica_info( + const FelicaData* data, + NfcProtocolFormatType format_type, + FuriString* str) { + furi_string_cat_printf(str, "IDm:"); + + for(size_t i = 0; i < FELICA_IDM_SIZE; i++) { + furi_string_cat_printf(str, " %02X", data->idm.data[i]); + } + + if(format_type == NfcProtocolFormatTypeFull) { + furi_string_cat_printf(str, "\nPMm:"); + for(size_t i = 0; i < FELICA_PMM_SIZE; ++i) { + furi_string_cat_printf(str, " %02X", data->pmm.data[i]); + } + } +} diff --git a/applications/main/nfc/helpers/protocol_support/felica/felica_render.h b/applications/main/nfc/helpers/protocol_support/felica/felica_render.h new file mode 100644 index 000000000..6d9816fc6 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/felica/felica_render.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_felica_info( + const FelicaData* data, + NfcProtocolFormatType format_type, + FuriString* str); diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a.c b/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a.c new file mode 100644 index 000000000..c0d502d03 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a.c @@ -0,0 +1,145 @@ +#include "iso14443_3a.h" +#include "iso14443_3a_render.h" + +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" + +static void nfc_scene_info_on_enter_iso14443_3a(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso14443_3aData* data = nfc_device_get_data(device, NfcProtocolIso14443_3a); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso14443_3a_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 64, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand + nfc_scene_read_poller_callback_iso14443_3a(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_3a); + + NfcApp* instance = context; + const Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolIso14443_3a, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_iso14443_3a(NfcApp* instance) { + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_iso14443_3a, instance); +} + +static void nfc_scene_read_success_on_enter_iso14443_3a(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso14443_3aData* data = nfc_device_get_data(device, NfcProtocolIso14443_3a); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso14443_3a_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand + nfc_scene_emulate_listener_callback_iso14443_3a(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + furi_assert(event.event_data); + + NfcApp* nfc = context; + Iso14443_3aListenerEvent* iso14443_3a_event = event.event_data; + + if(iso14443_3a_event->type == Iso14443_3aListenerEventTypeReceivedStandardFrame) { + if(furi_string_size(nfc->text_box_store) < NFC_LOG_SIZE_MAX) { + furi_string_cat_printf(nfc->text_box_store, "R:"); + for(size_t i = 0; i < bit_buffer_get_size_bytes(iso14443_3a_event->data->buffer); + i++) { + furi_string_cat_printf( + nfc->text_box_store, + " %02X", + bit_buffer_get_byte(iso14443_3a_event->data->buffer, i)); + } + furi_string_push_back(nfc->text_box_store, '\n'); + view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventListenerUpdate); + } + } + + return NfcCommandContinue; +} + +static void nfc_scene_emulate_on_enter_iso14443_3a(NfcApp* instance) { + const Iso14443_3aData* data = + nfc_device_get_data(instance->nfc_device, NfcProtocolIso14443_3a); + + instance->listener = nfc_listener_alloc(instance->nfc, NfcProtocolIso14443_3a, data); + nfc_listener_start( + instance->listener, nfc_scene_emulate_listener_callback_iso14443_3a, instance); +} + +static bool nfc_scene_read_menu_on_event_iso14443_3a(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexCommonEmulate) { + scene_manager_next_scene(instance->scene_manager, NfcSceneEmulate); + return true; + } + + return false; +} + +const NfcProtocolSupportBase nfc_protocol_support_iso14443_3a = { + .features = NfcProtocolFeatureEmulateUid | NfcProtocolFeatureEditUid, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_iso14443_3a, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_iso14443_3a, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_scene_read_menu_on_event_iso14443_3a, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_iso14443_3a, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_scene_emulate_on_enter_iso14443_3a, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a.h b/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a.h new file mode 100644 index 000000000..d085f25c7 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_iso14443_3a; diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a_render.c b/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a_render.c new file mode 100644 index 000000000..7306f1072 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a_render.c @@ -0,0 +1,34 @@ +#include "iso14443_3a_render.h" + +void nfc_render_iso14443_3a_format_bytes(FuriString* str, const uint8_t* const data, size_t size) { + for(size_t i = 0; i < size; i++) { + furi_string_cat_printf(str, " %02X", data[i]); + } +} + +void nfc_render_iso14443_3a_info( + const Iso14443_3aData* data, + NfcProtocolFormatType format_type, + FuriString* str) { + if(format_type == NfcProtocolFormatTypeFull) { + const char iso_type = iso14443_3a_supports_iso14443_4(data) ? '4' : '3'; + furi_string_cat_printf(str, "ISO 14443-%c (NFC-A)\n", iso_type); + } + + nfc_render_iso14443_3a_brief(data, str); + + if(format_type == NfcProtocolFormatTypeFull) { + nfc_render_iso14443_3a_extra(data, str); + } +} + +void nfc_render_iso14443_3a_brief(const Iso14443_3aData* data, FuriString* str) { + furi_string_cat_printf(str, "UID:"); + + nfc_render_iso14443_3a_format_bytes(str, data->uid, data->uid_len); +} + +void nfc_render_iso14443_3a_extra(const Iso14443_3aData* data, FuriString* str) { + furi_string_cat_printf(str, "\nATQA: %02X %02X ", data->atqa[1], data->atqa[0]); + furi_string_cat_printf(str, "SAK: %02X", data->sak); +} diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a_render.h b/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a_render.h new file mode 100644 index 000000000..14b91d221 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_3a/iso14443_3a_render.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_iso14443_3a_info( + const Iso14443_3aData* data, + NfcProtocolFormatType format_type, + FuriString* str); + +void nfc_render_iso14443_3a_format_bytes(FuriString* str, const uint8_t* const data, size_t size); + +void nfc_render_iso14443_3a_brief(const Iso14443_3aData* data, FuriString* str); + +void nfc_render_iso14443_3a_extra(const Iso14443_3aData* data, FuriString* str); diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b.c b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b.c new file mode 100644 index 000000000..fee231846 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b.c @@ -0,0 +1,113 @@ +#include "iso14443_3b.h" +#include "iso14443_3b_render.h" + +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" + +static void nfc_scene_info_on_enter_iso14443_3b(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso14443_3bData* data = nfc_device_get_data(device, NfcProtocolIso14443_3b); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso14443_3b_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 64, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand + nfc_scene_read_poller_callback_iso14443_3b(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_3b); + + NfcApp* instance = context; + const Iso14443_3bPollerEvent* iso14443_3b_event = event.event_data; + + if(iso14443_3b_event->type == Iso14443_3bPollerEventTypeReady) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolIso14443_3b, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_iso14443_3b(NfcApp* instance) { + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_iso14443_3b, instance); +} + +static void nfc_scene_read_success_on_enter_iso14443_3b(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso14443_3bData* data = nfc_device_get_data(device, NfcProtocolIso14443_3b); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso14443_3b_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +bool nfc_scene_saved_menu_on_event_iso14443_3b_common(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexCommonEdit) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSetUid); + return true; + } + + return false; +} + +static bool nfc_scene_saved_menu_on_event_iso14443_3b(NfcApp* instance, uint32_t event) { + return nfc_scene_saved_menu_on_event_iso14443_3b_common(instance, event); +} + +const NfcProtocolSupportBase nfc_protocol_support_iso14443_3b = { + .features = NfcProtocolFeatureNone, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_iso14443_3b, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_iso14443_3b, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_iso14443_3b, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_scene_saved_menu_on_event_iso14443_3b, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b.h b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b.h new file mode 100644 index 000000000..bf3caa0c0 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_iso14443_3b; diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b_i.h b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b_i.h new file mode 100644 index 000000000..53fe6b392 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b_i.h @@ -0,0 +1,7 @@ +#pragma once + +#include + +#include "iso14443_3b.h" + +bool nfc_scene_saved_menu_on_event_iso14443_3b_common(NfcApp* instance, uint32_t event); diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b_render.c b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b_render.c new file mode 100644 index 000000000..2e81d57a4 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b_render.c @@ -0,0 +1,78 @@ +#include "iso14443_3b_render.h" + +void nfc_render_iso14443_3b_info( + const Iso14443_3bData* data, + NfcProtocolFormatType format_type, + FuriString* str) { + if(format_type == NfcProtocolFormatTypeFull) { + const char iso_type = iso14443_3b_supports_iso14443_4(data) ? '4' : '3'; + furi_string_cat_printf(str, "ISO 14443-%c (NFC-B)\n", iso_type); + } + + furi_string_cat_printf(str, "UID:"); + + size_t uid_size; + const uint8_t* uid = iso14443_3b_get_uid(data, &uid_size); + + for(size_t i = 0; i < uid_size; i++) { + furi_string_cat_printf(str, " %02X", uid[i]); + } + + if(format_type != NfcProtocolFormatTypeFull) return; + + furi_string_cat_printf(str, "\n\e#Protocol info\n"); + + if(iso14443_3b_supports_bit_rate(data, Iso14443_3bBitRateBoth106Kbit)) { + furi_string_cat(str, "Bit rate PICC <-> PCD:\n 106 kBit/s supported\n"); + } else { + furi_string_cat(str, "Bit rate PICC -> PCD:\n"); + if(iso14443_3b_supports_bit_rate(data, Iso14443_3bBitRatePiccToPcd212Kbit)) { + furi_string_cat(str, " 212 kBit/s supported\n"); + } + if(iso14443_3b_supports_bit_rate(data, Iso14443_3bBitRatePiccToPcd424Kbit)) { + furi_string_cat(str, " 424 kBit/s supported\n"); + } + if(iso14443_3b_supports_bit_rate(data, Iso14443_3bBitRatePiccToPcd848Kbit)) { + furi_string_cat(str, " 848 kBit/s supported\n"); + } + + furi_string_cat(str, "Bit rate PICC <- PCD:\n"); + if(iso14443_3b_supports_bit_rate(data, Iso14443_3bBitRatePcdToPicc212Kbit)) { + furi_string_cat(str, " 212 kBit/s supported\n"); + } + if(iso14443_3b_supports_bit_rate(data, Iso14443_3bBitRatePcdToPicc424Kbit)) { + furi_string_cat(str, " 424 kBit/s supported\n"); + } + if(iso14443_3b_supports_bit_rate(data, Iso14443_3bBitRatePcdToPicc848Kbit)) { + furi_string_cat(str, " 848 kBit/s supported\n"); + } + } + + furi_string_cat(str, "Max frame size: "); + + const uint16_t max_frame_size = iso14443_3b_get_frame_size_max(data); + if(max_frame_size != 0) { + furi_string_cat_printf(str, "%u bytes\n", max_frame_size); + } else { + furi_string_cat(str, "? (RFU)\n"); + } + + const double fwt = iso14443_3b_get_fwt_fc_max(data) / 13.56e6; + furi_string_cat_printf(str, "Max waiting time: %4.2g s\n", fwt); + + const char* nad_support_str = + iso14443_3b_supports_frame_option(data, Iso14443_3bFrameOptionNad) ? "" : "not "; + furi_string_cat_printf(str, "NAD: %ssupported\n", nad_support_str); + + const char* cid_support_str = + iso14443_3b_supports_frame_option(data, Iso14443_3bFrameOptionCid) ? "" : "not "; + furi_string_cat_printf(str, "CID: %ssupported", cid_support_str); + + furi_string_cat_printf(str, "\n\e#Application data\nRaw:"); + + size_t app_data_size; + const uint8_t* app_data = iso14443_3b_get_application_data(data, &app_data_size); + for(size_t i = 0; i < app_data_size; ++i) { + furi_string_cat_printf(str, " %02X", app_data[i]); + } +} diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b_render.h b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b_render.h new file mode 100644 index 000000000..ee50f6acf --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_3b/iso14443_3b_render.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_iso14443_3b_info( + const Iso14443_3bData* data, + NfcProtocolFormatType format_type, + FuriString* str); diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a.c b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a.c new file mode 100644 index 000000000..0a3a592e1 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a.c @@ -0,0 +1,149 @@ +#include "iso14443_4a.h" +#include "iso14443_4a_render.h" + +#include +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" + +static void nfc_scene_info_on_enter_iso14443_4a(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso14443_4aData* data = nfc_device_get_data(device, NfcProtocolIso14443_4a); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso14443_4a_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 64, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand + nfc_scene_read_poller_callback_iso14443_4a(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_4a); + + NfcApp* instance = context; + const Iso14443_4aPollerEvent* iso14443_4a_event = event.event_data; + + if(iso14443_4a_event->type == Iso14443_4aPollerEventTypeReady) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolIso14443_4a, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_iso14443_4a(NfcApp* instance) { + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_iso14443_4a, instance); +} + +static void nfc_scene_read_success_on_enter_iso14443_4a(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso14443_4aData* data = nfc_device_get_data(device, NfcProtocolIso14443_4a); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso14443_4a_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static void nfc_scene_saved_menu_on_enter_iso14443_4a(NfcApp* instance) { + UNUSED(instance); +} + +NfcCommand nfc_scene_emulate_listener_callback_iso14443_4a(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolIso14443_4a); + furi_assert(event.event_data); + + NfcApp* nfc = context; + Iso14443_4aListenerEvent* iso14443_4a_event = event.event_data; + + if(iso14443_4a_event->type == Iso14443_4aListenerEventTypeReceivedData) { + if(furi_string_size(nfc->text_box_store) < NFC_LOG_SIZE_MAX) { + furi_string_cat_printf(nfc->text_box_store, "R:"); + for(size_t i = 0; i < bit_buffer_get_size_bytes(iso14443_4a_event->data->buffer); + i++) { + furi_string_cat_printf( + nfc->text_box_store, + " %02X", + bit_buffer_get_byte(iso14443_4a_event->data->buffer, i)); + } + furi_string_push_back(nfc->text_box_store, '\n'); + view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventListenerUpdate); + } + } + + return NfcCommandContinue; +} + +static void nfc_scene_emulate_on_enter_iso14443_4a(NfcApp* instance) { + const Iso14443_4aData* data = + nfc_device_get_data(instance->nfc_device, NfcProtocolIso14443_4a); + + instance->listener = nfc_listener_alloc(instance->nfc, NfcProtocolIso14443_4a, data); + nfc_listener_start( + instance->listener, nfc_scene_emulate_listener_callback_iso14443_4a, instance); +} + +static bool nfc_scene_read_menu_on_event_iso14443_4a(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexCommonEmulate) { + scene_manager_next_scene(instance->scene_manager, NfcSceneEmulate); + return true; + } + + return false; +} + +const NfcProtocolSupportBase nfc_protocol_support_iso14443_4a = { + .features = NfcProtocolFeatureEmulateUid | NfcProtocolFeatureEditUid, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_iso14443_4a, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_iso14443_4a, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_scene_read_menu_on_event_iso14443_4a, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_iso14443_4a, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_scene_saved_menu_on_enter_iso14443_4a, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_scene_emulate_on_enter_iso14443_4a, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a.h b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a.h new file mode 100644 index 000000000..1b173d7b0 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_iso14443_4a; diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a_i.h b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a_i.h new file mode 100644 index 000000000..7e13403da --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a_i.h @@ -0,0 +1,7 @@ +#pragma once + +#include + +#include "iso14443_4a.h" + +NfcCommand nfc_scene_emulate_listener_callback_iso14443_4a(NfcGenericEvent event, void* context); diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a_render.c b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a_render.c new file mode 100644 index 000000000..a963e744b --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a_render.c @@ -0,0 +1,84 @@ +#include "iso14443_4a_render.h" + +#include "../iso14443_3a/iso14443_3a_render.h" + +void nfc_render_iso14443_4a_info( + const Iso14443_4aData* data, + NfcProtocolFormatType format_type, + FuriString* str) { + nfc_render_iso14443_4a_brief(data, str); + + if(format_type != NfcProtocolFormatTypeFull) return; + + nfc_render_iso14443_4a_extra(data, str); +} + +void nfc_render_iso14443_4a_brief(const Iso14443_4aData* data, FuriString* str) { + nfc_render_iso14443_3a_brief(iso14443_4a_get_base_data(data), str); +} + +void nfc_render_iso14443_4a_extra(const Iso14443_4aData* data, FuriString* str) { + furi_string_cat_printf(str, "\n\e#Protocol info\n"); + + if(iso14443_4a_supports_bit_rate(data, Iso14443_4aBitRateBoth106Kbit)) { + furi_string_cat(str, "Bit rate PICC <-> PCD:\n 106 kBit/s supported\n"); + } else { + furi_string_cat(str, "Bit rate PICC -> PCD:\n"); + if(iso14443_4a_supports_bit_rate(data, Iso14443_4aBitRatePiccToPcd212Kbit)) { + furi_string_cat(str, " 212 kBit/s supported\n"); + } + if(iso14443_4a_supports_bit_rate(data, Iso14443_4aBitRatePiccToPcd424Kbit)) { + furi_string_cat(str, " 424 kBit/s supported\n"); + } + if(iso14443_4a_supports_bit_rate(data, Iso14443_4aBitRatePiccToPcd848Kbit)) { + furi_string_cat(str, " 848 kBit/s supported\n"); + } + + furi_string_cat(str, "Bit rate PICC <- PCD:\n"); + if(iso14443_4a_supports_bit_rate(data, Iso14443_4aBitRatePcdToPicc212Kbit)) { + furi_string_cat(str, " 212 kBit/s supported\n"); + } + if(iso14443_4a_supports_bit_rate(data, Iso14443_4aBitRatePcdToPicc424Kbit)) { + furi_string_cat(str, " 424 kBit/s supported\n"); + } + if(iso14443_4a_supports_bit_rate(data, Iso14443_4aBitRatePcdToPicc848Kbit)) { + furi_string_cat(str, " 848 kBit/s supported\n"); + } + } + + furi_string_cat(str, "Max frame size: "); + + const uint16_t max_frame_size = iso14443_4a_get_frame_size_max(data); + if(max_frame_size != 0) { + furi_string_cat_printf(str, "%u bytes\n", max_frame_size); + } else { + furi_string_cat(str, "? (RFU)\n"); + } + + const uint32_t fwt_fc = iso14443_4a_get_fwt_fc_max(data); + if(fwt_fc != 0) { + furi_string_cat_printf(str, "Max waiting time: %4.2g s\n", (double)(fwt_fc / 13.56e6)); + } + + const char* nad_support_str = + iso14443_4a_supports_frame_option(data, Iso14443_4aFrameOptionNad) ? "" : "not "; + furi_string_cat_printf(str, "NAD: %ssupported\n", nad_support_str); + + const char* cid_support_str = + iso14443_4a_supports_frame_option(data, Iso14443_4aFrameOptionCid) ? "" : "not "; + furi_string_cat_printf(str, "CID: %ssupported", cid_support_str); + + uint32_t hist_bytes_count; + const uint8_t* hist_bytes = iso14443_4a_get_historical_bytes(data, &hist_bytes_count); + + if(hist_bytes_count > 0) { + furi_string_cat_printf(str, "\n\e#Historical bytes\nRaw:"); + + for(size_t i = 0; i < hist_bytes_count; ++i) { + furi_string_cat_printf(str, " %02X", hist_bytes[i]); + } + } + + furi_string_cat(str, "\n\e#ISO14443-3A data"); + nfc_render_iso14443_3a_extra(iso14443_4a_get_base_data(data), str); +} diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a_render.h b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a_render.h new file mode 100644 index 000000000..fdcd7066e --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_4a/iso14443_4a_render.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_iso14443_4a_info( + const Iso14443_4aData* data, + NfcProtocolFormatType format_type, + FuriString* str); + +void nfc_render_iso14443_4a_brief(const Iso14443_4aData* data, FuriString* str); + +void nfc_render_iso14443_4a_extra(const Iso14443_4aData* data, FuriString* str); diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b.c b/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b.c new file mode 100644 index 000000000..a0c70a22e --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b.c @@ -0,0 +1,118 @@ +#include "iso14443_4b.h" +#include "iso14443_4b_render.h" + +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" +#include "../iso14443_3b/iso14443_3b_i.h" + +static void nfc_scene_info_on_enter_iso14443_4b(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso14443_4bData* data = nfc_device_get_data(device, NfcProtocolIso14443_4b); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso14443_4b_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 64, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand + nfc_scene_read_poller_callback_iso14443_4b(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_4b); + + NfcApp* instance = context; + const Iso14443_4bPollerEvent* iso14443_4b_event = event.event_data; + + if(iso14443_4b_event->type == Iso14443_4bPollerEventTypeReady) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolIso14443_4b, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_iso14443_4b(NfcApp* instance) { + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_iso14443_4b, instance); +} + +static void nfc_scene_read_success_on_enter_iso14443_4b(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso14443_4bData* data = nfc_device_get_data(device, NfcProtocolIso14443_4b); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso14443_4b_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static void nfc_scene_saved_menu_on_enter_iso14443_4b(NfcApp* instance) { + UNUSED(instance); +} + +static bool nfc_scene_read_menu_on_event_iso14443_4b(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexCommonEmulate) { + scene_manager_next_scene(instance->scene_manager, NfcSceneEmulate); + return true; + } + + return false; +} + +static bool nfc_scene_saved_menu_on_event_iso14443_4b(NfcApp* instance, uint32_t event) { + return nfc_scene_saved_menu_on_event_iso14443_3b_common(instance, event); +} + +const NfcProtocolSupportBase nfc_protocol_support_iso14443_4b = { + .features = NfcProtocolFeatureNone, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_iso14443_4b, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_iso14443_4b, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_scene_read_menu_on_event_iso14443_4b, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_iso14443_4b, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_scene_saved_menu_on_enter_iso14443_4b, + .on_event = nfc_scene_saved_menu_on_event_iso14443_4b, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b.h b/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b.h new file mode 100644 index 000000000..84a3456d4 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_iso14443_4b; diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b_render.c b/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b_render.c new file mode 100644 index 000000000..e15b289a0 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b_render.c @@ -0,0 +1,10 @@ +#include "iso14443_4b_render.h" + +#include "../iso14443_3b/iso14443_3b_render.h" + +void nfc_render_iso14443_4b_info( + const Iso14443_4bData* data, + NfcProtocolFormatType format_type, + FuriString* str) { + nfc_render_iso14443_3b_info(iso14443_4b_get_base_data(data), format_type, str); +} diff --git a/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b_render.h b/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b_render.h new file mode 100644 index 000000000..094892f83 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso14443_4b/iso14443_4b_render.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_iso14443_4b_info( + const Iso14443_4bData* data, + NfcProtocolFormatType format_type, + FuriString* str); diff --git a/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3.c b/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3.c new file mode 100644 index 000000000..7f861a032 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3.c @@ -0,0 +1,144 @@ +#include "iso15693_3.h" +#include "iso15693_3_render.h" + +#include +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" + +static void nfc_scene_info_on_enter_iso15693_3(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso15693_3Data* data = nfc_device_get_data(device, NfcProtocolIso15693_3); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso15693_3_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 64, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand nfc_scene_read_poller_callback_iso15693_3(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso15693_3); + + NfcApp* instance = context; + const Iso15693_3PollerEvent* iso15693_3_event = event.event_data; + + if(iso15693_3_event->type == Iso15693_3PollerEventTypeReady) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolIso15693_3, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_iso15693_3(NfcApp* instance) { + UNUSED(instance); + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_iso15693_3, instance); +} + +static void nfc_scene_read_success_on_enter_iso15693_3(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const Iso15693_3Data* data = nfc_device_get_data(device, NfcProtocolIso15693_3); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_iso15693_3_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand + nfc_scene_emulate_listener_callback_iso15693_3(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolIso15693_3); + furi_assert(event.event_data); + + NfcApp* nfc = context; + Iso15693_3ListenerEvent* iso15693_3_event = event.event_data; + + if(iso15693_3_event->type == Iso15693_3ListenerEventTypeCustomCommand) { + if(furi_string_size(nfc->text_box_store) < NFC_LOG_SIZE_MAX) { + furi_string_cat_printf(nfc->text_box_store, "R:"); + for(size_t i = 0; i < bit_buffer_get_size_bytes(iso15693_3_event->data->buffer); i++) { + furi_string_cat_printf( + nfc->text_box_store, + " %02X", + bit_buffer_get_byte(iso15693_3_event->data->buffer, i)); + } + furi_string_push_back(nfc->text_box_store, '\n'); + view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventListenerUpdate); + } + } + + return NfcCommandContinue; +} + +static void nfc_scene_emulate_on_enter_iso15693_3(NfcApp* instance) { + const Iso15693_3Data* data = nfc_device_get_data(instance->nfc_device, NfcProtocolIso15693_3); + + instance->listener = nfc_listener_alloc(instance->nfc, NfcProtocolIso15693_3, data); + nfc_listener_start( + instance->listener, nfc_scene_emulate_listener_callback_iso15693_3, instance); +} + +static bool nfc_scene_saved_menu_on_event_iso15693_3(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexCommonEdit) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSetUid); + return true; + } + + return false; +} + +const NfcProtocolSupportBase nfc_protocol_support_iso15693_3 = { + .features = NfcProtocolFeatureEmulateFull | NfcProtocolFeatureEditUid, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_iso15693_3, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_iso15693_3, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_iso15693_3, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_scene_saved_menu_on_event_iso15693_3, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_scene_emulate_on_enter_iso15693_3, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3.h b/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3.h new file mode 100644 index 000000000..a26633ee6 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_iso15693_3; diff --git a/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3_render.c b/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3_render.c new file mode 100644 index 000000000..92bdb22dc --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3_render.c @@ -0,0 +1,92 @@ +#include "iso15693_3_render.h" + +#define NFC_RENDER_ISO15693_3_MAX_BYTES (128U) + +void nfc_render_iso15693_3_info( + const Iso15693_3Data* data, + NfcProtocolFormatType format_type, + FuriString* str) { + if(format_type == NfcProtocolFormatTypeFull) { + furi_string_cat(str, "ISO15693-3 (NFC-V)\n"); + } + + nfc_render_iso15693_3_brief(data, str); + + if(format_type == NfcProtocolFormatTypeFull) { + nfc_render_iso15693_3_extra(data, str); + } +} + +void nfc_render_iso15693_3_brief(const Iso15693_3Data* data, FuriString* str) { + furi_string_cat_printf(str, "UID:"); + + size_t uid_len; + const uint8_t* uid = iso15693_3_get_uid(data, &uid_len); + + for(size_t i = 0; i < uid_len; i++) { + furi_string_cat_printf(str, " %02X", uid[i]); + } + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_MEMORY) { + const uint16_t block_count = iso15693_3_get_block_count(data); + const uint8_t block_size = iso15693_3_get_block_size(data); + + furi_string_cat_printf(str, "Memory: %u bytes\n", block_count * block_size); + furi_string_cat_printf(str, "(%u blocks x %u bytes)", block_count, block_size); + } +} + +void nfc_render_iso15693_3_extra(const Iso15693_3Data* data, FuriString* str) { + furi_string_cat(str, "\n\e#General info\n"); + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_DSFID) { + furi_string_cat_printf(str, "DSFID: %02X\n", data->system_info.ic_ref); + } + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_AFI) { + furi_string_cat_printf(str, "AFI: %02X\n", data->system_info.afi); + } + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_IC_REF) { + furi_string_cat_printf(str, "IC Reference: %02X\n", data->system_info.ic_ref); + } + + furi_string_cat(str, "\e#Lock bits\n"); + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_DSFID) { + furi_string_cat_printf( + str, "DSFID: %s locked\n", data->settings.lock_bits.dsfid ? "" : "not"); + } + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_AFI) { + furi_string_cat_printf( + str, "AFI: %s locked\n", data->settings.lock_bits.dsfid ? "" : "not"); + } + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_MEMORY) { + furi_string_cat(str, "\e#Memory data\n\e*--------------------\n"); + + const uint16_t block_count = iso15693_3_get_block_count(data); + const uint8_t block_size = iso15693_3_get_block_size(data); + const uint16_t display_block_count = + MIN(NFC_RENDER_ISO15693_3_MAX_BYTES / block_size, block_count); + + for(uint32_t i = 0; i < display_block_count; ++i) { + furi_string_cat(str, "\e*"); + + const uint8_t* block_data = iso15693_3_get_block_data(data, i); + for(uint32_t j = 0; j < block_size; ++j) { + furi_string_cat_printf(str, "%02X ", block_data[j]); + } + + const char* lock_str = iso15693_3_is_block_locked(data, i) ? "[LOCK]" : ""; + furi_string_cat_printf(str, "| %s\n", lock_str); + } + + if(block_count != display_block_count) { + furi_string_cat_printf( + str, + "(Data is too big. Showing only the first %u bytes.)", + display_block_count * block_size); + } + } +} diff --git a/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3_render.h b/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3_render.h new file mode 100644 index 000000000..d531fd2eb --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/iso15693_3/iso15693_3_render.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_iso15693_3_info( + const Iso15693_3Data* data, + NfcProtocolFormatType format_type, + FuriString* str); + +void nfc_render_iso15693_3_brief(const Iso15693_3Data* data, FuriString* str); + +void nfc_render_iso15693_3_extra(const Iso15693_3Data* data, FuriString* str); diff --git a/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic.c b/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic.c new file mode 100644 index 000000000..3e0468cd9 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic.c @@ -0,0 +1,252 @@ +#include "mf_classic.h" +#include "mf_classic_render.h" + +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" + +#define TAG "MfClassicApp" + +enum { + SubmenuIndexDetectReader = SubmenuIndexCommonMax, + SubmenuIndexWrite, + SubmenuIndexUpdate, +}; + +static void nfc_scene_info_on_enter_mf_classic(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const MfClassicData* data = nfc_device_get_data(device, NfcProtocolMfClassic); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_mf_classic_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static void nfc_scene_more_info_on_enter_mf_classic(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const MfClassicData* mfc_data = nfc_device_get_data(device, NfcProtocolMfClassic); + + furi_string_reset(instance->text_box_store); + nfc_render_mf_classic_dump(mfc_data, instance->text_box_store); + + text_box_set_font(instance->text_box, TextBoxFontHex); + text_box_set_text(instance->text_box, furi_string_get_cstr(instance->text_box_store)); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewTextBox); +} + +static NfcCommand nfc_scene_read_poller_callback_mf_classic(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolMfClassic); + + NfcApp* instance = context; + const MfClassicPollerEvent* mfc_event = event.event_data; + NfcCommand command = NfcCommandContinue; + + if(mfc_event->type == MfClassicPollerEventTypeRequestMode) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolMfClassic, nfc_poller_get_data(instance->poller)); + size_t uid_len = 0; + const uint8_t* uid = nfc_device_get_uid(instance->nfc_device, &uid_len); + if(mf_classic_key_cache_load(instance->mfc_key_cache, uid, uid_len)) { + FURI_LOG_I(TAG, "Key cache found"); + mfc_event->data->poller_mode.mode = MfClassicPollerModeRead; + } else { + FURI_LOG_I(TAG, "Key cache not found"); + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventPollerIncomplete); + command = NfcCommandStop; + } + } else if(mfc_event->type == MfClassicPollerEventTypeRequestReadSector) { + uint8_t sector_num = 0; + MfClassicKey key = {}; + MfClassicKeyType key_type = MfClassicKeyTypeA; + if(mf_classic_key_cahce_get_next_key( + instance->mfc_key_cache, §or_num, &key, &key_type)) { + mfc_event->data->read_sector_request_data.sector_num = sector_num; + mfc_event->data->read_sector_request_data.key = key; + mfc_event->data->read_sector_request_data.key_type = key_type; + mfc_event->data->read_sector_request_data.key_provided = true; + } else { + mfc_event->data->read_sector_request_data.key_provided = false; + } + } else if(mfc_event->type == MfClassicPollerEventTypeSuccess) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolMfClassic, nfc_poller_get_data(instance->poller)); + const MfClassicData* mfc_data = + nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic); + NfcCustomEvent custom_event = mf_classic_is_card_read(mfc_data) ? + NfcCustomEventPollerSuccess : + NfcCustomEventPollerIncomplete; + view_dispatcher_send_custom_event(instance->view_dispatcher, custom_event); + command = NfcCommandStop; + } + + return command; +} + +static void nfc_scene_read_on_enter_mf_classic(NfcApp* instance) { + mf_classic_key_cache_reset(instance->mfc_key_cache); + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_mf_classic, instance); +} + +static bool nfc_scene_read_on_event_mf_classic(NfcApp* instance, uint32_t event) { + if(event == NfcCustomEventPollerIncomplete) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicDictAttack); + } + + return true; +} + +static void nfc_scene_read_menu_on_enter_mf_classic(NfcApp* instance) { + Submenu* submenu = instance->submenu; + const MfClassicData* data = nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic); + + if(!mf_classic_is_card_read(data)) { + submenu_add_item( + submenu, + "Detect Reader", + SubmenuIndexDetectReader, + nfc_protocol_support_common_submenu_callback, + instance); + } +} + +static void nfc_scene_read_success_on_enter_mf_classic(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const MfClassicData* data = nfc_device_get_data(device, NfcProtocolMfClassic); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_mf_classic_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static void nfc_scene_saved_menu_on_enter_mf_classic(NfcApp* instance) { + Submenu* submenu = instance->submenu; + const MfClassicData* data = nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic); + + if(!mf_classic_is_card_read(data)) { + submenu_add_item( + submenu, + "Detect Reader", + SubmenuIndexDetectReader, + nfc_protocol_support_common_submenu_callback, + instance); + } + submenu_add_item( + submenu, + "Write to Initial Card", + SubmenuIndexWrite, + nfc_protocol_support_common_submenu_callback, + instance); + submenu_add_item( + submenu, + "Update from Initial Card", + SubmenuIndexUpdate, + nfc_protocol_support_common_submenu_callback, + instance); +} + +static void nfc_scene_emulate_on_enter_mf_classic(NfcApp* instance) { + const MfClassicData* data = nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic); + instance->listener = nfc_listener_alloc(instance->nfc, NfcProtocolMfClassic, data); + nfc_listener_start(instance->listener, NULL, NULL); +} + +static bool nfc_scene_read_menu_on_event_mf_classic(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexDetectReader) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicDetectReader); + dolphin_deed(DolphinDeedNfcDetectReader); + return true; + } + + return false; +} + +static bool nfc_scene_saved_menu_on_event_mf_classic(NfcApp* instance, uint32_t event) { + bool consumed = false; + + if(event == SubmenuIndexDetectReader) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicDetectReader); + consumed = true; + } else if(event == SubmenuIndexWrite) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicWriteInitial); + consumed = true; + } else if(event == SubmenuIndexUpdate) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicUpdateInitial); + consumed = true; + } + + return consumed; +} + +static bool nfc_scene_save_name_on_event_mf_classic(NfcApp* instance, uint32_t event) { + bool consumed = false; + + if(event == NfcCustomEventTextInputDone) { + mf_classic_key_cache_save( + instance->mfc_key_cache, + nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic)); + consumed = true; + } + + return consumed; +} + +const NfcProtocolSupportBase nfc_protocol_support_mf_classic = { + .features = NfcProtocolFeatureEmulateFull | NfcProtocolFeatureMoreInfo, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_mf_classic, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_more_info = + { + .on_enter = nfc_scene_more_info_on_enter_mf_classic, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_mf_classic, + .on_event = nfc_scene_read_on_event_mf_classic, + }, + .scene_read_menu = + { + .on_enter = nfc_scene_read_menu_on_enter_mf_classic, + .on_event = nfc_scene_read_menu_on_event_mf_classic, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_mf_classic, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_scene_saved_menu_on_enter_mf_classic, + .on_event = nfc_scene_saved_menu_on_event_mf_classic, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_scene_save_name_on_event_mf_classic, + }, + .scene_emulate = + { + .on_enter = nfc_scene_emulate_on_enter_mf_classic, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic.h b/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic.h new file mode 100644 index 000000000..d0f09f5d7 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_mf_classic; diff --git a/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic_render.c b/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic_render.c new file mode 100644 index 000000000..5bd4a6b6d --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic_render.c @@ -0,0 +1,30 @@ +#include "mf_classic_render.h" + +#include "../iso14443_3a/iso14443_3a_render.h" + +void nfc_render_mf_classic_info( + const MfClassicData* data, + NfcProtocolFormatType format_type, + FuriString* str) { + nfc_render_iso14443_3a_info(data->iso14443_3a_data, format_type, str); + + uint8_t sectors_total = mf_classic_get_total_sectors_num(data->type); + uint8_t keys_total = sectors_total * 2; + uint8_t keys_found = 0; + uint8_t sectors_read = 0; + mf_classic_get_read_sectors_and_keys(data, §ors_read, &keys_found); + + furi_string_cat_printf(str, "\nKeys Found: %u/%u", keys_found, keys_total); + furi_string_cat_printf(str, "\nSectors Read: %u/%u", sectors_read, sectors_total); +} + +void nfc_render_mf_classic_dump(const MfClassicData* data, FuriString* str) { + uint16_t total_blocks = mf_classic_get_total_block_num(data->type); + + for(size_t i = 0; i < total_blocks; i++) { + for(size_t j = 0; j < sizeof(MfClassicBlock); j += 2) { + furi_string_cat_printf( + str, "%02X%02X ", data->block[i].data[j], data->block[i].data[j + 1]); + } + } +} diff --git a/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic_render.h b/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic_render.h new file mode 100644 index 000000000..7e1619761 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_classic/mf_classic_render.h @@ -0,0 +1,12 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_mf_classic_info( + const MfClassicData* data, + NfcProtocolFormatType format_type, + FuriString* str); + +void nfc_render_mf_classic_dump(const MfClassicData* data, FuriString* str); diff --git a/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire.c b/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire.c new file mode 100644 index 000000000..bc05c2a4c --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire.c @@ -0,0 +1,120 @@ +#include "mf_desfire.h" +#include "mf_desfire_render.h" + +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" +#include "../iso14443_4a/iso14443_4a_i.h" + +static void nfc_scene_info_on_enter_mf_desfire(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const MfDesfireData* data = nfc_device_get_data(device, NfcProtocolMfDesfire); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_mf_desfire_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static void nfc_scene_more_info_on_enter_mf_desfire(NfcApp* instance) { + // Jump to advanced scene right away + scene_manager_next_scene(instance->scene_manager, NfcSceneMfDesfireMoreInfo); +} + +static NfcCommand nfc_scene_read_poller_callback_mf_desfire(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolMfDesfire); + + NfcApp* instance = context; + const MfDesfirePollerEvent* mf_desfire_event = event.event_data; + + if(mf_desfire_event->type == MfDesfirePollerEventTypeReadSuccess) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolMfDesfire, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_mf_desfire(NfcApp* instance) { + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_mf_desfire, instance); +} + +static void nfc_scene_read_success_on_enter_mf_desfire(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const MfDesfireData* data = nfc_device_get_data(device, NfcProtocolMfDesfire); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_mf_desfire_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static void nfc_scene_emulate_on_enter_mf_desfire(NfcApp* instance) { + const Iso14443_4aData* iso14443_4a_data = + nfc_device_get_data(instance->nfc_device, NfcProtocolIso14443_4a); + + instance->listener = + nfc_listener_alloc(instance->nfc, NfcProtocolIso14443_4a, iso14443_4a_data); + nfc_listener_start( + instance->listener, nfc_scene_emulate_listener_callback_iso14443_4a, instance); +} + +const NfcProtocolSupportBase nfc_protocol_support_mf_desfire = { + .features = NfcProtocolFeatureEmulateUid | NfcProtocolFeatureMoreInfo, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_mf_desfire, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_more_info = + { + .on_enter = nfc_scene_more_info_on_enter_mf_desfire, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_mf_desfire, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_mf_desfire, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_scene_emulate_on_enter_mf_desfire, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire.h b/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire.h new file mode 100644 index 000000000..504860f16 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_mf_desfire; diff --git a/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire_render.c b/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire_render.c new file mode 100644 index 000000000..94b333f55 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire_render.c @@ -0,0 +1,266 @@ +#include "mf_desfire_render.h" + +#include "../iso14443_4a/iso14443_4a_render.h" + +void nfc_render_mf_desfire_info( + const MfDesfireData* data, + NfcProtocolFormatType format_type, + FuriString* str) { + nfc_render_iso14443_4a_brief(mf_desfire_get_base_data(data), str); + + const uint32_t bytes_total = 1UL << (data->version.sw_storage >> 1); + const uint32_t bytes_free = data->free_memory.is_present ? data->free_memory.bytes_free : 0; + + furi_string_cat_printf(str, "\n%lu", bytes_total); + + if(data->version.sw_storage & 1) { + furi_string_push_back(str, '+'); + } + + furi_string_cat_printf(str, " bytes, %lu bytes free\n", bytes_free); + + const uint32_t app_count = simple_array_get_count(data->applications); + uint32_t file_count = 0; + + for(uint32_t i = 0; i < app_count; ++i) { + const MfDesfireApplication* app = simple_array_cget(data->applications, i); + file_count += simple_array_get_count(app->file_ids); + } + + furi_string_cat_printf(str, "%lu Application%s", app_count, app_count != 1 ? "s" : ""); + furi_string_cat_printf(str, ", %lu File%s", file_count, file_count != 1 ? "s" : ""); + + if(format_type != NfcProtocolFormatTypeFull) return; + + furi_string_cat(str, "\n\e#ISO14443-4 data"); + nfc_render_iso14443_4a_extra(mf_desfire_get_base_data(data), str); +} + +void nfc_render_mf_desfire_data(const MfDesfireData* data, FuriString* str) { + nfc_render_mf_desfire_version(&data->version, str); + nfc_render_mf_desfire_free_memory(&data->free_memory, str); + nfc_render_mf_desfire_key_settings(&data->master_key_settings, str); + + for(uint32_t i = 0; i < simple_array_get_count(data->master_key_versions); ++i) { + nfc_render_mf_desfire_key_version(simple_array_cget(data->master_key_versions, i), i, str); + } +} + +void nfc_render_mf_desfire_version(const MfDesfireVersion* data, FuriString* str) { + furi_string_cat_printf( + str, + "%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", + data->uid[0], + data->uid[1], + data->uid[2], + data->uid[3], + data->uid[4], + data->uid[5], + data->uid[6]); + furi_string_cat_printf( + str, + "hw %02x type %02x sub %02x\n" + " maj %02x min %02x\n" + " size %02x proto %02x\n", + data->hw_vendor, + data->hw_type, + data->hw_subtype, + data->hw_major, + data->hw_minor, + data->hw_storage, + data->hw_proto); + furi_string_cat_printf( + str, + "sw %02x type %02x sub %02x\n" + " maj %02x min %02x\n" + " size %02x proto %02x\n", + data->sw_vendor, + data->sw_type, + data->sw_subtype, + data->sw_major, + data->sw_minor, + data->sw_storage, + data->sw_proto); + furi_string_cat_printf( + str, + "batch %02x:%02x:%02x:%02x:%02x\n" + "week %d year %d\n", + data->batch[0], + data->batch[1], + data->batch[2], + data->batch[3], + data->batch[4], + data->prod_week, + data->prod_year); +} + +void nfc_render_mf_desfire_free_memory(const MfDesfireFreeMemory* data, FuriString* str) { + if(data->is_present) { + furi_string_cat_printf(str, "freeMem %lu\n", data->bytes_free); + } +} + +void nfc_render_mf_desfire_key_settings(const MfDesfireKeySettings* data, FuriString* str) { + furi_string_cat_printf(str, "changeKeyID %d\n", data->change_key_id); + furi_string_cat_printf(str, "configChangeable %d\n", data->is_config_changeable); + furi_string_cat_printf(str, "freeCreateDelete %d\n", data->is_free_create_delete); + furi_string_cat_printf(str, "freeDirectoryList %d\n", data->is_free_directory_list); + furi_string_cat_printf(str, "masterChangeable %d\n", data->is_master_key_changeable); + + if(data->flags) { + furi_string_cat_printf(str, "flags %d\n", data->flags); + } + + furi_string_cat_printf(str, "maxKeys %d\n", data->max_keys); +} + +void nfc_render_mf_desfire_key_version( + const MfDesfireKeyVersion* data, + uint32_t index, + FuriString* str) { + furi_string_cat_printf(str, "key %lu version %u\n", index, *data); +} + +void nfc_render_mf_desfire_application_id(const MfDesfireApplicationId* data, FuriString* str) { + const uint8_t* app_id = data->data; + furi_string_cat_printf(str, "Application %02x%02x%02x\n", app_id[0], app_id[1], app_id[2]); +} + +void nfc_render_mf_desfire_application(const MfDesfireApplication* data, FuriString* str) { + nfc_render_mf_desfire_key_settings(&data->key_settings, str); + + for(uint32_t i = 0; i < simple_array_get_count(data->key_versions); ++i) { + nfc_render_mf_desfire_key_version(simple_array_cget(data->key_versions, i), i, str); + } +} + +void nfc_render_mf_desfire_file_id(const MfDesfireFileId* data, FuriString* str) { + furi_string_cat_printf(str, "File %d\n", *data); +} + +void nfc_render_mf_desfire_file_settings_data( + const MfDesfireFileSettings* settings, + const MfDesfireFileData* data, + FuriString* str) { + const char* type; + switch(settings->type) { + case MfDesfireFileTypeStandard: + type = "standard"; + break; + case MfDesfireFileTypeBackup: + type = "backup"; + break; + case MfDesfireFileTypeValue: + type = "value"; + break; + case MfDesfireFileTypeLinearRecord: + type = "linear"; + break; + case MfDesfireFileTypeCyclicRecord: + type = "cyclic"; + break; + default: + type = "unknown"; + } + + const char* comm; + switch(settings->comm) { + case MfDesfireFileCommunicationSettingsPlaintext: + comm = "plain"; + break; + case MfDesfireFileCommunicationSettingsAuthenticated: + comm = "auth"; + break; + case MfDesfireFileCommunicationSettingsEnciphered: + comm = "enciphered"; + break; + default: + comm = "unknown"; + } + + furi_string_cat_printf(str, "%s %s\n", type, comm); + furi_string_cat_printf( + str, + "r %d w %d rw %d c %d\n", + settings->access_rights >> 12 & 0xF, + settings->access_rights >> 8 & 0xF, + settings->access_rights >> 4 & 0xF, + settings->access_rights & 0xF); + + uint32_t record_count = 1; + uint32_t record_size = 0; + + const uint32_t total_size = simple_array_get_count(data->data); + + switch(settings->type) { + case MfDesfireFileTypeStandard: + case MfDesfireFileTypeBackup: + record_size = settings->data.size; + furi_string_cat_printf(str, "size %lu\n", record_size); + break; + case MfDesfireFileTypeValue: + record_size = MF_DESFIRE_VALUE_SIZE; + furi_string_cat_printf( + str, "lo %lu hi %lu\n", settings->value.lo_limit, settings->value.hi_limit); + furi_string_cat_printf( + str, + "limit %lu enabled %d\n", + settings->value.limited_credit_value, + settings->value.limited_credit_enabled); + break; + case MfDesfireFileTypeLinearRecord: + case MfDesfireFileTypeCyclicRecord: + record_count = settings->record.cur; + record_size = settings->record.size; + furi_string_cat_printf(str, "size %lu\n", record_size); + furi_string_cat_printf(str, "num %lu max %lu\n", record_count, settings->record.max); + break; + } + + if(simple_array_get_count(data->data) == 0) { + return; + } + + for(uint32_t rec = 0; rec < record_count; rec++) { + const uint32_t size_offset = rec * record_size; + const uint32_t size_remaining = total_size > size_offset ? total_size - size_offset : 0; + + if(size_remaining < record_size) { + furi_string_cat_printf( + str, "record %lu (partial %lu of %lu)\n", rec, size_remaining, record_size); + record_size = size_remaining; + } else { + furi_string_cat_printf(str, "record %lu\n", rec); + } + + for(uint32_t ch = 0; ch < record_size; ch += 4) { + furi_string_cat_printf(str, "%03lx|", ch); + + for(uint32_t i = 0; i < 4; i++) { + if(ch + i < record_size) { + const uint32_t data_index = rec * record_size + ch + i; + const uint8_t data_byte = + *(const uint8_t*)simple_array_cget(data->data, data_index); + furi_string_cat_printf(str, "%02x ", data_byte); + } else { + furi_string_cat_printf(str, " "); + } + } + + for(uint32_t i = 0; i < 4 && ch + i < record_size; i++) { + const uint32_t data_index = rec * record_size + ch + i; + const uint8_t data_byte = + *(const uint8_t*)simple_array_cget(data->data, data_index); + if(isprint(data_byte)) { + furi_string_cat_printf(str, "%c", data_byte); + } else { + furi_string_cat_printf(str, "."); + } + } + + furi_string_push_back(str, '\n'); + } + + furi_string_push_back(str, '\n'); + } +} diff --git a/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire_render.h b/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire_render.h new file mode 100644 index 000000000..ff5e815bf --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_desfire/mf_desfire_render.h @@ -0,0 +1,34 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_mf_desfire_info( + const MfDesfireData* data, + NfcProtocolFormatType format_type, + FuriString* str); + +void nfc_render_mf_desfire_data(const MfDesfireData* data, FuriString* str); + +void nfc_render_mf_desfire_version(const MfDesfireVersion* data, FuriString* str); + +void nfc_render_mf_desfire_free_memory(const MfDesfireFreeMemory* data, FuriString* str); + +void nfc_render_mf_desfire_key_settings(const MfDesfireKeySettings* data, FuriString* str); + +void nfc_render_mf_desfire_key_version( + const MfDesfireKeyVersion* data, + uint32_t index, + FuriString* str); + +void nfc_render_mf_desfire_application_id(const MfDesfireApplicationId* data, FuriString* str); + +void nfc_render_mf_desfire_application(const MfDesfireApplication* data, FuriString* str); + +void nfc_render_mf_desfire_file_id(const MfDesfireFileId* data, FuriString* str); + +void nfc_render_mf_desfire_file_settings_data( + const MfDesfireFileSettings* settings, + const MfDesfireFileData* data, + FuriString* str); diff --git a/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight.c b/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight.c new file mode 100644 index 000000000..c4fd04c7e --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight.c @@ -0,0 +1,196 @@ +#include "mf_ultralight.h" +#include "mf_ultralight_render.h" + +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" + +enum { + SubmenuIndexUnlock = SubmenuIndexCommonMax, + SubmenuIndexUnlockByReader, + SubmenuIndexUnlockByPassword, +}; + +static void nfc_scene_info_on_enter_mf_ultralight(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const MfUltralightData* data = nfc_device_get_data(device, NfcProtocolMfUltralight); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_mf_ultralight_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static void nfc_scene_more_info_on_enter_mf_ultralight(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const MfUltralightData* mfu = nfc_device_get_data(device, NfcProtocolMfUltralight); + + furi_string_reset(instance->text_box_store); + nfc_render_mf_ultralight_dump(mfu, instance->text_box_store); + + text_box_set_font(instance->text_box, TextBoxFontHex); + text_box_set_text(instance->text_box, furi_string_get_cstr(instance->text_box_store)); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewTextBox); +} + +static NfcCommand + nfc_scene_read_poller_callback_mf_ultralight(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolMfUltralight); + + NfcApp* instance = context; + const MfUltralightPollerEvent* mf_ultralight_event = event.event_data; + + if(mf_ultralight_event->type == MfUltralightPollerEventTypeReadSuccess) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolMfUltralight, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } else if(mf_ultralight_event->type == MfUltralightPollerEventTypeAuthRequest) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolMfUltralight, nfc_poller_get_data(instance->poller)); + const MfUltralightData* data = + nfc_device_get_data(instance->nfc_device, NfcProtocolMfUltralight); + if(instance->mf_ul_auth->type == MfUltralightAuthTypeXiaomi) { + if(mf_ultralight_generate_xiaomi_pass( + instance->mf_ul_auth, + data->iso14443_3a_data->uid, + data->iso14443_3a_data->uid_len)) { + mf_ultralight_event->data->auth_context.skip_auth = false; + } + } else if(instance->mf_ul_auth->type == MfUltralightAuthTypeAmiibo) { + if(mf_ultralight_generate_amiibo_pass( + instance->mf_ul_auth, + data->iso14443_3a_data->uid, + data->iso14443_3a_data->uid_len)) { + mf_ultralight_event->data->auth_context.skip_auth = false; + } + } else if( + instance->mf_ul_auth->type == MfUltralightAuthTypeManual || + instance->mf_ul_auth->type == MfUltralightAuthTypeReader) { + mf_ultralight_event->data->auth_context.skip_auth = false; + } else { + mf_ultralight_event->data->auth_context.skip_auth = true; + } + if(!mf_ultralight_event->data->auth_context.skip_auth) { + mf_ultralight_event->data->auth_context.password = instance->mf_ul_auth->password; + } + } else if(mf_ultralight_event->type == MfUltralightPollerEventTypeAuthSuccess) { + instance->mf_ul_auth->pack = mf_ultralight_event->data->auth_context.pack; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_mf_ultralight(NfcApp* instance) { + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_mf_ultralight, instance); +} + +static void nfc_scene_read_and_saved_menu_on_enter_mf_ultralight(NfcApp* instance) { + Submenu* submenu = instance->submenu; + + const MfUltralightData* data = + nfc_device_get_data(instance->nfc_device, NfcProtocolMfUltralight); + + if(!mf_ultralight_is_all_data_read(data)) { + submenu_add_item( + submenu, + "Unlock", + SubmenuIndexUnlock, + nfc_protocol_support_common_submenu_callback, + instance); + } +} + +static void nfc_scene_read_success_on_enter_mf_ultralight(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const MfUltralightData* data = nfc_device_get_data(device, NfcProtocolMfUltralight); + + FuriString* temp_str = furi_string_alloc(); + + bool unlocked = + scene_manager_has_previous_scene(instance->scene_manager, NfcSceneMfUltralightUnlockWarn); + if(unlocked) { + nfc_render_mf_ultralight_pwd_pack(data, temp_str); + } else { + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + + nfc_render_mf_ultralight_info(data, NfcProtocolFormatTypeShort, temp_str); + } + + mf_ultralight_auth_reset(instance->mf_ul_auth); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static void nfc_scene_emulate_on_enter_mf_ultralight(NfcApp* instance) { + const MfUltralightData* data = + nfc_device_get_data(instance->nfc_device, NfcProtocolMfUltralight); + instance->listener = nfc_listener_alloc(instance->nfc, NfcProtocolMfUltralight, data); + nfc_listener_start(instance->listener, NULL, NULL); +} + +static bool + nfc_scene_read_and_saved_menu_on_event_mf_ultralight(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexUnlock) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfUltralightUnlockMenu); + return true; + } + return false; +} + +const NfcProtocolSupportBase nfc_protocol_support_mf_ultralight = { + .features = NfcProtocolFeatureEmulateFull | NfcProtocolFeatureMoreInfo, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_mf_ultralight, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_more_info = + { + .on_enter = nfc_scene_more_info_on_enter_mf_ultralight, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_mf_ultralight, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_scene_read_and_saved_menu_on_enter_mf_ultralight, + .on_event = nfc_scene_read_and_saved_menu_on_event_mf_ultralight, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_mf_ultralight, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_scene_read_and_saved_menu_on_enter_mf_ultralight, + .on_event = nfc_scene_read_and_saved_menu_on_event_mf_ultralight, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_scene_emulate_on_enter_mf_ultralight, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight.h b/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight.h new file mode 100644 index 000000000..83e58732e --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_mf_ultralight; diff --git a/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight_render.c b/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight_render.c new file mode 100644 index 000000000..5296f4807 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight_render.c @@ -0,0 +1,45 @@ +#include "mf_ultralight_render.h" + +#include "../iso14443_3a/iso14443_3a_render.h" + +static void nfc_render_mf_ultralight_pages_count(const MfUltralightData* data, FuriString* str) { + furi_string_cat_printf(str, "\nPages Read: %u/%u", data->pages_read, data->pages_total); + if(data->pages_read != data->pages_total) { + furi_string_cat_printf(str, "\nPassword-protected pages!"); + } +} + +void nfc_render_mf_ultralight_pwd_pack(const MfUltralightData* data, FuriString* str) { + bool all_pages = mf_ultralight_is_all_data_read(data); + furi_string_cat_printf(str, "\e#%s pages unlocked!", all_pages ? "All" : "Not all"); + + MfUltralightConfigPages* config; + mf_ultralight_get_config_page(data, &config); + + furi_string_cat_printf(str, "\nPassword: "); + nfc_render_iso14443_3a_format_bytes( + str, config->password.data, MF_ULTRALIGHT_AUTH_PASSWORD_SIZE); + + furi_string_cat_printf(str, "\nPACK: "); + nfc_render_iso14443_3a_format_bytes(str, config->pack.data, MF_ULTRALIGHT_AUTH_PACK_SIZE); + + nfc_render_mf_ultralight_pages_count(data, str); +} + +void nfc_render_mf_ultralight_info( + const MfUltralightData* data, + NfcProtocolFormatType format_type, + FuriString* str) { + nfc_render_iso14443_3a_info(data->iso14443_3a_data, format_type, str); + + nfc_render_mf_ultralight_pages_count(data, str); +} + +void nfc_render_mf_ultralight_dump(const MfUltralightData* data, FuriString* str) { + for(size_t i = 0; i < data->pages_read; i++) { + const uint8_t* page_data = data->page[i].data; + for(size_t j = 0; j < MF_ULTRALIGHT_PAGE_SIZE; j += 2) { + furi_string_cat_printf(str, "%02X%02X ", page_data[j], page_data[j + 1]); + } + } +} diff --git a/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight_render.h b/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight_render.h new file mode 100644 index 000000000..5b15bb591 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/mf_ultralight/mf_ultralight_render.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_mf_ultralight_info( + const MfUltralightData* data, + NfcProtocolFormatType format_type, + FuriString* str); + +void nfc_render_mf_ultralight_dump(const MfUltralightData* data, FuriString* str); + +void nfc_render_mf_ultralight_pwd_pack(const MfUltralightData* data, FuriString* str); \ No newline at end of file diff --git a/applications/main/nfc/helpers/protocol_support/nfc_protocol_support.c b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support.c new file mode 100644 index 000000000..87fbe9f08 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support.c @@ -0,0 +1,788 @@ +/** + * @file nfc_protocol_support.c + * @brief Common implementation of application-level protocol support. + * + * @see nfc_protocol_support_base.h + * @see nfc_protocol_support_common.h + */ +#include "nfc_protocol_support.h" + +#include "nfc/nfc_app_i.h" +#include "nfc/helpers/nfc_supported_cards.h" + +#include "nfc_protocol_support_defs.h" +#include "nfc_protocol_support_gui_common.h" + +/** + * @brief Common scene entry handler. + * + * @param[in,out] instance pointer to the NFC application instance. + */ +typedef void (*NfcProtocolSupportCommonOnEnter)(NfcApp* instance); + +/** + * @brief Common scene custom event handler. + * + * @param[in,out] instance pointer to the NFC application instance. + * @param[in] event custom event to be handled. + * @returns true if the event was handled, false otherwise. + */ +typedef bool (*NfcProtocolSupportCommonOnEvent)(NfcApp* instance, SceneManagerEvent event); + +/** + * @brief Common scene exit handler. + * + * @param[in,out] instance pointer to the NFC application instance. + */ +typedef void (*NfcProtocolSupportCommonOnExit)(NfcApp* instance); + +/** + * @brief Structure containing common scene handler pointers. + */ +typedef struct { + NfcProtocolSupportCommonOnEnter on_enter; /**< Pointer to the on_enter() function. */ + NfcProtocolSupportCommonOnEvent on_event; /**< Pointer to the on_event() function. */ + NfcProtocolSupportCommonOnExit on_exit; /**< Pointer to the on_exit() function. */ +} NfcProtocolSupportCommonSceneBase; + +static const NfcProtocolSupportCommonSceneBase nfc_protocol_support_scenes[]; + +// Interface functions +void nfc_protocol_support_on_enter(NfcProtocolSupportScene scene, void* context) { + furi_assert(scene < NfcProtocolSupportSceneCount); + furi_assert(context); + + NfcApp* instance = context; + nfc_protocol_support_scenes[scene].on_enter(instance); +} + +bool nfc_protocol_support_on_event( + NfcProtocolSupportScene scene, + void* context, + SceneManagerEvent event) { + furi_assert(scene < NfcProtocolSupportSceneCount); + furi_assert(context); + + NfcApp* instance = context; + return nfc_protocol_support_scenes[scene].on_event(instance, event); +} + +void nfc_protocol_support_on_exit(NfcProtocolSupportScene scene, void* context) { + furi_assert(scene < NfcProtocolSupportSceneCount); + furi_assert(context); + + NfcApp* instance = context; + nfc_protocol_support_scenes[scene].on_exit(instance); +} + +static bool nfc_protocol_support_has_feature(NfcProtocol protocol, NfcProtocolFeature feature) { + return nfc_protocol_support[protocol]->features & feature; +} + +// Common scene handlers +// SceneInfo +static void nfc_protocol_support_scene_info_on_enter(NfcApp* instance) { + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + nfc_protocol_support[protocol]->scene_info.on_enter(instance); + + if(nfc_protocol_support_has_feature(protocol, NfcProtocolFeatureMoreInfo)) { + widget_add_button_element( + instance->widget, + GuiButtonTypeRight, + "More", + nfc_protocol_support_common_widget_callback, + instance); + } + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); +} + +static bool nfc_protocol_support_scene_info_on_event(NfcApp* instance, SceneManagerEvent event) { + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == GuiButtonTypeRight) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMoreInfo); + consumed = true; + } + } else if(event.type == SceneManagerEventTypeBack) { + // If the card could not be parsed, return to the respective menu + if(!scene_manager_get_scene_state(instance->scene_manager, NfcSceneSupportedCard)) { + const uint32_t scenes[] = {NfcSceneSavedMenu, NfcSceneReadMenu}; + scene_manager_search_and_switch_to_previous_scene_one_of( + instance->scene_manager, scenes, COUNT_OF(scenes)); + consumed = true; + } + } + + return consumed; +} + +static void nfc_protocol_support_scene_info_on_exit(NfcApp* instance) { + widget_reset(instance->widget); +} + +// SceneMoreInfo +static void nfc_protocol_support_scene_more_info_on_enter(NfcApp* instance) { + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + nfc_protocol_support[protocol]->scene_more_info.on_enter(instance); +} + +static bool + nfc_protocol_support_scene_more_info_on_event(NfcApp* instance, SceneManagerEvent event) { + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + consumed = nfc_protocol_support[protocol]->scene_more_info.on_event(instance, event.event); + } + + return consumed; +} + +static void nfc_protocol_support_scene_more_info_on_exit(NfcApp* instance) { + text_box_reset(instance->text_box); + furi_string_reset(instance->text_box_store); +} + +// SceneRead +static void nfc_protocol_support_scene_read_on_enter(NfcApp* instance) { + popup_set_header( + instance->popup, "Reading card\nDon't move...", 85, 24, AlignCenter, AlignTop); + popup_set_icon(instance->popup, 12, 23, &A_Loading_24); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewPopup); + + const NfcProtocol protocol = + instance->protocols_detected[instance->protocols_detected_selected_idx]; + instance->poller = nfc_poller_alloc(instance->nfc, protocol); + + // Start poller with the appropriate callback + nfc_protocol_support[protocol]->scene_read.on_enter(instance); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewPopup); + + nfc_blink_detect_start(instance); +} + +static bool nfc_protocol_support_scene_read_on_event(NfcApp* instance, SceneManagerEvent event) { + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventPollerSuccess) { + nfc_poller_stop(instance->poller); + nfc_poller_free(instance->poller); + notification_message(instance->notifications, &sequence_success); + scene_manager_next_scene(instance->scene_manager, NfcSceneReadSuccess); + dolphin_deed(DolphinDeedNfcReadSuccess); + consumed = true; + } else if(event.event == NfcCustomEventPollerIncomplete) { + nfc_poller_stop(instance->poller); + nfc_poller_free(instance->poller); + bool card_read = nfc_supported_cards_read(instance->nfc_device, instance->nfc); + if(card_read) { + notification_message(instance->notifications, &sequence_success); + scene_manager_next_scene(instance->scene_manager, NfcSceneReadSuccess); + dolphin_deed(DolphinDeedNfcReadSuccess); + consumed = true; + } else { + const NfcProtocol protocol = + instance->protocols_detected[instance->protocols_detected_selected_idx]; + consumed = + nfc_protocol_support[protocol]->scene_read.on_event(instance, event.event); + } + } else if(event.event == NfcCustomEventPollerFailure) { + nfc_poller_stop(instance->poller); + nfc_poller_free(instance->poller); + if(scene_manager_has_previous_scene(instance->scene_manager, NfcSceneDetect)) { + scene_manager_search_and_switch_to_previous_scene( + instance->scene_manager, NfcSceneDetect); + } + consumed = true; + } + } else if(event.type == SceneManagerEventTypeBack) { + nfc_poller_stop(instance->poller); + nfc_poller_free(instance->poller); + static const uint32_t possible_scenes[] = {NfcSceneSelectProtocol, NfcSceneStart}; + scene_manager_search_and_switch_to_previous_scene_one_of( + instance->scene_manager, possible_scenes, COUNT_OF(possible_scenes)); + consumed = true; + } + + return consumed; +} + +static void nfc_protocol_support_scene_read_on_exit(NfcApp* instance) { + popup_reset(instance->popup); + + nfc_blink_stop(instance); +} + +// SceneReadMenu +static void nfc_protocol_support_scene_read_menu_on_enter(NfcApp* instance) { + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + + Submenu* submenu = instance->submenu; + + submenu_add_item( + submenu, + "Save", + SubmenuIndexCommonSave, + nfc_protocol_support_common_submenu_callback, + instance); + + if(nfc_protocol_support_has_feature(protocol, NfcProtocolFeatureEmulateUid)) { + submenu_add_item( + submenu, + "Emulate UID", + SubmenuIndexCommonEmulate, + nfc_protocol_support_common_submenu_callback, + instance); + + } else if(nfc_protocol_support_has_feature(protocol, NfcProtocolFeatureEmulateFull)) { + submenu_add_item( + submenu, + "Emulate", + SubmenuIndexCommonEmulate, + nfc_protocol_support_common_submenu_callback, + instance); + } + + nfc_protocol_support[protocol]->scene_read_menu.on_enter(instance); + + submenu_add_item( + submenu, + "Info", + SubmenuIndexCommonInfo, + nfc_protocol_support_common_submenu_callback, + instance); + + submenu_set_selected_item( + instance->submenu, + scene_manager_get_scene_state(instance->scene_manager, NfcSceneReadMenu)); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewMenu); +} + +static bool + nfc_protocol_support_scene_read_menu_on_event(NfcApp* instance, SceneManagerEvent event) { + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + scene_manager_set_scene_state(instance->scene_manager, NfcSceneReadMenu, event.event); + + if(event.event == SubmenuIndexCommonSave) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSaveName); + consumed = true; + } else if(event.event == SubmenuIndexCommonInfo) { + scene_manager_next_scene(instance->scene_manager, NfcSceneInfo); + consumed = true; + } else if(event.event == SubmenuIndexCommonEmulate) { + dolphin_deed(DolphinDeedNfcEmulate); + scene_manager_next_scene(instance->scene_manager, NfcSceneEmulate); + consumed = true; + } else { + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + consumed = + nfc_protocol_support[protocol]->scene_read_menu.on_event(instance, event.event); + } + + } else if(event.type == SceneManagerEventTypeBack) { + scene_manager_set_scene_state(instance->scene_manager, NfcSceneSavedMenu, 0); + } + + return consumed; +} + +// Same for read_menu and saved_menu +static void nfc_protocol_support_scene_read_saved_menu_on_exit(NfcApp* instance) { + submenu_reset(instance->submenu); +} + +// SceneReadSuccess +static void nfc_protocol_support_scene_read_success_on_enter(NfcApp* instance) { + Widget* widget = instance->widget; + + FuriString* temp_str = furi_string_alloc(); + if(nfc_supported_cards_parse(instance->nfc_device, temp_str)) { + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + } else { + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + nfc_protocol_support[protocol]->scene_read_success.on_enter(instance); + } + + furi_string_free(temp_str); + + widget_add_button_element( + widget, GuiButtonTypeLeft, "Retry", nfc_protocol_support_common_widget_callback, instance); + widget_add_button_element( + widget, GuiButtonTypeRight, "More", nfc_protocol_support_common_widget_callback, instance); + + notification_message_block(instance->notifications, &sequence_set_green_255); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); +} + +static bool + nfc_protocol_support_scene_read_success_on_event(NfcApp* instance, SceneManagerEvent event) { + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == GuiButtonTypeLeft) { + scene_manager_next_scene(instance->scene_manager, NfcSceneRetryConfirm); + consumed = true; + + } else if(event.event == GuiButtonTypeRight) { + scene_manager_next_scene(instance->scene_manager, NfcSceneReadMenu); + consumed = true; + } + + } else if(event.type == SceneManagerEventTypeBack) { + scene_manager_next_scene(instance->scene_manager, NfcSceneExitConfirm); + consumed = true; + } + + return consumed; +} + +static void nfc_protocol_support_scene_read_success_on_exit(NfcApp* instance) { + notification_message_block(instance->notifications, &sequence_reset_green); + widget_reset(instance->widget); +} + +// SceneSavedMenu +static void nfc_protocol_support_scene_saved_menu_on_enter(NfcApp* instance) { + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + + Submenu* submenu = instance->submenu; + + // Header submenu items + if(nfc_protocol_support_has_feature(protocol, NfcProtocolFeatureEmulateUid)) { + submenu_add_item( + submenu, + "Emulate UID", + SubmenuIndexCommonEmulate, + nfc_protocol_support_common_submenu_callback, + instance); + + } else if(nfc_protocol_support_has_feature(protocol, NfcProtocolFeatureEmulateFull)) { + submenu_add_item( + submenu, + "Emulate", + SubmenuIndexCommonEmulate, + nfc_protocol_support_common_submenu_callback, + instance); + } + + if(nfc_protocol_support_has_feature(protocol, NfcProtocolFeatureEditUid)) { + submenu_add_item( + submenu, + "Edit UID", + SubmenuIndexCommonEdit, + nfc_protocol_support_common_submenu_callback, + instance); + } + + // Protocol-dependent menu items + nfc_protocol_support[protocol]->scene_saved_menu.on_enter(instance); + + // Trailer submenu items + submenu_add_item( + submenu, + "Info", + SubmenuIndexCommonInfo, + nfc_protocol_support_common_submenu_callback, + instance); + submenu_add_item( + submenu, + "Rename", + SubmenuIndexCommonRename, + nfc_protocol_support_common_submenu_callback, + instance); + submenu_add_item( + submenu, + "Delete", + SubmenuIndexCommonDelete, + nfc_protocol_support_common_submenu_callback, + instance); + + if(nfc_has_shadow_file(instance)) { + submenu_add_item( + submenu, + "Restore Data Changes", + SubmenuIndexCommonRestore, + nfc_protocol_support_common_submenu_callback, + instance); + } + + submenu_set_selected_item( + instance->submenu, + scene_manager_get_scene_state(instance->scene_manager, NfcSceneSavedMenu)); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewMenu); +} + +static bool + nfc_protocol_support_scene_saved_menu_on_event(NfcApp* instance, SceneManagerEvent event) { + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + scene_manager_set_scene_state(instance->scene_manager, NfcSceneSavedMenu, event.event); + + if(event.event == SubmenuIndexCommonRestore) { + scene_manager_next_scene(instance->scene_manager, NfcSceneRestoreOriginalConfirm); + consumed = true; + } else if(event.event == SubmenuIndexCommonInfo) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSupportedCard); + consumed = true; + } else if(event.event == SubmenuIndexCommonRename) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSaveName); + consumed = true; + } else if(event.event == SubmenuIndexCommonDelete) { + scene_manager_next_scene(instance->scene_manager, NfcSceneDelete); + consumed = true; + } else if(event.event == SubmenuIndexCommonEmulate) { + const bool is_added = + scene_manager_has_previous_scene(instance->scene_manager, NfcSceneSetType); + dolphin_deed(is_added ? DolphinDeedNfcAddEmulate : DolphinDeedNfcEmulate); + scene_manager_next_scene(instance->scene_manager, NfcSceneEmulate); + consumed = true; + } else if(event.event == SubmenuIndexCommonEdit) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSetUid); + consumed = true; + } else { + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + consumed = + nfc_protocol_support[protocol]->scene_saved_menu.on_event(instance, event.event); + } + + } else if(event.type == SceneManagerEventTypeBack) { + scene_manager_set_scene_state(instance->scene_manager, NfcSceneSavedMenu, 0); + } + + return consumed; +} + +// SceneSaveName + +static void nfc_protocol_support_scene_save_name_on_enter(NfcApp* instance) { + FuriString* folder_path = furi_string_alloc(); + TextInput* text_input = instance->text_input; + + bool name_is_empty = furi_string_empty(instance->file_name); + if(name_is_empty) { + furi_string_set(instance->file_path, NFC_APP_FOLDER); + name_generator_make_auto( + instance->text_store, NFC_TEXT_STORE_SIZE, NFC_APP_FILENAME_PREFIX); + furi_string_set(folder_path, NFC_APP_FOLDER); + } else { + nfc_text_store_set(instance, "%s", furi_string_get_cstr(instance->file_name)); + path_extract_dirname(furi_string_get_cstr(instance->file_path), folder_path); + } + + text_input_set_header_text(text_input, "Name the card"); + text_input_set_result_callback( + text_input, + nfc_protocol_support_common_text_input_done_callback, + instance, + instance->text_store, + NFC_NAME_SIZE, + name_is_empty); + + ValidatorIsFile* validator_is_file = validator_is_file_alloc_init( + furi_string_get_cstr(folder_path), + NFC_APP_EXTENSION, + furi_string_get_cstr(instance->file_name)); + text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); + + furi_string_free(folder_path); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewTextInput); +} + +static bool + nfc_protocol_support_scene_save_name_on_event(NfcApp* instance, SceneManagerEvent event) { + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventTextInputDone) { + if(!furi_string_empty(instance->file_name)) { + nfc_delete(instance); + } + furi_string_set(instance->file_name, instance->text_store); + + if(nfc_save(instance)) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSaveSuccess); + dolphin_deed( + scene_manager_has_previous_scene(instance->scene_manager, NfcSceneSetType) ? + DolphinDeedNfcAddSave : + DolphinDeedNfcSave); + const NfcProtocol protocol = + instance->protocols_detected[instance->protocols_detected_selected_idx]; + consumed = nfc_protocol_support[protocol]->scene_save_name.on_event( + instance, event.event); + } else { + consumed = scene_manager_search_and_switch_to_previous_scene( + instance->scene_manager, NfcSceneStart); + } + } + } + + return consumed; +} + +static void nfc_protocol_support_scene_save_name_on_exit(NfcApp* instance) { + void* validator_context = text_input_get_validator_callback_context(instance->text_input); + text_input_set_validator(instance->text_input, NULL, NULL); + validator_is_file_free(validator_context); + + text_input_reset(instance->text_input); +} + +// SceneEmulate +/** + * @brief Current view displayed on the emulation scene. + * + * The emulation scehe has two states: the default one showing information about + * the card being emulated, and the logs which show the raw data received from the reader. + * + * The user has the ability to switch betweeen these two scenes, however the prompt to switch is + * only shown after some information had appered in the log view. + */ +enum { + NfcSceneEmulateStateWidget, /**< Widget view is displayed. */ + NfcSceneEmulateStateTextBox, /**< TextBox view is displayed. */ +}; + +static void nfc_protocol_support_scene_emulate_on_enter(NfcApp* instance) { + Widget* widget = instance->widget; + TextBox* text_box = instance->text_box; + + FuriString* temp_str = furi_string_alloc(); + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + + widget_add_icon_element(widget, 0, 3, &I_NFC_dolphin_emulation_47x61); + + if(nfc_protocol_support_has_feature(protocol, NfcProtocolFeatureEmulateUid)) { + widget_add_string_element( + widget, 90, 13, AlignCenter, AlignTop, FontPrimary, "Emulating UID"); + + size_t uid_len; + const uint8_t* uid = nfc_device_get_uid(instance->nfc_device, &uid_len); + + for(size_t i = 0; i < uid_len; ++i) { + furi_string_cat_printf(temp_str, "%02X ", uid[i]); + } + + furi_string_trim(temp_str); + + } else { + widget_add_string_element(widget, 90, 13, AlignCenter, AlignTop, FontPrimary, "Emulating"); + furi_string_set( + temp_str, nfc_device_get_name(instance->nfc_device, NfcDeviceNameTypeFull)); + } + + widget_add_text_box_element( + widget, 56, 28, 71, 25, AlignCenter, AlignTop, furi_string_get_cstr(temp_str), false); + + furi_string_free(temp_str); + + text_box_set_font(text_box, TextBoxFontHex); + text_box_set_focus(text_box, TextBoxFocusEnd); + furi_string_reset(instance->text_box_store); + + // instance->listener is allocated in the respective on_enter() handler + nfc_protocol_support[protocol]->scene_emulate.on_enter(instance); + + scene_manager_set_scene_state( + instance->scene_manager, NfcSceneEmulate, NfcSceneEmulateStateWidget); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); + nfc_blink_emulate_start(instance); +} + +static bool + nfc_protocol_support_scene_emulate_on_event(NfcApp* instance, SceneManagerEvent event) { + bool consumed = false; + + const uint32_t state = scene_manager_get_scene_state(instance->scene_manager, NfcSceneEmulate); + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventListenerUpdate) { + // Add data button to widget if data is received for the first time + if(furi_string_size(instance->text_box_store)) { + widget_add_button_element( + instance->widget, + GuiButtonTypeCenter, + "Log", + nfc_protocol_support_common_widget_callback, + instance); + } + // Update TextBox data + text_box_set_text(instance->text_box, furi_string_get_cstr(instance->text_box_store)); + consumed = true; + } else if(event.event == GuiButtonTypeCenter) { + if(state == NfcSceneEmulateStateWidget) { + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewTextBox); + scene_manager_set_scene_state( + instance->scene_manager, NfcSceneEmulate, NfcSceneEmulateStateTextBox); + consumed = true; + } + } + } else if(event.type == SceneManagerEventTypeBack) { + if(state == NfcSceneEmulateStateTextBox) { + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); + scene_manager_set_scene_state( + instance->scene_manager, NfcSceneEmulate, NfcSceneEmulateStateWidget); + consumed = true; + } + } + + return consumed; +} + +static void nfc_protocol_support_scene_emulate_stop_listener(NfcApp* instance) { + nfc_listener_stop(instance->listener); + + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + + if(protocol == nfc_listener_get_protocol(instance->listener)) { + const NfcDeviceData* data = nfc_listener_get_data(instance->listener, protocol); + + if(!nfc_device_is_equal_data(instance->nfc_device, protocol, data)) { + nfc_device_set_data(instance->nfc_device, protocol, data); + nfc_save_shadow_file(instance); + } + } + + nfc_listener_free(instance->listener); +} + +static void nfc_protocol_support_scene_emulate_on_exit(NfcApp* instance) { + nfc_protocol_support_scene_emulate_stop_listener(instance); + + // Clear view + widget_reset(instance->widget); + text_box_reset(instance->text_box); + furi_string_reset(instance->text_box_store); + + nfc_blink_stop(instance); +} + +static void nfc_protocol_support_scene_rpc_on_enter(NfcApp* instance) { + UNUSED(instance); +} + +static void nfc_protocol_support_scene_rpc_setup_ui_and_emulate(NfcApp* instance) { + nfc_text_store_set(instance, "emulating\n%s", furi_string_get_cstr(instance->file_name)); + + popup_set_header(instance->popup, "NFC", 89, 42, AlignCenter, AlignBottom); + popup_set_text(instance->popup, instance->text_store, 89, 44, AlignCenter, AlignTop); + popup_set_icon(instance->popup, 0, 12, &I_RFIDDolphinSend_97x61); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewPopup); + + notification_message(instance->notifications, &sequence_display_backlight_on); + nfc_blink_emulate_start(instance); + + const NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + nfc_protocol_support[protocol]->scene_emulate.on_enter(instance); + + instance->rpc_state = NfcRpcStateEmulating; +} + +static bool nfc_protocol_support_scene_rpc_on_event(NfcApp* instance, SceneManagerEvent event) { + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventRpcLoadFile) { + bool success = false; + if(instance->rpc_state == NfcRpcStateIdle) { + if(nfc_load_file(instance, instance->file_path, false)) { + nfc_protocol_support_scene_rpc_setup_ui_and_emulate(instance); + success = true; + } + } + rpc_system_app_confirm(instance->rpc_ctx, success); + } else if(event.event == NfcCustomEventRpcExit) { + rpc_system_app_confirm(instance->rpc_ctx, true); + scene_manager_stop(instance->scene_manager); + view_dispatcher_stop(instance->view_dispatcher); + } else if(event.event == NfcCustomEventRpcSessionClose) { + scene_manager_stop(instance->scene_manager); + view_dispatcher_stop(instance->view_dispatcher); + } + consumed = true; + } + + return consumed; +} + +static void nfc_protocol_support_scene_rpc_on_exit(NfcApp* instance) { + if(instance->rpc_state == NfcRpcStateEmulating) { + nfc_protocol_support_scene_emulate_stop_listener(instance); + } + + popup_reset(instance->popup); + text_box_reset(instance->text_box); + furi_string_reset(instance->text_box_store); + + nfc_blink_stop(instance); +} + +static const NfcProtocolSupportCommonSceneBase + nfc_protocol_support_scenes[NfcProtocolSupportSceneCount] = { + [NfcProtocolSupportSceneInfo] = + { + .on_enter = nfc_protocol_support_scene_info_on_enter, + .on_event = nfc_protocol_support_scene_info_on_event, + .on_exit = nfc_protocol_support_scene_info_on_exit, + }, + [NfcProtocolSupportSceneMoreInfo] = + { + .on_enter = nfc_protocol_support_scene_more_info_on_enter, + .on_event = nfc_protocol_support_scene_more_info_on_event, + .on_exit = nfc_protocol_support_scene_more_info_on_exit, + }, + [NfcProtocolSupportSceneRead] = + { + .on_enter = nfc_protocol_support_scene_read_on_enter, + .on_event = nfc_protocol_support_scene_read_on_event, + .on_exit = nfc_protocol_support_scene_read_on_exit, + }, + [NfcProtocolSupportSceneReadMenu] = + { + .on_enter = nfc_protocol_support_scene_read_menu_on_enter, + .on_event = nfc_protocol_support_scene_read_menu_on_event, + .on_exit = nfc_protocol_support_scene_read_saved_menu_on_exit, + }, + [NfcProtocolSupportSceneReadSuccess] = + { + .on_enter = nfc_protocol_support_scene_read_success_on_enter, + .on_event = nfc_protocol_support_scene_read_success_on_event, + .on_exit = nfc_protocol_support_scene_read_success_on_exit, + }, + [NfcProtocolSupportSceneSavedMenu] = + { + .on_enter = nfc_protocol_support_scene_saved_menu_on_enter, + .on_event = nfc_protocol_support_scene_saved_menu_on_event, + .on_exit = nfc_protocol_support_scene_read_saved_menu_on_exit, + }, + [NfcProtocolSupportSceneSaveName] = + { + .on_enter = nfc_protocol_support_scene_save_name_on_enter, + .on_event = nfc_protocol_support_scene_save_name_on_event, + .on_exit = nfc_protocol_support_scene_save_name_on_exit, + }, + [NfcProtocolSupportSceneEmulate] = + { + .on_enter = nfc_protocol_support_scene_emulate_on_enter, + .on_event = nfc_protocol_support_scene_emulate_on_event, + .on_exit = nfc_protocol_support_scene_emulate_on_exit, + }, + [NfcProtocolSupportSceneRpc] = + { + .on_enter = nfc_protocol_support_scene_rpc_on_enter, + .on_event = nfc_protocol_support_scene_rpc_on_event, + .on_exit = nfc_protocol_support_scene_rpc_on_exit, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/nfc_protocol_support.h b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support.h new file mode 100644 index 000000000..b6bfde45c --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support.h @@ -0,0 +1,113 @@ +/** + * @file nfc_protocol_support.h + * @brief Interface for application-level protocol support. + * + * NFC protocol support helper abstracts common scenes with a single interface + * and lets each protocol decide on concrete implementation. + * + * # Integrating a new protocol into the application + * + * Most of the scenes in the NFC application work through abstract APIs, so they do not need + * protocol-specific versions of themselves. However, when such a situation + * occurs, the protocol support helper provides another level of abstraction to hide + * the protocol-specific details and isolate them to separate modules. + * + * @see nfc_protocol.h for more information on adding library protocols. + * + * The steps for adding support for a library protocol are described below. + * + * ## 1. Create the files + * + * ### 1.1 Recommended file structure + * + * The recommended file structure for a protocol support is as follows: + * + * ```text + * protocol_support + * | + * +- protocol_name + * | + * +- protocol_name.h + * | + * +- protocol_name.c + * | + * +- protocol_name_render.h + * | + * +- protocol_name_render.c + * | + * ``` + * ### 1.2 File structure explanation + * + * | Filename | Explanation | + * |:-----------------------|:------------| + * | protocol_name.h | Interface structure declaration used in `nfc_protocol_support_defs.c`. | + * | protocol_name.c | Protocol-specific scene implemenatations and definitions. | + * | protocol_name_render.h | Protocol-specific rendering (formatting) functions. Used for converting protocol data into textual descriptions. | + * | protocol_name_render.c | Implementations for functions declared in `protocol_name_render.h`.| + * + * ## 2. Implement the code + * + * ### 2.1 Features + * + * Decide what features the protocol will be providing. The features can be combined using bitwise OR (`"|"`). + * This choice influences which scenes will have to be implemented in step 2.2. + * + * @see NfcProtocolFeature for the enumeration of possible features to implement. + * + * ### 2.2 Scenes + * + * If a particular scene is not implemented, its empty placeholder from nfc_protocol_support_gui_common.h must be used instead. + * + * @see nfc_protocol_support_common.h for the enumeration of all scenes that can be implemented. + * @see nfc_protocol_support_base.h for the scene implementation details. + * + * ### 2.3. Registering the protocol support + * + * After completing the protocol support, it must be registered within the application in order for it to be usable. + * + * In nfc_protocol_support_defs.c, include the `protocol_name.h` file and add a new entry in the `nfc_protocol_support[]` + * array under the appropriate index. + * + * ## Done! + * + * @note It will not always be possible to abstract all of the protocol's functionality using the protocol support helper. + * In such cases, creating separate protocol-specific scenes is okay (as an example, note the `nfc/scenes/nfc_scene_mf_classic_*` scenes which didn't fit this paradigm). + */ +#pragma once + +#include + +#include "nfc_protocol_support_common.h" + +/** + * @brief Abstract interface for on_enter() scene handler. + * + * Is to be called whenever a scene is entered to. + * + * @param[in] scene identifier of the scene associated with the handler. + * @param[in,out] context pointer to a user-specified context (will be passed to concrete handler). + */ +void nfc_protocol_support_on_enter(NfcProtocolSupportScene scene, void* context); + +/** + * @brief Abstract interface for on_event() scene handler. + * + * @param[in] scene identifier of the scene associated with the handler. + * @param[in,out] context pointer to a user-specified context (will be passed to concrete handler). + * @param[in] event SceneManager event to be handled by the scene. + * @returns true if the event was consumed, false otherwise. + */ +bool nfc_protocol_support_on_event( + NfcProtocolSupportScene scene, + void* context, + SceneManagerEvent event); + +/** + * @brief Abstract interface for on_exit() scene handler. + * + * Is to be called whenever a scene is exited from. + * + * @param[in] scene identifier of the scene associated with the handler. + * @param[in,out] context pointer to a user-specified context (will be passed to concrete handler). + */ +void nfc_protocol_support_on_exit(NfcProtocolSupportScene scene, void* context); diff --git a/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_base.h b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_base.h new file mode 100644 index 000000000..69a6d34d2 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_base.h @@ -0,0 +1,116 @@ +/** + * @file nfc_protocol_support_base.h + * @brief Abstract interface for application-level protocol support. + */ +#pragma once + +#include + +#include "../../nfc_app.h" + +/** + * @brief Scene entry handler. + * + * @param[in,out] instance pointer to the NFC application instance. + */ +typedef void (*NfcProtocolSupportOnEnter)(NfcApp* instance); + +/** + * @brief Scene event handler. + * + * @param[in,out] instance pointer to the NFC application instance. + * @param[in] event custom event that has occurred. + * @returns true if the event was handled, false otherwise. + */ +typedef bool (*NfcProtocolSupportOnEvent)(NfcApp* instance, uint32_t event); + +/** + * @brief Abstract scene interface. + * + * on_exit() handler is not implemented due to being redundant. + */ +typedef struct { + NfcProtocolSupportOnEnter on_enter; /**< Pointer to the on_enter() function. */ + NfcProtocolSupportOnEvent on_event; /**< Pointer to the on_event() function. */ +} NfcProtocolSupportSceneBase; + +/** + * @brief Abstract protocol support interface. + */ +typedef struct { + const uint32_t features; /**< Feature bitmask supported by the protocol. */ + + /** + * @brief Handlers for protocol-specific info scene. + * + * This scene displays general information about a saved or recently read card. + * It may include a button that will lead to more information being shown. + */ + NfcProtocolSupportSceneBase scene_info; + + /** + * @brief Handlers for protocol-specific extended info scene. + * + * This scene shows more information about a saved or + * recently read card, such as memory dumps. + * + * It may include (a) button(s) and/or menu(s) that will lead to + * protocol-specific scenes not covered in this helper. + */ + NfcProtocolSupportSceneBase scene_more_info; + + /** + * @brief Handlers for protocol-specific read scene. + * + * This scene is activated when a read operation is in progress. + * It is responsible for creating a poller and for handling its events. + */ + NfcProtocolSupportSceneBase scene_read; + + /** + * @brief Handlers for protocol-specific read menu scene. + * + * This scene presents the user with options available for the + * recenly read card. Such options may include: + * * Saving + * * Getting information + * * Emulating etc. + */ + NfcProtocolSupportSceneBase scene_read_menu; + + /** + * @brief Handlers for protocol-specific read success scene. + * + * This scene is activated after a successful read operation. + * It is responsible for displaying a very short summary about + * the card that was just read. + */ + NfcProtocolSupportSceneBase scene_read_success; + + /** + * @brief Handlers for protocol-specific saved file menu scene. + * + * This scene presents the user with options available for a + * card loaded from file. Such options may include: + * * Renaming + * * Deleting + * * Getting information + * * Emulating etc. + */ + NfcProtocolSupportSceneBase scene_saved_menu; + + /** + * @brief Handlers for protocol-specific name entry scene. + * + * This scene is used to enter a file name when saving or renaming a file. + */ + NfcProtocolSupportSceneBase scene_save_name; + + /** + * @brief Handlers for protocol-specific emulate scene. + * + * This scene is activated when an emulation operation is in progress. + * It is responsible for creating a listener and for handling its events. + */ + NfcProtocolSupportSceneBase scene_emulate; +} NfcProtocolSupportBase; diff --git a/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_common.h b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_common.h new file mode 100644 index 000000000..6e3214106 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_common.h @@ -0,0 +1,36 @@ +/** + * @file nfc_protocol_support_common.h + * @brief Common application-level protocol support definitions. + */ +#pragma once + +/** + * @brief Enumeration of protocol features. + */ +typedef enum { + NfcProtocolFeatureNone = 0, /**< No features are supported. */ + NfcProtocolFeatureEmulateUid = 1UL << 0, /**< Partial emulation is supported. */ + NfcProtocolFeatureEmulateFull = 1UL << 1, /**< Complete emulation is supported. */ + NfcProtocolFeatureEditUid = 1UL << 2, /**< UID editing is supported. */ + NfcProtocolFeatureMoreInfo = 1UL << 3, /**< More information is provided. */ +} NfcProtocolFeature; + +/** + * @brief Enumeration of protocol-aware scenes. + * + * These are the scenes that are common to all protocols, but require + * a protocol-specific implementation. + */ +typedef enum { + NfcProtocolSupportSceneInfo, /**< Display general card information. */ + NfcProtocolSupportSceneMoreInfo, /**< Display more card information. */ + NfcProtocolSupportSceneRead, /**< Shown when reading a card. */ + NfcProtocolSupportSceneReadMenu, /**< Menu with options available for the recently read card. */ + NfcProtocolSupportSceneReadSuccess, /**< Shown after having successfully read a card. */ + NfcProtocolSupportSceneSavedMenu, /**< Menu for the card that was loaded from file. */ + NfcProtocolSupportSceneSaveName, /**< Shown when saving or renaming a file. */ + NfcProtocolSupportSceneEmulate, /**< Shown when emulating a card. */ + NfcProtocolSupportSceneRpc, /**< Shown in remote-controlled (RPC) mode. */ + + NfcProtocolSupportSceneCount, /**< Special value equal to total scene count. Internal use. */ +} NfcProtocolSupportScene; diff --git a/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_defs.c b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_defs.c new file mode 100644 index 000000000..215ffc455 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_defs.c @@ -0,0 +1,45 @@ +/** + * @file nfc_protocol_support_defs.c + * @brief Application-level protocol support definitions. + * + * This file is to be modified whenever support for + * a new protocol is to be added. + */ +#include "nfc_protocol_support_base.h" + +#include + +#include "iso14443_3a/iso14443_3a.h" +#include "iso14443_3b/iso14443_3b.h" +#include "iso14443_4a/iso14443_4a.h" +#include "iso14443_4b/iso14443_4b.h" +#include "iso15693_3/iso15693_3.h" +#include "felica/felica.h" +#include "mf_ultralight/mf_ultralight.h" +#include "mf_classic/mf_classic.h" +#include "mf_desfire/mf_desfire.h" +#include "slix/slix.h" +#include "st25tb/st25tb.h" + +/** + * @brief Array of pointers to concrete protocol support implementations. + * + * When adding support for a new protocol, add it to the end of this array + * under its respective index. + * + * @see nfc_protocol.h + */ +const NfcProtocolSupportBase* nfc_protocol_support[NfcProtocolNum] = { + [NfcProtocolIso14443_3a] = &nfc_protocol_support_iso14443_3a, + [NfcProtocolIso14443_3b] = &nfc_protocol_support_iso14443_3b, + [NfcProtocolIso14443_4a] = &nfc_protocol_support_iso14443_4a, + [NfcProtocolIso14443_4b] = &nfc_protocol_support_iso14443_4b, + [NfcProtocolIso15693_3] = &nfc_protocol_support_iso15693_3, + [NfcProtocolFelica] = &nfc_protocol_support_felica, + [NfcProtocolMfUltralight] = &nfc_protocol_support_mf_ultralight, + [NfcProtocolMfClassic] = &nfc_protocol_support_mf_classic, + [NfcProtocolMfDesfire] = &nfc_protocol_support_mf_desfire, + [NfcProtocolSlix] = &nfc_protocol_support_slix, + [NfcProtocolSt25tb] = &nfc_protocol_support_st25tb, + /* Add new protocol support implementations here */ +}; diff --git a/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_defs.h b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_defs.h new file mode 100644 index 000000000..7a9d5b637 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_defs.h @@ -0,0 +1,12 @@ +/** + * @file nfc_protocol_support_defs.h + * @brief Application-level protocol support declarations. + */ +#pragma once + +#include "nfc_protocol_support_base.h" + +/** + * @brief Declaraion of array of pointers to protocol support implementations. + */ +extern const NfcProtocolSupportBase* nfc_protocol_support[]; diff --git a/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_gui_common.c b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_gui_common.c new file mode 100644 index 000000000..f3a855125 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_gui_common.c @@ -0,0 +1,42 @@ +#include "nfc_protocol_support_gui_common.h" + +#include "nfc/nfc_app_i.h" + +void nfc_protocol_support_common_submenu_callback(void* context, uint32_t index) { + furi_assert(context); + NfcApp* instance = context; + view_dispatcher_send_custom_event(instance->view_dispatcher, index); +} + +void nfc_protocol_support_common_widget_callback( + GuiButtonType result, + InputType type, + void* context) { + furi_assert(context); + NfcApp* instance = context; + if(type == InputTypeShort) { + view_dispatcher_send_custom_event(instance->view_dispatcher, result); + } +} + +void nfc_protocol_support_common_byte_input_done_callback(void* context) { + furi_assert(context); + NfcApp* instance = context; + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventByteInputDone); +} + +void nfc_protocol_support_common_text_input_done_callback(void* context) { + NfcApp* nfc = context; + + view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventTextInputDone); +} + +void nfc_protocol_support_common_on_enter_empty(NfcApp* instance) { + UNUSED(instance); +} + +bool nfc_protocol_support_common_on_event_empty(NfcApp* instance, uint32_t event) { + UNUSED(instance); + UNUSED(event); + return true; +} diff --git a/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_gui_common.h b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_gui_common.h new file mode 100644 index 000000000..40ba40c8e --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_gui_common.h @@ -0,0 +1,85 @@ +/** + * @file nfc_protocol_support_gui_common.h + * @brief Common GUI functions and definitions. + */ +#pragma once + +#include + +#include "nfc/nfc_app.h" + +/** + * @brief Common submenu indices. + */ +enum { + SubmenuIndexCommonSave, /**< Save menu option. */ + SubmenuIndexCommonEmulate, /**< Emulate menu option. */ + SubmenuIndexCommonEdit, /**< Edit menu option. */ + SubmenuIndexCommonInfo, /**< Info menu option. */ + SubmenuIndexCommonRename, /**< Rename menu option. */ + SubmenuIndexCommonDelete, /**< Delete menu option. */ + SubmenuIndexCommonRestore, /**< Restore menu option. */ + SubmenuIndexCommonMax, /**< Special value, internal use. */ +}; + +/** + * @brief Common submenu callback. + * + * Called each time the user presses on a selected submenu item. + * + * @param[in,out] context pointer to a user-defined context object. + * @param[in] index index of the item that was activated. + */ +void nfc_protocol_support_common_submenu_callback(void* context, uint32_t index); + +/** + * @brief Common widget callback. + * + * Called each time the user presses on a selected widget element. + * + * @param[in] result identifier of the activated button. + * @param[in] type type of press action. + * @param[in,out] context pointer to a user-defined context object. + */ +void nfc_protocol_support_common_widget_callback( + GuiButtonType result, + InputType type, + void* context); + +/** + * @brief Common byte input callback. + * + * Called each time the user accepts the byte input. + * + * @param[in,out] context pointer to a user-defined context object. + */ +void nfc_protocol_support_common_byte_input_done_callback(void* context); + +/** + * @brief Common text input callback. + * + * Called each time the user accepts the text input. + * + * @param[in,out] context pointer to a user-defined context object. + */ +void nfc_protocol_support_common_text_input_done_callback(void* context); + +/** + * @brief Empty on_enter() handler. + * + * Does nothing. + * + * @param[in] instance pointer to the NFC application instance. + */ +void nfc_protocol_support_common_on_enter_empty(NfcApp* instance); + +/** + * @brief Empty on_event() handler. + * + * Does nothing and returns true. + * + * @param[in] instance pointer to the NFC application instance. + * @param[in] event custom event type that has occurred. + * @returns always true. + */ +bool nfc_protocol_support_common_on_event_empty(NfcApp* instance, uint32_t event); diff --git a/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_render_common.h b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_render_common.h new file mode 100644 index 000000000..a2e82ea15 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/nfc_protocol_support_render_common.h @@ -0,0 +1,13 @@ +/** + * @file nfc_protocol_support_render_common.h + * @brief Common formatting-related defines. + */ +#pragma once + +/** + * @brief Displayed information verbosity level. + */ +typedef enum { + NfcProtocolFormatTypeShort, /**< Short format, terse info. */ + NfcProtocolFormatTypeFull, /**< Full format, verbose info. */ +} NfcProtocolFormatType; diff --git a/applications/main/nfc/helpers/protocol_support/slix/slix.c b/applications/main/nfc/helpers/protocol_support/slix/slix.c new file mode 100644 index 000000000..ad858a75f --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/slix/slix.c @@ -0,0 +1,141 @@ +#include "slix.h" +#include "slix_render.h" + +#include +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" + +static void nfc_scene_info_on_enter_slix(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const SlixData* data = nfc_device_get_data(device, NfcProtocolSlix); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_slix_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 64, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand nfc_scene_read_poller_callback_slix(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolSlix); + + NfcApp* instance = context; + const SlixPollerEvent* slix_event = event.event_data; + + if(slix_event->type == SlixPollerEventTypeReady) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolSlix, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_slix(NfcApp* instance) { + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_slix, instance); +} + +static void nfc_scene_read_success_on_enter_slix(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const SlixData* data = nfc_device_get_data(device, NfcProtocolSlix); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_slix_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand nfc_scene_emulate_listener_callback_slix(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolSlix); + furi_assert(event.event_data); + + NfcApp* nfc = context; + SlixListenerEvent* slix_event = event.event_data; + + if(slix_event->type == SlixListenerEventTypeCustomCommand) { + if(furi_string_size(nfc->text_box_store) < NFC_LOG_SIZE_MAX) { + furi_string_cat_printf(nfc->text_box_store, "R:"); + for(size_t i = 0; i < bit_buffer_get_size_bytes(slix_event->data->buffer); i++) { + furi_string_cat_printf( + nfc->text_box_store, + " %02X", + bit_buffer_get_byte(slix_event->data->buffer, i)); + } + furi_string_push_back(nfc->text_box_store, '\n'); + view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventListenerUpdate); + } + } + + return NfcCommandContinue; +} + +static void nfc_scene_emulate_on_enter_slix(NfcApp* instance) { + const SlixData* data = nfc_device_get_data(instance->nfc_device, NfcProtocolSlix); + + instance->listener = nfc_listener_alloc(instance->nfc, NfcProtocolSlix, data); + nfc_listener_start(instance->listener, nfc_scene_emulate_listener_callback_slix, instance); +} + +static bool nfc_scene_saved_menu_on_event_slix(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexCommonEdit) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSetUid); + return true; + } + + return false; +} + +const NfcProtocolSupportBase nfc_protocol_support_slix = { + .features = NfcProtocolFeatureEmulateFull, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_slix, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_slix, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_slix, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_scene_saved_menu_on_event_slix, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_scene_emulate_on_enter_slix, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/slix/slix.h b/applications/main/nfc/helpers/protocol_support/slix/slix.h new file mode 100644 index 000000000..9c7504eba --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/slix/slix.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_slix; diff --git a/applications/main/nfc/helpers/protocol_support/slix/slix_render.c b/applications/main/nfc/helpers/protocol_support/slix/slix_render.c new file mode 100644 index 000000000..80f953db9 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/slix/slix_render.c @@ -0,0 +1,74 @@ +#include "slix_render.h" + +#include "../iso15693_3/iso15693_3_render.h" + +void nfc_render_slix_info(const SlixData* data, NfcProtocolFormatType format_type, FuriString* str) { + nfc_render_iso15693_3_brief(slix_get_base_data(data), str); + + if(format_type != NfcProtocolFormatTypeFull) return; + const SlixType slix_type = slix_get_type(data); + + furi_string_cat(str, "\n\e#Passwords\n"); + + static const char* slix_password_names[] = { + "Read", + "Write", + "Privacy", + "Destroy", + "EAS/AFI", + }; + + for(uint32_t i = 0; i < SlixPasswordTypeCount; ++i) { + if(slix_type_supports_password(slix_type, i)) { + furi_string_cat_printf( + str, "%s : %08lX\n", slix_password_names[i], data->passwords[i]); + } + } + + furi_string_cat(str, "\e#Lock bits\n"); + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_EAS)) { + furi_string_cat_printf( + str, "EAS: %s locked\n", data->system_info.lock_bits.eas ? "" : "not"); + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_PROTECTION)) { + furi_string_cat_printf( + str, "PPL: %s locked\n", data->system_info.lock_bits.ppl ? "" : "not"); + + const SlixProtection protection = data->system_info.protection; + + furi_string_cat(str, "\e#Page protection\n"); + furi_string_cat_printf(str, "Pointer: H >= %02X\n", protection.pointer); + + const char* rh = (protection.condition & SLIX_PP_CONDITION_RH) ? "" : "un"; + const char* rl = (protection.condition & SLIX_PP_CONDITION_RL) ? "" : "un"; + + const char* wh = (protection.condition & SLIX_PP_CONDITION_WH) ? "" : "un"; + const char* wl = (protection.condition & SLIX_PP_CONDITION_WL) ? "" : "un"; + + furi_string_cat_printf(str, "R: H %sprotec. L %sprotec.\n", rh, rl); + furi_string_cat_printf(str, "W: H %sprotec. L %sprotec.\n", wh, wl); + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_PRIVACY)) { + furi_string_cat(str, "\e#Privacy\n"); + furi_string_cat_printf(str, "Privacy mode: %sabled\n", data->privacy ? "en" : "dis"); + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_SIGNATURE)) { + furi_string_cat(str, "\e#Signature\n"); + for(uint32_t i = 0; i < 4; ++i) { + furi_string_cat_printf(str, "%02X ", data->signature[i]); + } + + furi_string_cat(str, "[ ... ]"); + + for(uint32_t i = 0; i < 3; ++i) { + furi_string_cat_printf(str, " %02X", data->signature[sizeof(SlixSignature) - i - 1]); + } + } + + furi_string_cat(str, "\n\e#ISO15693-3 data"); + nfc_render_iso15693_3_extra(slix_get_base_data(data), str); +} diff --git a/applications/main/nfc/helpers/protocol_support/slix/slix_render.h b/applications/main/nfc/helpers/protocol_support/slix/slix_render.h new file mode 100644 index 000000000..98ae6dc97 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/slix/slix_render.h @@ -0,0 +1,7 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_slix_info(const SlixData* data, NfcProtocolFormatType format_type, FuriString* str); diff --git a/applications/main/nfc/helpers/protocol_support/st25tb/st25tb.c b/applications/main/nfc/helpers/protocol_support/st25tb/st25tb.c new file mode 100644 index 000000000..32b2f4775 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/st25tb/st25tb.c @@ -0,0 +1,108 @@ +#include "st25tb.h" +#include "st25tb_render.h" + +#include + +#include "nfc/nfc_app_i.h" + +#include "../nfc_protocol_support_common.h" +#include "../nfc_protocol_support_gui_common.h" + +static void nfc_scene_info_on_enter_st25tb(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const St25tbData* data = nfc_device_get_data(device, NfcProtocolSt25tb); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_st25tb_info(data, NfcProtocolFormatTypeFull, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 64, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static NfcCommand nfc_scene_read_poller_callback_st25tb(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolSt25tb); + + NfcApp* instance = context; + const St25tbPollerEvent* st25tb_event = event.event_data; + + if(st25tb_event->type == St25tbPollerEventTypeReady) { + nfc_device_set_data( + instance->nfc_device, NfcProtocolSt25tb, nfc_poller_get_data(instance->poller)); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + return NfcCommandStop; + } + + return NfcCommandContinue; +} + +static void nfc_scene_read_on_enter_st25tb(NfcApp* instance) { + nfc_poller_start(instance->poller, nfc_scene_read_poller_callback_st25tb, instance); +} + +static void nfc_scene_read_success_on_enter_st25tb(NfcApp* instance) { + const NfcDevice* device = instance->nfc_device; + const St25tbData* data = nfc_device_get_data(device, NfcProtocolSt25tb); + + FuriString* temp_str = furi_string_alloc(); + furi_string_cat_printf( + temp_str, "\e#%s\n", nfc_device_get_name(device, NfcDeviceNameTypeFull)); + nfc_render_st25tb_info(data, NfcProtocolFormatTypeShort, temp_str); + + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + + furi_string_free(temp_str); +} + +static bool nfc_scene_saved_menu_on_event_st25tb(NfcApp* instance, uint32_t event) { + if(event == SubmenuIndexCommonEdit) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSetUid); + return true; + } + + return false; +} + +const NfcProtocolSupportBase nfc_protocol_support_st25tb = { + .features = NfcProtocolFeatureNone, + + .scene_info = + { + .on_enter = nfc_scene_info_on_enter_st25tb, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read = + { + .on_enter = nfc_scene_read_on_enter_st25tb, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_read_success = + { + .on_enter = nfc_scene_read_success_on_enter_st25tb, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_saved_menu = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_scene_saved_menu_on_event_st25tb, + }, + .scene_save_name = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, + .scene_emulate = + { + .on_enter = nfc_protocol_support_common_on_enter_empty, + .on_event = nfc_protocol_support_common_on_event_empty, + }, +}; diff --git a/applications/main/nfc/helpers/protocol_support/st25tb/st25tb.h b/applications/main/nfc/helpers/protocol_support/st25tb/st25tb.h new file mode 100644 index 000000000..3b635fdef --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/st25tb/st25tb.h @@ -0,0 +1,5 @@ +#pragma once + +#include "../nfc_protocol_support_base.h" + +extern const NfcProtocolSupportBase nfc_protocol_support_st25tb; diff --git a/applications/main/nfc/helpers/protocol_support/st25tb/st25tb_render.c b/applications/main/nfc/helpers/protocol_support/st25tb/st25tb_render.c new file mode 100644 index 000000000..e3a0f3c50 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/st25tb/st25tb_render.c @@ -0,0 +1,22 @@ +#include "st25tb_render.h" +#include + +void nfc_render_st25tb_info( + const St25tbData* data, + NfcProtocolFormatType format_type, + FuriString* str) { + furi_string_cat_printf(str, "UID"); + + for(size_t i = 0; i < ST25TB_UID_SIZE; i++) { + furi_string_cat_printf(str, " %02X", data->uid[i]); + } + + if(format_type == NfcProtocolFormatTypeFull) { + furi_string_cat_printf(str, "\nSys. OTP: %08lX", data->system_otp_block); + furi_string_cat_printf(str, "\nBlocks:"); + for(size_t i = 0; i < st25tb_get_block_count(data->type); i += 2) { + furi_string_cat_printf( + str, "\n %02X %08lX %08lX", i, data->blocks[i], data->blocks[i + 1]); + } + } +} diff --git a/applications/main/nfc/helpers/protocol_support/st25tb/st25tb_render.h b/applications/main/nfc/helpers/protocol_support/st25tb/st25tb_render.h new file mode 100644 index 000000000..9f7be34e9 --- /dev/null +++ b/applications/main/nfc/helpers/protocol_support/st25tb/st25tb_render.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include "../nfc_protocol_support_render_common.h" + +void nfc_render_st25tb_info( + const St25tbData* data, + NfcProtocolFormatType format_type, + FuriString* str); diff --git a/applications/main/nfc/nfc.c b/applications/main/nfc/nfc.c deleted file mode 100644 index 561868110..000000000 --- a/applications/main/nfc/nfc.c +++ /dev/null @@ -1,321 +0,0 @@ -#include "nfc_i.h" -#include -#include - -bool nfc_custom_event_callback(void* context, uint32_t event) { - furi_assert(context); - Nfc* nfc = context; - return scene_manager_handle_custom_event(nfc->scene_manager, event); -} - -bool nfc_back_event_callback(void* context) { - furi_assert(context); - Nfc* nfc = context; - return scene_manager_handle_back_event(nfc->scene_manager); -} - -static void nfc_rpc_command_callback(RpcAppSystemEvent event, void* context) { - furi_assert(context); - Nfc* nfc = context; - - furi_assert(nfc->rpc_ctx); - - if(event == RpcAppEventSessionClose) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventRpcSessionClose); - rpc_system_app_set_callback(nfc->rpc_ctx, NULL, NULL); - nfc->rpc_ctx = NULL; - } else if(event == RpcAppEventAppExit) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); - } else if(event == RpcAppEventLoadFile) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventRpcLoad); - } else { - rpc_system_app_confirm(nfc->rpc_ctx, event, false); - } -} - -Nfc* nfc_alloc() { - Nfc* nfc = malloc(sizeof(Nfc)); - - nfc->worker = nfc_worker_alloc(); - nfc->view_dispatcher = view_dispatcher_alloc(); - nfc->scene_manager = scene_manager_alloc(&nfc_scene_handlers, nfc); - view_dispatcher_enable_queue(nfc->view_dispatcher); - view_dispatcher_set_event_callback_context(nfc->view_dispatcher, nfc); - view_dispatcher_set_custom_event_callback(nfc->view_dispatcher, nfc_custom_event_callback); - view_dispatcher_set_navigation_event_callback(nfc->view_dispatcher, nfc_back_event_callback); - - // Nfc device - nfc->dev = nfc_device_alloc(); - furi_string_set(nfc->dev->folder, NFC_APP_FOLDER); - - // Open GUI record - nfc->gui = furi_record_open(RECORD_GUI); - - // Open Notification record - nfc->notifications = furi_record_open(RECORD_NOTIFICATION); - - // Submenu - nfc->submenu = submenu_alloc(); - view_dispatcher_add_view(nfc->view_dispatcher, NfcViewMenu, submenu_get_view(nfc->submenu)); - - // Dialog - nfc->dialog_ex = dialog_ex_alloc(); - view_dispatcher_add_view( - nfc->view_dispatcher, NfcViewDialogEx, dialog_ex_get_view(nfc->dialog_ex)); - - // Popup - nfc->popup = popup_alloc(); - view_dispatcher_add_view(nfc->view_dispatcher, NfcViewPopup, popup_get_view(nfc->popup)); - - // Loading - nfc->loading = loading_alloc(); - view_dispatcher_add_view(nfc->view_dispatcher, NfcViewLoading, loading_get_view(nfc->loading)); - - // Text Input - nfc->text_input = text_input_alloc(); - view_dispatcher_add_view( - nfc->view_dispatcher, NfcViewTextInput, text_input_get_view(nfc->text_input)); - - // Byte Input - nfc->byte_input = byte_input_alloc(); - view_dispatcher_add_view( - nfc->view_dispatcher, NfcViewByteInput, byte_input_get_view(nfc->byte_input)); - - // TextBox - nfc->text_box = text_box_alloc(); - view_dispatcher_add_view( - nfc->view_dispatcher, NfcViewTextBox, text_box_get_view(nfc->text_box)); - nfc->text_box_store = furi_string_alloc(); - - // Custom Widget - nfc->widget = widget_alloc(); - view_dispatcher_add_view(nfc->view_dispatcher, NfcViewWidget, widget_get_view(nfc->widget)); - - // Mifare Classic Dict Attack - nfc->dict_attack = dict_attack_alloc(); - view_dispatcher_add_view( - nfc->view_dispatcher, NfcViewDictAttack, dict_attack_get_view(nfc->dict_attack)); - - // Detect Reader - nfc->detect_reader = detect_reader_alloc(); - view_dispatcher_add_view( - nfc->view_dispatcher, NfcViewDetectReader, detect_reader_get_view(nfc->detect_reader)); - - // Generator - nfc->generator = NULL; - - return nfc; -} - -void nfc_free(Nfc* nfc) { - furi_assert(nfc); - - if(nfc->rpc_state == NfcRpcStateEmulating) { - // Stop worker - nfc_worker_stop(nfc->worker); - } else if(nfc->rpc_state == NfcRpcStateEmulated) { - // Stop worker - nfc_worker_stop(nfc->worker); - // Save data in shadow file - if(furi_string_size(nfc->dev->load_path)) { - nfc_device_save_shadow(nfc->dev, furi_string_get_cstr(nfc->dev->load_path)); - } - } - if(nfc->rpc_ctx) { - rpc_system_app_send_exited(nfc->rpc_ctx); - rpc_system_app_set_callback(nfc->rpc_ctx, NULL, NULL); - nfc->rpc_ctx = NULL; - } - - // Nfc device - nfc_device_free(nfc->dev); - - // Submenu - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewMenu); - submenu_free(nfc->submenu); - - // DialogEx - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewDialogEx); - dialog_ex_free(nfc->dialog_ex); - - // Popup - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewPopup); - popup_free(nfc->popup); - - // Loading - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewLoading); - loading_free(nfc->loading); - - // TextInput - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewTextInput); - text_input_free(nfc->text_input); - - // ByteInput - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewByteInput); - byte_input_free(nfc->byte_input); - - // TextBox - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewTextBox); - text_box_free(nfc->text_box); - furi_string_free(nfc->text_box_store); - - // Custom Widget - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewWidget); - widget_free(nfc->widget); - - // Mifare Classic Dict Attack - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewDictAttack); - dict_attack_free(nfc->dict_attack); - - // Detect Reader - view_dispatcher_remove_view(nfc->view_dispatcher, NfcViewDetectReader); - detect_reader_free(nfc->detect_reader); - - // Worker - nfc_worker_stop(nfc->worker); - nfc_worker_free(nfc->worker); - - // View Dispatcher - view_dispatcher_free(nfc->view_dispatcher); - - // Scene Manager - scene_manager_free(nfc->scene_manager); - - // GUI - furi_record_close(RECORD_GUI); - nfc->gui = NULL; - - // Notifications - furi_record_close(RECORD_NOTIFICATION); - nfc->notifications = NULL; - - free(nfc); -} - -void nfc_text_store_set(Nfc* nfc, const char* text, ...) { - va_list args; - va_start(args, text); - - vsnprintf(nfc->text_store, sizeof(nfc->text_store), text, args); - - va_end(args); -} - -void nfc_text_store_clear(Nfc* nfc) { - memset(nfc->text_store, 0, sizeof(nfc->text_store)); -} - -void nfc_blink_read_start(Nfc* nfc) { - notification_message(nfc->notifications, &sequence_blink_start_cyan); -} - -void nfc_blink_emulate_start(Nfc* nfc) { - notification_message(nfc->notifications, &sequence_blink_start_magenta); -} - -void nfc_blink_detect_start(Nfc* nfc) { - notification_message(nfc->notifications, &sequence_blink_start_yellow); -} - -void nfc_blink_stop(Nfc* nfc) { - notification_message(nfc->notifications, &sequence_blink_stop); -} - -bool nfc_save_file(Nfc* nfc) { - furi_string_printf( - nfc->dev->load_path, - "%s/%s%s", - NFC_APP_FOLDER, - nfc->dev->dev_name, - NFC_APP_FILENAME_EXTENSION); - bool file_saved = nfc_device_save(nfc->dev, furi_string_get_cstr(nfc->dev->load_path)); - return file_saved; -} - -void nfc_show_loading_popup(void* context, bool show) { - Nfc* nfc = context; - TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME); - - if(show) { - // Raise timer priority so that animations can play - vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewLoading); - } else { - // Restore default timer priority - vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY); - } -} - -static bool nfc_is_hal_ready() { - if(!furi_hal_nfc_is_init()) { - // No connection to the chip, show an error screen - DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS); - DialogMessage* message = dialog_message_alloc(); - dialog_message_set_text( - message, - "Error!\nNFC chip failed to start\n\n\nSend a photo of this to:\nsupport@flipperzero.one", - 0, - 0, - AlignLeft, - AlignTop); - dialog_message_show(dialogs, message); - dialog_message_free(message); - furi_record_close(RECORD_DIALOGS); - return false; - } else { - return true; - } -} - -int32_t nfc_app(void* p) { - if(!nfc_is_hal_ready()) return 0; - - Nfc* nfc = nfc_alloc(); - char* args = p; - - // Check argument and run corresponding scene - if(args && strlen(args)) { - nfc_device_set_loading_callback(nfc->dev, nfc_show_loading_popup, nfc); - uint32_t rpc_ctx = 0; - if(sscanf(p, "RPC %lX", &rpc_ctx) == 1) { - nfc->rpc_ctx = (void*)rpc_ctx; - rpc_system_app_set_callback(nfc->rpc_ctx, nfc_rpc_command_callback, nfc); - rpc_system_app_send_started(nfc->rpc_ctx); - view_dispatcher_attach_to_gui( - nfc->view_dispatcher, nfc->gui, ViewDispatcherTypeDesktop); - scene_manager_next_scene(nfc->scene_manager, NfcSceneRpc); - } else { - view_dispatcher_attach_to_gui( - nfc->view_dispatcher, nfc->gui, ViewDispatcherTypeFullscreen); - if(nfc_device_load(nfc->dev, p, true)) { - if(nfc->dev->format == NfcDeviceSaveFormatMifareUl) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightEmulate); - dolphin_deed(DolphinDeedNfcEmulate); - } else if(nfc->dev->format == NfcDeviceSaveFormatMifareClassic) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicEmulate); - dolphin_deed(DolphinDeedNfcEmulate); - } else if(nfc->dev->format == NfcDeviceSaveFormatNfcV) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVEmulate); - dolphin_deed(DolphinDeedNfcEmulate); - } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneEmulateUid); - dolphin_deed(DolphinDeedNfcEmulate); - } - } else { - // Exit app - view_dispatcher_stop(nfc->view_dispatcher); - } - } - nfc_device_set_loading_callback(nfc->dev, NULL, nfc); - } else { - view_dispatcher_attach_to_gui( - nfc->view_dispatcher, nfc->gui, ViewDispatcherTypeFullscreen); - scene_manager_next_scene(nfc->scene_manager, NfcSceneStart); - } - - view_dispatcher_run(nfc->view_dispatcher); - - nfc_free(nfc); - - return 0; -} diff --git a/applications/main/nfc/nfc.h b/applications/main/nfc/nfc.h deleted file mode 100644 index e08be6a3a..000000000 --- a/applications/main/nfc/nfc.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - -typedef struct Nfc Nfc; diff --git a/applications/main/nfc/nfc_app.c b/applications/main/nfc/nfc_app.c new file mode 100644 index 000000000..141a67e5c --- /dev/null +++ b/applications/main/nfc/nfc_app.c @@ -0,0 +1,500 @@ +#include "nfc_app_i.h" + +#include + +bool nfc_custom_event_callback(void* context, uint32_t event) { + furi_assert(context); + NfcApp* nfc = context; + return scene_manager_handle_custom_event(nfc->scene_manager, event); +} + +bool nfc_back_event_callback(void* context) { + furi_assert(context); + NfcApp* nfc = context; + return scene_manager_handle_back_event(nfc->scene_manager); +} + +static void nfc_app_rpc_command_callback(const RpcAppSystemEvent* event, void* context) { + furi_assert(context); + NfcApp* nfc = (NfcApp*)context; + + furi_assert(nfc->rpc_ctx); + + if(event->type == RpcAppEventTypeSessionClose) { + view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventRpcSessionClose); + rpc_system_app_set_callback(nfc->rpc_ctx, NULL, NULL); + nfc->rpc_ctx = NULL; + } else if(event->type == RpcAppEventTypeAppExit) { + view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventRpcExit); + } else if(event->type == RpcAppEventTypeLoadFile) { + furi_assert(event->data.type == RpcAppSystemEventDataTypeString); + furi_string_set(nfc->file_path, event->data.string); + view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventRpcLoadFile); + } else { + rpc_system_app_confirm(nfc->rpc_ctx, false); + } +} + +NfcApp* nfc_app_alloc() { + NfcApp* instance = malloc(sizeof(NfcApp)); + + instance->view_dispatcher = view_dispatcher_alloc(); + instance->scene_manager = scene_manager_alloc(&nfc_scene_handlers, instance); + view_dispatcher_enable_queue(instance->view_dispatcher); + view_dispatcher_set_event_callback_context(instance->view_dispatcher, instance); + view_dispatcher_set_custom_event_callback( + instance->view_dispatcher, nfc_custom_event_callback); + view_dispatcher_set_navigation_event_callback( + instance->view_dispatcher, nfc_back_event_callback); + + instance->nfc = nfc_alloc(); + + instance->mf_ul_auth = mf_ultralight_auth_alloc(); + instance->mfc_key_cache = mf_classic_key_cache_alloc(); + + // Nfc device + instance->nfc_device = nfc_device_alloc(); + nfc_device_set_loading_callback(instance->nfc_device, nfc_show_loading_popup, instance); + + // Open GUI record + instance->gui = furi_record_open(RECORD_GUI); + + // Open Notification record + instance->notifications = furi_record_open(RECORD_NOTIFICATION); + + // Open Storage record + instance->storage = furi_record_open(RECORD_STORAGE); + + // Open Dialogs record + instance->dialogs = furi_record_open(RECORD_DIALOGS); + + // Submenu + instance->submenu = submenu_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, NfcViewMenu, submenu_get_view(instance->submenu)); + + // Dialog + instance->dialog_ex = dialog_ex_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, NfcViewDialogEx, dialog_ex_get_view(instance->dialog_ex)); + + // Popup + instance->popup = popup_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, NfcViewPopup, popup_get_view(instance->popup)); + + // Loading + instance->loading = loading_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, NfcViewLoading, loading_get_view(instance->loading)); + + // Text Input + instance->text_input = text_input_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, NfcViewTextInput, text_input_get_view(instance->text_input)); + + // Byte Input + instance->byte_input = byte_input_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, NfcViewByteInput, byte_input_get_view(instance->byte_input)); + + // TextBox + instance->text_box = text_box_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, NfcViewTextBox, text_box_get_view(instance->text_box)); + instance->text_box_store = furi_string_alloc(); + + // Custom Widget + instance->widget = widget_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, NfcViewWidget, widget_get_view(instance->widget)); + + // Dict attack + + instance->dict_attack = dict_attack_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, NfcViewDictAttack, dict_attack_get_view(instance->dict_attack)); + + // Detect Reader + instance->detect_reader = detect_reader_alloc(); + view_dispatcher_add_view( + instance->view_dispatcher, + NfcViewDetectReader, + detect_reader_get_view(instance->detect_reader)); + + instance->iso14443_3a_edit_data = iso14443_3a_alloc(); + instance->file_path = furi_string_alloc_set(NFC_APP_FOLDER); + instance->file_name = furi_string_alloc(); + + return instance; +} + +void nfc_app_free(NfcApp* instance) { + furi_assert(instance); + + if(instance->rpc_ctx) { + rpc_system_app_send_exited(instance->rpc_ctx); + rpc_system_app_set_callback(instance->rpc_ctx, NULL, NULL); + } + + nfc_free(instance->nfc); + + mf_ultralight_auth_free(instance->mf_ul_auth); + mf_classic_key_cache_free(instance->mfc_key_cache); + + // Nfc device + nfc_device_free(instance->nfc_device); + + // Submenu + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewMenu); + submenu_free(instance->submenu); + + // DialogEx + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewDialogEx); + dialog_ex_free(instance->dialog_ex); + + // Popup + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewPopup); + popup_free(instance->popup); + + // Loading + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewLoading); + loading_free(instance->loading); + + // TextInput + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewTextInput); + text_input_free(instance->text_input); + + // ByteInput + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewByteInput); + byte_input_free(instance->byte_input); + + // TextBox + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewTextBox); + text_box_free(instance->text_box); + furi_string_free(instance->text_box_store); + + // Custom Widget + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewWidget); + widget_free(instance->widget); + + // Dict attack + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewDictAttack); + dict_attack_free(instance->dict_attack); + + // Detect reader + view_dispatcher_remove_view(instance->view_dispatcher, NfcViewDetectReader); + detect_reader_free(instance->detect_reader); + + // View Dispatcher + view_dispatcher_free(instance->view_dispatcher); + + // Scene Manager + scene_manager_free(instance->scene_manager); + + furi_record_close(RECORD_DIALOGS); + furi_record_close(RECORD_STORAGE); + furi_record_close(RECORD_NOTIFICATION); + // GUI + furi_record_close(RECORD_GUI); + instance->gui = NULL; + + instance->notifications = NULL; + + iso14443_3a_free(instance->iso14443_3a_edit_data); + furi_string_free(instance->file_path); + furi_string_free(instance->file_name); + + free(instance); +} + +void nfc_text_store_set(NfcApp* nfc, const char* text, ...) { + va_list args; + va_start(args, text); + + vsnprintf(nfc->text_store, sizeof(nfc->text_store), text, args); + + va_end(args); +} + +void nfc_text_store_clear(NfcApp* nfc) { + memset(nfc->text_store, 0, sizeof(nfc->text_store)); +} + +void nfc_blink_read_start(NfcApp* nfc) { + notification_message(nfc->notifications, &sequence_blink_start_cyan); +} + +void nfc_blink_emulate_start(NfcApp* nfc) { + notification_message(nfc->notifications, &sequence_blink_start_magenta); +} + +void nfc_blink_detect_start(NfcApp* nfc) { + notification_message(nfc->notifications, &sequence_blink_start_yellow); +} + +void nfc_blink_stop(NfcApp* nfc) { + notification_message(nfc->notifications, &sequence_blink_stop); +} + +void nfc_make_app_folders(NfcApp* instance) { + furi_assert(instance); + + if(!storage_simply_mkdir(instance->storage, NFC_APP_FOLDER)) { + dialog_message_show_storage_error(instance->dialogs, "Cannot create\napp folder"); + } +} + +bool nfc_save_file(NfcApp* instance, FuriString* path) { + furi_assert(instance); + furi_assert(path); + + bool result = nfc_device_save(instance->nfc_device, furi_string_get_cstr(instance->file_path)); + + if(!result) { + dialog_message_show_storage_error(instance->dialogs, "Cannot save\nkey file"); + } + + return result; +} + +static bool nfc_set_shadow_file_path(FuriString* file_path, FuriString* shadow_file_path) { + furi_assert(file_path); + furi_assert(shadow_file_path); + + bool shadow_file_path_set = false; + if(furi_string_end_with(file_path, NFC_APP_SHADOW_EXTENSION)) { + furi_string_set(shadow_file_path, file_path); + shadow_file_path_set = true; + } else if(furi_string_end_with(file_path, NFC_APP_EXTENSION)) { + size_t path_len = furi_string_size(file_path); + // Cut .nfc + furi_string_set_n(shadow_file_path, file_path, 0, path_len - 4); + furi_string_cat_printf(shadow_file_path, "%s", NFC_APP_SHADOW_EXTENSION); + shadow_file_path_set = true; + } + + return shadow_file_path_set; +} + +static bool nfc_has_shadow_file_internal(NfcApp* instance, FuriString* path) { + furi_assert(path); + + bool has_shadow_file = false; + FuriString* shadow_file_path = furi_string_alloc(); + do { + if(furi_string_empty(path)) break; + if(!nfc_set_shadow_file_path(path, shadow_file_path)) break; + has_shadow_file = + storage_common_exists(instance->storage, furi_string_get_cstr(shadow_file_path)); + } while(false); + + furi_string_free(shadow_file_path); + + return has_shadow_file; +} + +bool nfc_has_shadow_file(NfcApp* instance) { + furi_assert(instance); + + return nfc_has_shadow_file_internal(instance, instance->file_path); +} + +static bool nfc_save_internal(NfcApp* instance, const char* extension) { + furi_assert(instance); + furi_assert(extension); + + bool result = false; + + nfc_make_app_folders(instance); + + if(furi_string_end_with(instance->file_path, NFC_APP_EXTENSION) || + (furi_string_end_with(instance->file_path, NFC_APP_SHADOW_EXTENSION))) { + size_t filename_start = furi_string_search_rchar(instance->file_path, '/'); + furi_string_left(instance->file_path, filename_start); + } + + furi_string_cat_printf( + instance->file_path, "/%s%s", furi_string_get_cstr(instance->file_name), extension); + + result = nfc_save_file(instance, instance->file_path); + + return result; +} + +bool nfc_save_shadow_file(NfcApp* instance) { + furi_assert(instance); + + return nfc_save_internal(instance, NFC_APP_SHADOW_EXTENSION); +} + +bool nfc_save(NfcApp* instance) { + furi_assert(instance); + + return nfc_save_internal(instance, NFC_APP_EXTENSION); +} + +bool nfc_load_file(NfcApp* instance, FuriString* path, bool show_dialog) { + furi_assert(instance); + furi_assert(path); + bool result = false; + + FuriString* load_path = furi_string_alloc(); + if(nfc_has_shadow_file_internal(instance, path)) { + nfc_set_shadow_file_path(path, load_path); + } else if(furi_string_end_with(path, NFC_APP_SHADOW_EXTENSION)) { + size_t path_len = furi_string_size(path); + furi_string_set_n(load_path, path, 0, path_len - 4); + furi_string_cat_printf(load_path, "%s", NFC_APP_EXTENSION); + } else { + furi_string_set(load_path, path); + } + + result = nfc_device_load(instance->nfc_device, furi_string_get_cstr(load_path)); + + if(result) { + path_extract_filename(load_path, instance->file_name, true); + } + + if((!result) && (show_dialog)) { + dialog_message_show_storage_error(instance->dialogs, "Cannot load\nkey file"); + } + + furi_string_free(load_path); + + return result; +} + +bool nfc_delete(NfcApp* instance) { + furi_assert(instance); + + if(nfc_has_shadow_file(instance)) { + nfc_delete_shadow_file(instance); + } + + if(furi_string_end_with_str(instance->file_path, NFC_APP_SHADOW_EXTENSION)) { + size_t path_len = furi_string_size(instance->file_path); + furi_string_replace_at(instance->file_path, path_len - 4, 4, NFC_APP_EXTENSION); + } + + return storage_simply_remove(instance->storage, furi_string_get_cstr(instance->file_path)); +} + +bool nfc_delete_shadow_file(NfcApp* instance) { + furi_assert(instance); + + FuriString* shadow_file_path = furi_string_alloc(); + + bool result = nfc_set_shadow_file_path(instance->file_path, shadow_file_path) && + storage_simply_remove(instance->storage, furi_string_get_cstr(shadow_file_path)); + + furi_string_free(shadow_file_path); + return result; +} + +bool nfc_load_from_file_select(NfcApp* instance) { + furi_assert(instance); + + DialogsFileBrowserOptions browser_options; + dialog_file_browser_set_basic_options(&browser_options, NFC_APP_EXTENSION, &I_Nfc_10px); + browser_options.base_path = NFC_APP_FOLDER; + browser_options.hide_dot_files = true; + + // Input events and views are managed by file_browser + bool result = dialog_file_browser_show( + instance->dialogs, instance->file_path, instance->file_path, &browser_options); + + if(result) { + result = nfc_load_file(instance, instance->file_path, true); + } + + return result; +} + +void nfc_show_loading_popup(void* context, bool show) { + NfcApp* nfc = context; + + if(show) { + // Raise timer priority so that animations can play + furi_timer_set_thread_priority(FuriTimerThreadPriorityElevated); + view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewLoading); + } else { + // Restore default timer priority + furi_timer_set_thread_priority(FuriTimerThreadPriorityNormal); + } +} + +void nfc_app_set_detected_protocols(NfcApp* instance, const NfcProtocol* types, uint32_t count) { + furi_assert(instance); + furi_assert(types); + furi_assert(count < NfcProtocolNum); + + memcpy(instance->protocols_detected, types, count); + instance->protocols_detected_num = count; + instance->protocols_detected_selected_idx = 0; +} + +void nfc_app_reset_detected_protocols(NfcApp* instance) { + furi_assert(instance); + + instance->protocols_detected_selected_idx = 0; + instance->protocols_detected_num = 0; +} + +static bool nfc_is_hal_ready() { + if(furi_hal_nfc_is_hal_ready() != FuriHalNfcErrorNone) { + // No connection to the chip, show an error screen + DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS); + DialogMessage* message = dialog_message_alloc(); + dialog_message_set_text( + message, + "Error!\nNFC chip failed to start\n\n\nSend a photo of this to:\nsupport@flipperzero.one", + 0, + 0, + AlignLeft, + AlignTop); + dialog_message_show(dialogs, message); + dialog_message_free(message); + furi_record_close(RECORD_DIALOGS); + return false; + } else { + return true; + } +} + +int32_t nfc_app(void* p) { + if(!nfc_is_hal_ready()) return 0; + + NfcApp* nfc = nfc_app_alloc(); + const char* args = p; + + if(args && strlen(args)) { + if(sscanf(args, "RPC %p", &nfc->rpc_ctx) == 1) { + rpc_system_app_set_callback(nfc->rpc_ctx, nfc_app_rpc_command_callback, nfc); + rpc_system_app_send_started(nfc->rpc_ctx); + view_dispatcher_attach_to_gui( + nfc->view_dispatcher, nfc->gui, ViewDispatcherTypeDesktop); + scene_manager_next_scene(nfc->scene_manager, NfcSceneRpc); + } else { + view_dispatcher_attach_to_gui( + nfc->view_dispatcher, nfc->gui, ViewDispatcherTypeFullscreen); + + furi_string_set(nfc->file_path, args); + if(nfc_load_file(nfc, nfc->file_path, false)) { + scene_manager_next_scene(nfc->scene_manager, NfcSceneEmulate); + } else { + view_dispatcher_stop(nfc->view_dispatcher); + } + } + } else { + view_dispatcher_attach_to_gui( + nfc->view_dispatcher, nfc->gui, ViewDispatcherTypeFullscreen); + scene_manager_next_scene(nfc->scene_manager, NfcSceneStart); + } + + view_dispatcher_run(nfc->view_dispatcher); + + nfc_app_free(nfc); + + return 0; +} diff --git a/applications/main/nfc/nfc_app.h b/applications/main/nfc/nfc_app.h new file mode 100644 index 000000000..c3026d302 --- /dev/null +++ b/applications/main/nfc/nfc_app.h @@ -0,0 +1,19 @@ +/** + * @file nfc_app.h + * @brief NFC application -- start here. + * + * Application for interfacing with NFC cards and other devices via Flipper's built-in NFC hardware. + * + * Main features: + * * Multiple protocols support + * * Card emulation + * * Shadow file support + * * Dynamically loaded parser plugins + * + * @see nfc_protocol.h for information on adding a new library protocol. + * @see nfc_protocol_support.h for information on integrating a library protocol into the app. + * @see nfc_supported_card_plugin.h for information on adding supported card plugins (parsers). + */ +#pragma once + +typedef struct NfcApp NfcApp; diff --git a/applications/main/nfc/nfc_app_i.h b/applications/main/nfc/nfc_app_i.h new file mode 100644 index 000000000..3c0092007 --- /dev/null +++ b/applications/main/nfc/nfc_app_i.h @@ -0,0 +1,192 @@ +#pragma once + +#include "nfc_app.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "views/dict_attack.h" +#include "views/detect_reader.h" +#include "views/dict_attack.h" + +#include +#include "helpers/nfc_custom_event.h" +#include "helpers/mf_ultralight_auth.h" +#include "helpers/mf_user_dict.h" +#include "helpers/mfkey32_logger.h" +#include "helpers/mf_classic_key_cache.h" + +#include +#include +#include + +#include "rpc/rpc_app.h" + +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#define NFC_NAME_SIZE 22 +#define NFC_TEXT_STORE_SIZE 128 +#define NFC_BYTE_INPUT_STORE_SIZE 10 +#define NFC_LOG_SIZE_MAX (1024) +#define NFC_APP_FOLDER ANY_PATH("nfc") +#define NFC_APP_EXTENSION ".nfc" +#define NFC_APP_SHADOW_EXTENSION ".shd" +#define NFC_APP_FILENAME_PREFIX "NFC" + +#define NFC_APP_MFKEY32_LOGS_FILE_NAME ".mfkey32.log" +#define NFC_APP_MFKEY32_LOGS_FILE_PATH (NFC_APP_FOLDER "/" NFC_APP_MFKEY32_LOGS_FILE_NAME) + +#define NFC_APP_MF_CLASSIC_DICT_USER_PATH (NFC_APP_FOLDER "/assets/mf_classic_dict_user.nfc") +#define NFC_APP_MF_CLASSIC_DICT_SYSTEM_PATH (NFC_APP_FOLDER "/assets/mf_classic_dict.nfc") + +typedef enum { + NfcRpcStateIdle, + NfcRpcStateEmulating, +} NfcRpcState; + +typedef struct { + NfcDict* dict; + uint8_t sectors_total; + uint8_t sectors_read; + uint8_t current_sector; + uint8_t keys_found; + size_t dict_keys_total; + size_t dict_keys_current; + bool is_key_attack; + uint8_t key_attack_current_sector; + bool is_card_present; +} NfcMfClassicDictAttackContext; + +struct NfcApp { + DialogsApp* dialogs; + Storage* storage; + Gui* gui; + ViewDispatcher* view_dispatcher; + NotificationApp* notifications; + SceneManager* scene_manager; + + char text_store[NFC_TEXT_STORE_SIZE + 1]; + FuriString* text_box_store; + uint8_t byte_input_store[NFC_BYTE_INPUT_STORE_SIZE]; + + uint32_t protocols_detected_num; + NfcProtocol protocols_detected[NfcProtocolNum]; + uint32_t protocols_detected_selected_idx; + + RpcAppSystem* rpc_ctx; + NfcRpcState rpc_state; + + // Common Views + Submenu* submenu; + DialogEx* dialog_ex; + Popup* popup; + Loading* loading; + TextInput* text_input; + ByteInput* byte_input; + TextBox* text_box; + Widget* widget; + DetectReader* detect_reader; + DictAttack* dict_attack; + + Nfc* nfc; + NfcPoller* poller; + NfcScanner* scanner; + NfcListener* listener; + + MfUltralightAuth* mf_ul_auth; + NfcMfClassicDictAttackContext nfc_dict_context; + Mfkey32Logger* mfkey32_logger; + MfUserDict* mf_user_dict; + MfClassicKeyCache* mfc_key_cache; + + NfcDevice* nfc_device; + Iso14443_3aData* iso14443_3a_edit_data; + FuriString* file_path; + FuriString* file_name; + FuriTimer* timer; +}; + +typedef enum { + NfcViewMenu, + NfcViewDialogEx, + NfcViewPopup, + NfcViewLoading, + NfcViewTextInput, + NfcViewByteInput, + NfcViewTextBox, + NfcViewWidget, + NfcViewDictAttack, + NfcViewDetectReader, +} NfcView; + +int32_t nfc_task(void* p); + +void nfc_text_store_set(NfcApp* nfc, const char* text, ...); + +void nfc_text_store_clear(NfcApp* nfc); + +void nfc_blink_read_start(NfcApp* nfc); + +void nfc_blink_emulate_start(NfcApp* nfc); + +void nfc_blink_detect_start(NfcApp* nfc); + +void nfc_blink_stop(NfcApp* nfc); + +void nfc_show_loading_popup(void* context, bool show); + +bool nfc_has_shadow_file(NfcApp* instance); + +bool nfc_save_shadow_file(NfcApp* instance); + +bool nfc_delete_shadow_file(NfcApp* instance); + +bool nfc_save(NfcApp* instance); + +bool nfc_delete(NfcApp* instance); + +bool nfc_load_from_file_select(NfcApp* instance); + +bool nfc_load_file(NfcApp* instance, FuriString* path, bool show_dialog); + +bool nfc_save_file(NfcApp* instance, FuriString* path); + +void nfc_make_app_folder(NfcApp* instance); + +void nfc_app_set_detected_protocols(NfcApp* instance, const NfcProtocol* types, uint32_t count); + +void nfc_app_reset_detected_protocols(NfcApp* instance); diff --git a/applications/main/nfc/nfc_cli.c b/applications/main/nfc/nfc_cli.c index e96174381..b5a40b122 100644 --- a/applications/main/nfc/nfc_cli.c +++ b/applications/main/nfc/nfc_cli.c @@ -4,90 +4,30 @@ #include #include -#include -#include +#include + +#define FLAG_EVENT (1 << 10) static void nfc_cli_print_usage() { printf("Usage:\r\n"); printf("nfc \r\n"); printf("Cmd list:\r\n"); - printf("\tdetect\t - detect nfc device\r\n"); - printf("\temulate\t - emulate predefined nfca card\r\n"); - printf("\tapdu\t - Send APDU and print response \r\n"); if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { printf("\tfield\t - turn field on\r\n"); } } -static void nfc_cli_detect(Cli* cli, FuriString* args) { - UNUSED(args); - // Check if nfc worker is not busy - if(furi_hal_nfc_is_busy()) { - printf("Nfc is busy\r\n"); - return; - } - - FuriHalNfcDevData dev_data = {}; - bool cmd_exit = false; - furi_hal_nfc_exit_sleep(); - printf("Detecting nfc...\r\nPress Ctrl+C to abort\r\n"); - while(!cmd_exit) { - cmd_exit |= cli_cmd_interrupt_received(cli); - if(furi_hal_nfc_detect(&dev_data, 400)) { - printf("Found: %s ", nfc_get_dev_type(dev_data.type)); - printf("UID length: %d, UID:", dev_data.uid_len); - for(size_t i = 0; i < dev_data.uid_len; i++) { - printf("%02X", dev_data.uid[i]); - } - printf("\r\n"); - break; - } - furi_hal_nfc_sleep(); - furi_delay_ms(50); - } - furi_hal_nfc_sleep(); -} - -static void nfc_cli_emulate(Cli* cli, FuriString* args) { - UNUSED(args); - // Check if nfc worker is not busy - if(furi_hal_nfc_is_busy()) { - printf("Nfc is busy\r\n"); - return; - } - - furi_hal_nfc_exit_sleep(); - printf("Emulating NFC-A Type: T2T UID: 36 9C E7 B1 0A C1 34 SAK: 00 ATQA: 00/44\r\n"); - printf("Press Ctrl+C to abort\r\n"); - - FuriHalNfcDevData params = { - .uid = {0x36, 0x9C, 0xe7, 0xb1, 0x0A, 0xC1, 0x34}, - .uid_len = 7, - .atqa = {0x44, 0x00}, - .sak = 0x00, - .type = FuriHalNfcTypeA, - }; - - while(!cli_cmd_interrupt_received(cli)) { - if(furi_hal_nfc_listen(params.uid, params.uid_len, params.atqa, params.sak, false, 100)) { - printf("Reader detected\r\n"); - furi_hal_nfc_sleep(); - } - furi_delay_ms(50); - } - furi_hal_nfc_sleep(); -} - static void nfc_cli_field(Cli* cli, FuriString* args) { UNUSED(args); // Check if nfc worker is not busy - if(furi_hal_nfc_is_busy()) { - printf("Nfc is busy\r\n"); + if(furi_hal_nfc_is_hal_ready() != FuriHalNfcErrorNone) { + printf("NFC chip failed to start\r\n"); return; } - furi_hal_nfc_exit_sleep(); - furi_hal_nfc_field_on(); + furi_hal_nfc_acquire(); + furi_hal_nfc_low_power_mode_stop(); + furi_hal_nfc_poller_field_on(); printf("Field is on. Don't leave device in this mode for too long.\r\n"); printf("Press Ctrl+C to abort\r\n"); @@ -96,73 +36,8 @@ static void nfc_cli_field(Cli* cli, FuriString* args) { furi_delay_ms(50); } - furi_hal_nfc_field_off(); - furi_hal_nfc_sleep(); -} - -static void nfc_cli_apdu(Cli* cli, FuriString* args) { - UNUSED(cli); - if(furi_hal_nfc_is_busy()) { - printf("Nfc is busy\r\n"); - return; - } - - furi_hal_nfc_exit_sleep(); - FuriString* data = NULL; - data = furi_string_alloc(); - FuriHalNfcTxRxContext tx_rx = {}; - FuriHalNfcDevData dev_data = {}; - uint8_t* req_buffer = NULL; - uint8_t* resp_buffer = NULL; - size_t apdu_size = 0; - size_t resp_size = 0; - - do { - if(!args_read_string_and_trim(args, data)) { - printf( - "Use like `nfc apdu 00a404000e325041592e5359532e444446303100 00a4040008a0000003010102` \r\n"); - break; - } - - printf("detecting tag\r\n"); - if(!furi_hal_nfc_detect(&dev_data, 300)) { - printf("Failed to detect tag\r\n"); - break; - } - do { - apdu_size = furi_string_size(data) / 2; - req_buffer = malloc(apdu_size); - hex_chars_to_uint8(furi_string_get_cstr(data), req_buffer); - - memcpy(tx_rx.tx_data, req_buffer, apdu_size); - tx_rx.tx_bits = apdu_size * 8; - tx_rx.tx_rx_type = FuriHalNfcTxRxTypeDefault; - - printf("Sending APDU:%s to Tag\r\n", furi_string_get_cstr(data)); - if(!furi_hal_nfc_tx_rx(&tx_rx, 300)) { - printf("Failed to tx_rx\r\n"); - break; - } - resp_size = (tx_rx.rx_bits / 8) * 2; - if(!resp_size) { - printf("No response\r\n"); - continue; - } - resp_buffer = malloc(resp_size); - uint8_to_hex_chars(tx_rx.rx_data, resp_buffer, resp_size); - resp_buffer[resp_size] = 0; - printf("Response: %s\r\n", resp_buffer); - free(req_buffer); - free(resp_buffer); - req_buffer = NULL; - resp_buffer = NULL; - } while(args_read_string_and_trim(args, data)); - } while(false); - - free(req_buffer); - free(resp_buffer); - furi_string_free(data); - furi_hal_nfc_sleep(); + furi_hal_nfc_low_power_mode_start(); + furi_hal_nfc_release(); } static void nfc_cli(Cli* cli, FuriString* args, void* context) { @@ -175,20 +50,6 @@ static void nfc_cli(Cli* cli, FuriString* args, void* context) { nfc_cli_print_usage(); break; } - if(furi_string_cmp_str(cmd, "detect") == 0) { - nfc_cli_detect(cli, args); - break; - } - if(furi_string_cmp_str(cmd, "emulate") == 0) { - nfc_cli_emulate(cli, args); - break; - } - - if(furi_string_cmp_str(cmd, "apdu") == 0) { - nfc_cli_apdu(cli, args); - break; - } - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { if(furi_string_cmp_str(cmd, "field") == 0) { nfc_cli_field(cli, args); diff --git a/applications/main/nfc/nfc_i.h b/applications/main/nfc/nfc_i.h deleted file mode 100644 index f7e489902..000000000 --- a/applications/main/nfc/nfc_i.h +++ /dev/null @@ -1,118 +0,0 @@ -#pragma once - -#include "nfc.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "views/dict_attack.h" -#include "views/detect_reader.h" - -#include -#include - -#include - -#include "rpc/rpc_app.h" - -#include - -ARRAY_DEF(MfClassicUserKeys, char*, M_PTR_OPLIST); - -#define NFC_TEXT_STORE_SIZE 128 -#define NFC_APP_FOLDER ANY_PATH("nfc") - -typedef enum { - NfcRpcStateIdle, - NfcRpcStateEmulating, - NfcRpcStateEmulated, -} NfcRpcState; - -struct Nfc { - NfcWorker* worker; - ViewDispatcher* view_dispatcher; - Gui* gui; - NotificationApp* notifications; - SceneManager* scene_manager; - NfcDevice* dev; - FuriHalNfcDevData dev_edit_data; - - char text_store[NFC_TEXT_STORE_SIZE + 1]; - FuriString* text_box_store; - uint8_t byte_input_store[6]; - MfClassicUserKeys_t mfc_key_strs; // Used in MFC key listing - - void* rpc_ctx; - NfcRpcState rpc_state; - - // Common Views - Submenu* submenu; - DialogEx* dialog_ex; - Popup* popup; - Loading* loading; - TextInput* text_input; - ByteInput* byte_input; - TextBox* text_box; - Widget* widget; - DictAttack* dict_attack; - DetectReader* detect_reader; - - const NfcGenerator* generator; -}; - -typedef enum { - NfcViewMenu, - NfcViewDialogEx, - NfcViewPopup, - NfcViewLoading, - NfcViewTextInput, - NfcViewByteInput, - NfcViewTextBox, - NfcViewWidget, - NfcViewDictAttack, - NfcViewDetectReader, -} NfcView; - -Nfc* nfc_alloc(); - -int32_t nfc_task(void* p); - -void nfc_text_store_set(Nfc* nfc, const char* text, ...); - -void nfc_text_store_clear(Nfc* nfc); - -void nfc_blink_read_start(Nfc* nfc); - -void nfc_blink_emulate_start(Nfc* nfc); - -void nfc_blink_detect_start(Nfc* nfc); - -void nfc_blink_stop(Nfc* nfc); - -bool nfc_save_file(Nfc* nfc); - -void nfc_show_loading_popup(void* context, bool show); diff --git a/applications/main/nfc/plugins/supported_cards/all_in_one.c b/applications/main/nfc/plugins/supported_cards/all_in_one.c new file mode 100644 index 000000000..1be23d1f3 --- /dev/null +++ b/applications/main/nfc/plugins/supported_cards/all_in_one.c @@ -0,0 +1,107 @@ +#include "nfc_supported_card_plugin.h" + +#include +#include + +#define TAG "AllInOne" + +typedef enum { + AllInOneLayoutTypeA, + AllInOneLayoutTypeD, + AllInOneLayoutTypeE2, + AllInOneLayoutTypeE3, + AllInOneLayoutTypeE5, + AllInOneLayoutType2, + AllInOneLayoutTypeUnknown, +} AllInOneLayoutType; + +static AllInOneLayoutType all_in_one_get_layout(const MfUltralightData* data) { + // Switch on the second half of the third byte of page 5 + const uint8_t layout_byte = data->page[5].data[2]; + const uint8_t layout_half_byte = data->page[5].data[2] & 0x0F; + + FURI_LOG_I(TAG, "Layout byte: %02x", layout_byte); + FURI_LOG_I(TAG, "Layout half-byte: %02x", layout_half_byte); + + switch(layout_half_byte) { + // If it is A, the layout type is a type A layout + case 0x0A: + return AllInOneLayoutTypeA; + case 0x0D: + return AllInOneLayoutTypeD; + case 0x02: + return AllInOneLayoutType2; + default: + FURI_LOG_I(TAG, "Unknown layout type: %d", layout_half_byte); + return AllInOneLayoutTypeUnknown; + } +} + +static bool all_in_one_parse(const NfcDevice* device, FuriString* parsed_data) { + furi_assert(device); + furi_assert(parsed_data); + + const MfUltralightData* data = nfc_device_get_data(device, NfcProtocolMfUltralight); + + bool parsed = false; + + do { + if(data->page[4].data[0] != 0x45 || data->page[4].data[1] != 0xD9) { + FURI_LOG_I(TAG, "Pass not verified"); + break; + } + + uint8_t ride_count = 0; + uint32_t serial = 0; + + const AllInOneLayoutType layout_type = all_in_one_get_layout(data); + + if(layout_type == AllInOneLayoutTypeA) { + // If the layout is A then the ride count is stored in the first byte of page 8 + ride_count = data->page[8].data[0]; + } else if(layout_type == AllInOneLayoutTypeD) { + // If the layout is D, the ride count is stored in the second byte of page 9 + ride_count = data->page[9].data[1]; + } else { + FURI_LOG_I(TAG, "Unknown layout: %d", layout_type); + ride_count = 137; + } + + // // The number starts at the second half of the third byte on page 4, and is 32 bits long + // // So we get the second half of the third byte, then bytes 4-6, and then the first half of the 7th byte + // // B8 17 A2 A4 BD becomes 81 7A 2A 4B + const uint8_t* serial_data_lo = data->page[4].data; + const uint8_t* serial_data_hi = data->page[5].data; + + serial = (serial_data_lo[2] & 0x0F) << 28 | serial_data_lo[3] << 20 | + serial_data_hi[0] << 12 | serial_data_hi[1] << 4 | serial_data_hi[2] >> 4; + + // Format string for rides count + furi_string_printf( + parsed_data, "\e#All-In-One\nNumber: %lu\nRides left: %u", serial, ride_count); + + parsed = true; + } while(false); + + return parsed; +} + +/* Actual implementation of app<>plugin interface */ +static const NfcSupportedCardsPlugin all_in_one_plugin = { + .protocol = NfcProtocolMfUltralight, + .verify = NULL, + .read = NULL, + .parse = all_in_one_parse, +}; + +/* Plugin descriptor to comply with basic plugin specification */ +static const FlipperAppPluginDescriptor all_in_one_plugin_descriptor = { + .appid = NFC_SUPPORTED_CARD_PLUGIN_APP_ID, + .ep_api_version = NFC_SUPPORTED_CARD_PLUGIN_API_VERSION, + .entry_point = &all_in_one_plugin, +}; + +/* Plugin entry point - must return a pointer to const descriptor */ +const FlipperAppPluginDescriptor* all_in_one_plugin_ep() { + return &all_in_one_plugin_descriptor; +} diff --git a/applications/main/nfc/plugins/supported_cards/myki.c b/applications/main/nfc/plugins/supported_cards/myki.c new file mode 100644 index 000000000..70a696371 --- /dev/null +++ b/applications/main/nfc/plugins/supported_cards/myki.c @@ -0,0 +1,116 @@ +/* myki.c - Parser for myki cards (Melbourne, Australia). + * + * Based on the code by Emily Trau (https://github.com/emilytrau) + * Original pull request URL: https://github.com/flipperdevices/flipperzero-firmware/pull/2326 + * Reference: https://github.com/metrodroid/metrodroid/wiki/Myki + */ +#include "nfc_supported_card_plugin.h" + +#include +#include + +static const MfDesfireApplicationId myki_app_id = {.data = {0x00, 0x11, 0xf2}}; +static const MfDesfireFileId myki_file_id = 0x0f; + +static uint8_t myki_calculate_luhn(uint64_t number) { + // https://en.wikipedia.org/wiki/Luhn_algorithm + // Drop existing check digit to form payload + uint64_t payload = number / 10; + int sum = 0; + int position = 0; + + while(payload > 0) { + int digit = payload % 10; + if(position % 2 == 0) { + digit *= 2; + } + if(digit > 9) { + digit = (digit / 10) + (digit % 10); + } + sum += digit; + payload /= 10; + position++; + } + + return (10 - (sum % 10)) % 10; +} + +static bool myki_parse(const NfcDevice* device, FuriString* parsed_data) { + furi_assert(device); + furi_assert(parsed_data); + + bool parsed = false; + + do { + const MfDesfireData* data = nfc_device_get_data(device, NfcProtocolMfDesfire); + + const MfDesfireApplication* app = mf_desfire_get_application(data, &myki_app_id); + if(app == NULL) break; + + typedef struct { + uint32_t top; + uint32_t bottom; + } MykiFile; + + const MfDesfireFileSettings* file_settings = + mf_desfire_get_file_settings(app, &myki_file_id); + + if(file_settings == NULL || file_settings->type != MfDesfireFileTypeStandard || + file_settings->data.size < sizeof(MykiFile)) + break; + + const MfDesfireFileData* file_data = mf_desfire_get_file_data(app, &myki_file_id); + if(file_data == NULL) break; + + const MykiFile* myki_file = simple_array_cget_data(file_data->data); + + // All myki card numbers are prefixed with "308425" + if(myki_file->top != 308425UL) break; + // Card numbers are always 15 digits in length + if(myki_file->bottom < 10000000UL || myki_file->bottom >= 100000000UL) break; + + uint64_t card_number = myki_file->top * 1000000000ULL + myki_file->bottom * 10UL; + // Stored card number doesn't include check digit + card_number += myki_calculate_luhn(card_number); + + furi_string_set(parsed_data, "\e#myki\n"); + + // Stylise card number according to the physical card + char card_string[20]; + snprintf(card_string, sizeof(card_string), "%llu", card_number); + + // Digit count in each space-separated group + static const uint8_t digit_count[] = {1, 5, 4, 4, 1}; + + for(uint32_t i = 0, k = 0; i < COUNT_OF(digit_count); k += digit_count[i++]) { + for(uint32_t j = 0; j < digit_count[i]; ++j) { + furi_string_push_back(parsed_data, card_string[j + k]); + } + furi_string_push_back(parsed_data, ' '); + } + + parsed = true; + } while(false); + + return parsed; +} + +/* Actual implementation of app<>plugin interface */ +static const NfcSupportedCardsPlugin myki_plugin = { + .protocol = NfcProtocolMfDesfire, + .verify = NULL, + .read = NULL, + .parse = myki_parse, +}; + +/* Plugin descriptor to comply with basic plugin specification */ +static const FlipperAppPluginDescriptor myki_plugin_descriptor = { + .appid = NFC_SUPPORTED_CARD_PLUGIN_APP_ID, + .ep_api_version = NFC_SUPPORTED_CARD_PLUGIN_API_VERSION, + .entry_point = &myki_plugin, +}; + +/* Plugin entry point - must return a pointer to const descriptor */ +const FlipperAppPluginDescriptor* myki_plugin_ep() { + return &myki_plugin_descriptor; +} diff --git a/applications/main/nfc/plugins/supported_cards/nfc_supported_card_plugin.h b/applications/main/nfc/plugins/supported_cards/nfc_supported_card_plugin.h new file mode 100644 index 000000000..7883aeb6b --- /dev/null +++ b/applications/main/nfc/plugins/supported_cards/nfc_supported_card_plugin.h @@ -0,0 +1,94 @@ +/** + * @file nfc_supported_card_plugin.h + * @brief Supported card plugin abstract interface. + * + * Supported card plugins are dynamically loaded libraries that help making sense of + * a particular card's raw data, if a suitable plugin exists. + * + * For example, if some card serves as a bus ticket, instead of just displaying a data dump, + * a suitable plugin will transform that data into a human-readable format, showing the number + * of rides or balance left. + * Because of the highly specialised nature of application-specific cards, a separate plugin + * for each such card type must be implemented. + * + * To add a new plugin, create a uniquely-named .c file in the `supported_cards` directory + * and implement at least the parse() function in the NfcSupportedCardsPlugin structure. + * Then, register the plugin in the `application.fam` file in the `nfc` directory. Use the existing + * entries as an example. After being registered, the plugin will be automatically deployed with the application. + * + * @note the APPID field MUST end with `_parser` so the applicaton would know that this particular file + * is a supported card plugin. + * + * @see nfc_supported_cards.h + */ +#pragma once + +#include + +#include +#include + +/** + * @brief Unique string identifier for supported card plugins. + */ +#define NFC_SUPPORTED_CARD_PLUGIN_APP_ID "NfcSupportedCardPlugin" + +/** + * @brief Currently supported plugin API version. + */ +#define NFC_SUPPORTED_CARD_PLUGIN_API_VERSION 1 + +/** + * @brief Verify that the card is of a supported type. + * + * This function should be implemented if a quick check exists + * allowing to verify that the plugin is working with the appropriate card type. + * Such checks may include, but are not limited to: reading a specific sector, + * performing a certain read operation, etc. + * + * @param[in,out] nfc pointer to an Nfc instance. + * @returns true if the card was successfully verified, false otherwise. + */ +typedef bool (*NfcSupportedCardPluginVerify)(Nfc* nfc); + +/** + * @brief Read the card using a custom procedure. + * + * This function should be implemented if a card requires some special reading + * procedure not covered in the vanilla poller. Examples include, but are not + * limited to: reading with particular security keys, mandatory order of read + * operations, etc. + * + * @param[in,out] nfc pointer to an Nfc instance. + * @param[in,out] device pointer to a device instance to hold the read data. + * @returns true if the card was successfully read, false otherwise. + */ +typedef bool (*NfcSupportedCardPluginRead)(Nfc* nfc, NfcDevice* device); + +/** + * @brief Parse raw data into human-readable representation. + * + * A supported card plugin may contain only this function, if no special verification + * or reading procedures are not required. In any case, the data must be complete and + * available through the `device` parameter at the time of calling. + * + * The output format is free and application-dependent. Multiple lines should + * be separated by newline character. + * + * @param[in] device pointer to a device instance holding the data is to be parsed. + * @param[out] parsed_data pointer to the string to contain the formatted result. + * @returns true if the card was successfully parsed, false otherwise. + */ +typedef bool (*NfcSupportedCardPluginParse)(const NfcDevice* device, FuriString* parsed_data); + +/** + * @brief Supported card plugin interface. + * + * For a minimally functional plugin, only the parse() function must be implemented. + */ +typedef struct { + NfcProtocol protocol; /**< Identifier of the protocol this card type works on top of. */ + NfcSupportedCardPluginVerify verify; /**< Pointer to the verify() function. */ + NfcSupportedCardPluginRead read; /**< Pointer to the read() function. */ + NfcSupportedCardPluginParse parse; /**< Pointer to the parse() function. */ +} NfcSupportedCardsPlugin; diff --git a/applications/main/nfc/plugins/supported_cards/opal.c b/applications/main/nfc/plugins/supported_cards/opal.c new file mode 100644 index 000000000..c71635d53 --- /dev/null +++ b/applications/main/nfc/plugins/supported_cards/opal.c @@ -0,0 +1,233 @@ +/* + * opal.c - Parser for Opal card (Sydney, Australia). + * + * Copyright 2023 Michael Farrell + * + * This will only read "standard" MIFARE DESFire-based Opal cards. Free travel + * cards (including School Opal cards, veteran, vision-impaired persons and + * TfNSW employees' cards) and single-trip tickets are MIFARE Ultralight C + * cards and not supported. + * + * Reference: https://github.com/metrodroid/metrodroid/wiki/Opal + * + * Note: The card values are all little-endian (like Flipper), but the above + * reference was originally written based on Java APIs, which are big-endian. + * This implementation presumes a little-endian system. + * + * 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. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "nfc_supported_card_plugin.h" + +#include +#include +#include + +#include + +static const MfDesfireApplicationId opal_app_id = {.data = {0x31, 0x45, 0x53}}; + +static const MfDesfireFileId opal_file_id = 0x07; + +static const char* opal_modes[5] = + {"Rail / Metro", "Ferry / Light Rail", "Bus", "Unknown mode", "Manly Ferry"}; + +static const char* opal_usages[14] = { + "New / Unused", + "Tap on: new journey", + "Tap on: transfer from same mode", + "Tap on: transfer from other mode", + NULL, // Manly Ferry: new journey + NULL, // Manly Ferry: transfer from ferry + NULL, // Manly Ferry: transfer from other + "Tap off: distance fare", + "Tap off: flat fare", + "Automated tap off: failed to tap off", + "Tap off: end of trip without start", + "Tap off: reversal", + "Tap on: rejected", + "Unknown usage", +}; + +// Opal file 0x7 structure. Assumes a little-endian CPU. +typedef struct __attribute__((__packed__)) { + uint32_t serial : 32; + uint8_t check_digit : 4; + bool blocked : 1; + uint16_t txn_number : 16; + int32_t balance : 21; + uint16_t days : 15; + uint16_t minutes : 11; + uint8_t mode : 3; + uint16_t usage : 4; + bool auto_topup : 1; + uint8_t weekly_journeys : 4; + uint16_t checksum : 16; +} OpalFile; + +static_assert(sizeof(OpalFile) == 16, "OpalFile"); + +// Converts an Opal timestamp to FuriHalRtcDateTime. +// +// Opal measures days since 1980-01-01 and minutes since midnight, and presumes +// all days are 1440 minutes. +static void opal_date_time_to_furi(uint16_t days, uint16_t minutes, FuriHalRtcDateTime* out) { + out->year = 1980; + out->month = 1; + // 1980-01-01 is a Tuesday + out->weekday = ((days + 1) % 7) + 1; + out->hour = minutes / 60; + out->minute = minutes % 60; + out->second = 0; + + // What year is it? + for(;;) { + const uint16_t num_days_in_year = furi_hal_rtc_get_days_per_year(out->year); + if(days < num_days_in_year) break; + days -= num_days_in_year; + out->year++; + } + + // 1-index the day of the year + days++; + + for(;;) { + // What month is it? + const bool is_leap = furi_hal_rtc_is_leap_year(out->year); + const uint8_t num_days_in_month = furi_hal_rtc_get_days_per_month(is_leap, out->month); + if(days <= num_days_in_month) break; + days -= num_days_in_month; + out->month++; + } + + out->day = days; +} + +static bool opal_parse(const NfcDevice* device, FuriString* parsed_data) { + furi_assert(device); + furi_assert(parsed_data); + + const MfDesfireData* data = nfc_device_get_data(device, NfcProtocolMfDesfire); + + bool parsed = false; + + do { + const MfDesfireApplication* app = mf_desfire_get_application(data, &opal_app_id); + if(app == NULL) break; + + const MfDesfireFileSettings* file_settings = + mf_desfire_get_file_settings(app, &opal_file_id); + if(file_settings == NULL || file_settings->type != MfDesfireFileTypeStandard || + file_settings->data.size != sizeof(OpalFile)) + break; + + const MfDesfireFileData* file_data = mf_desfire_get_file_data(app, &opal_file_id); + if(file_data == NULL) break; + + const OpalFile* opal_file = simple_array_cget_data(file_data->data); + + const uint8_t serial2 = opal_file->serial / 10000000; + const uint16_t serial3 = (opal_file->serial / 1000) % 10000; + const uint16_t serial4 = (opal_file->serial % 1000); + + if(opal_file->check_digit > 9) break; + + // Negative balance. Make this a positive value again and record the + // sign separately, because then we can handle balances of -99..-1 + // cents, as the "dollars" division below would result in a positive + // zero value. + const bool is_negative_balance = (opal_file->balance < 0); + const char* sign = is_negative_balance ? "-" : ""; + const int32_t balance = is_negative_balance ? labs(opal_file->balance) : //-V1081 + opal_file->balance; + const uint8_t balance_cents = balance % 100; + const int32_t balance_dollars = balance / 100; + + FuriHalRtcDateTime timestamp; + opal_date_time_to_furi(opal_file->days, opal_file->minutes, ×tamp); + + // Usages 4..6 associated with the Manly Ferry, which correspond to + // usages 1..3 for other modes. + const bool is_manly_ferry = (opal_file->usage >= 4) && (opal_file->usage <= 6); + + // 3..7 are "reserved", but we use 4 to indicate the Manly Ferry. + const uint8_t mode = is_manly_ferry ? 4 : opal_file->mode; + const uint8_t usage = is_manly_ferry ? opal_file->usage - 3 : opal_file->usage; + + const char* mode_str = opal_modes[mode > 4 ? 3 : mode]; + const char* usage_str = opal_usages[usage > 12 ? 13 : usage]; + + furi_string_printf( + parsed_data, + "\e#Opal: $%s%ld.%02hu\n3085 22%02hhu %04hu %03hu%01hhu\n%s, %s\n", + sign, + balance_dollars, + balance_cents, + serial2, + serial3, + serial4, + opal_file->check_digit, + mode_str, + usage_str); + + FuriString* timestamp_str = furi_string_alloc(); + + locale_format_date(timestamp_str, ×tamp, locale_get_date_format(), "-"); + furi_string_cat(parsed_data, timestamp_str); + furi_string_cat(parsed_data, " at "); + + locale_format_time(timestamp_str, ×tamp, locale_get_time_format(), false); + furi_string_cat(parsed_data, timestamp_str); + + furi_string_free(timestamp_str); + + furi_string_cat_printf( + parsed_data, + "\nWeekly journeys: %hhu, Txn #%hu\n", + opal_file->weekly_journeys, + opal_file->txn_number); + + if(opal_file->auto_topup) { + furi_string_cat_str(parsed_data, "Auto-topup enabled\n"); + } + + if(opal_file->blocked) { + furi_string_cat_str(parsed_data, "Card blocked\n"); + } + + parsed = true; + } while(false); + + return parsed; +} + +/* Actual implementation of app<>plugin interface */ +static const NfcSupportedCardsPlugin opal_plugin = { + .protocol = NfcProtocolMfDesfire, + .verify = NULL, + .read = NULL, + .parse = opal_parse, +}; + +/* Plugin descriptor to comply with basic plugin specification */ +static const FlipperAppPluginDescriptor opal_plugin_descriptor = { + .appid = NFC_SUPPORTED_CARD_PLUGIN_APP_ID, + .ep_api_version = NFC_SUPPORTED_CARD_PLUGIN_API_VERSION, + .entry_point = &opal_plugin, +}; + +/* Plugin entry point - must return a pointer to const descriptor */ +const FlipperAppPluginDescriptor* opal_plugin_ep() { + return &opal_plugin_descriptor; +} diff --git a/applications/main/nfc/plugins/supported_cards/plantain.c b/applications/main/nfc/plugins/supported_cards/plantain.c new file mode 100644 index 000000000..cb8c0093d --- /dev/null +++ b/applications/main/nfc/plugins/supported_cards/plantain.c @@ -0,0 +1,219 @@ +#include "nfc_supported_card_plugin.h" + +#include + +#include +#include +#include + +#define TAG "Plantain" + +typedef struct { + uint64_t a; + uint64_t b; +} MfClassicKeyPair; + +typedef struct { + const MfClassicKeyPair* keys; + uint32_t data_sector; +} PlantainCardConfig; + +static const MfClassicKeyPair plantain_1k_keys[] = { + {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xe56ac127dd45, .b = 0x19fc84a3784b}, + {.a = 0x77dabc9825e1, .b = 0x9764fec3154a}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0x26973ea74321, .b = 0xd27058c6e2c7}, + {.a = 0xeb0a8ff88ade, .b = 0x578a9ada41e3}, + {.a = 0xea0fd73cb149, .b = 0x29c35fa068fb}, + {.a = 0xc76bf71a2509, .b = 0x9ba241db3f56}, + {.a = 0xacffffffffff, .b = 0x71f3a315ad26}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, +}; + +static const MfClassicKeyPair plantain_4k_keys[] = { + {.a = 0xffffffffffff, .b = 0xffffffffffff}, {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xe56ac127dd45, .b = 0x19fc84a3784b}, {.a = 0x77dabc9825e1, .b = 0x9764fec3154a}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0x26973ea74321, .b = 0xd27058c6e2c7}, {.a = 0xeb0a8ff88ade, .b = 0x578a9ada41e3}, + {.a = 0xea0fd73cb149, .b = 0x29c35fa068fb}, {.a = 0xc76bf71a2509, .b = 0x9ba241db3f56}, + {.a = 0xacffffffffff, .b = 0x71f3a315ad26}, {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0x72f96bdd3714, .b = 0x462225cd34cf}, {.a = 0x044ce1872bc3, .b = 0x8c90c70cff4a}, + {.a = 0xbc2d1791dec1, .b = 0xca96a487de0b}, {.a = 0x8791b2ccb5c4, .b = 0xc956c3b80da3}, + {.a = 0x8e26e45e7d65, .b = 0x8e65b3af7d22}, {.a = 0x0f318130ed18, .b = 0x0c420a20e056}, + {.a = 0x045ceca15535, .b = 0x31bec3d9e510}, {.a = 0x9d993c5d4ef4, .b = 0x86120e488abf}, + {.a = 0xc65d4eaa645b, .b = 0xb69d40d1a439}, {.a = 0x3a8a139c20b4, .b = 0x8818a9c5d406}, + {.a = 0xbaff3053b496, .b = 0x4b7cb25354d3}, {.a = 0x7413b599c4ea, .b = 0xb0a2AAF3A1BA}, + {.a = 0x0ce7cd2cc72b, .b = 0xfa1fbb3f0f1f}, {.a = 0x0be5fac8b06a, .b = 0x6f95887a4fd3}, + {.a = 0x0eb23cc8110b, .b = 0x04dc35277635}, {.a = 0xbc4580b7f20b, .b = 0xd0a4131fb290}, + {.a = 0x7a396f0d633d, .b = 0xad2bdc097023}, {.a = 0xa3faa6daff67, .b = 0x7600e889adf9}, + {.a = 0xfd8705e721b0, .b = 0x296fc317a513}, {.a = 0x22052b480d11, .b = 0xe19504c39461}, + {.a = 0xa7141147d430, .b = 0xff16014fefc7}, {.a = 0x8a8d88151a00, .b = 0x038b5f9b5a2a}, + {.a = 0xb27addfb64b0, .b = 0x152fd0c420a7}, {.a = 0x7259fa0197c6, .b = 0x5583698df085}, +}; + +static bool plantain_get_card_config(PlantainCardConfig* config, MfClassicType type) { + bool success = true; + + if(type == MfClassicType1k) { + config->data_sector = 8; + config->keys = plantain_1k_keys; + } else if(type == MfClassicType4k) { + config->data_sector = 8; + config->keys = plantain_4k_keys; + } else { + success = false; + } + + return success; +} + +static bool plantain_verify_type(Nfc* nfc, MfClassicType type) { + bool verified = false; + + do { + PlantainCardConfig cfg = {}; + if(!plantain_get_card_config(&cfg, type)) break; + + const uint8_t block_num = mf_classic_get_first_block_num_of_sector(cfg.data_sector); + FURI_LOG_D(TAG, "Verifying sector %lu", cfg.data_sector); + + MfClassicKey key = {0}; + nfc_util_num2bytes(cfg.keys[cfg.data_sector].a, COUNT_OF(key.data), key.data); + + MfClassicAuthContext auth_context; + MfClassicError error = + mf_classic_poller_auth(nfc, block_num, &key, MfClassicKeyTypeA, &auth_context); + if(error != MfClassicErrorNone) { + FURI_LOG_D(TAG, "Failed to read block %u: %d", block_num, error); + break; + } + + verified = true; + } while(false); + + return verified; +} + +static bool plantain_verify(Nfc* nfc) { + return plantain_verify_type(nfc, MfClassicType1k) || + plantain_verify_type(nfc, MfClassicType4k); +} + +static bool plantain_read(Nfc* nfc, NfcDevice* device) { + furi_assert(nfc); + furi_assert(device); + + bool is_read = false; + + MfClassicData* data = mf_classic_alloc(); + nfc_device_copy_data(device, NfcProtocolMfClassic, data); + + do { + MfClassicType type = MfClassicTypeMini; + MfClassicError error = mf_classic_poller_detect_type(nfc, &type); + if(error != MfClassicErrorNone) break; + + data->type = type; + PlantainCardConfig cfg = {}; + if(!plantain_get_card_config(&cfg, data->type)) break; + + MfClassicDeviceKeys keys = {}; + for(size_t i = 0; i < mf_classic_get_total_sectors_num(data->type); i++) { + nfc_util_num2bytes(cfg.keys[i].a, sizeof(MfClassicKey), keys.key_a[i].data); + FURI_BIT_SET(keys.key_a_mask, i); + nfc_util_num2bytes(cfg.keys[i].b, sizeof(MfClassicKey), keys.key_b[i].data); + FURI_BIT_SET(keys.key_b_mask, i); + } + + error = mf_classic_poller_read(nfc, &keys, data); + if(error != MfClassicErrorNone) { + FURI_LOG_W(TAG, "Failed to read data"); + break; + } + + nfc_device_set_data(device, NfcProtocolMfClassic, data); + + is_read = true; + } while(false); + + mf_classic_free(data); + + return is_read; +} + +static bool plantain_parse(const NfcDevice* device, FuriString* parsed_data) { + furi_assert(device); + + const MfClassicData* data = nfc_device_get_data(device, NfcProtocolMfClassic); + + bool parsed = false; + + do { + // Verify card type + PlantainCardConfig cfg = {}; + if(!plantain_get_card_config(&cfg, data->type)) break; + + // Verify key + const MfClassicSectorTrailer* sec_tr = + mf_classic_get_sector_trailer_by_sector(data, cfg.data_sector); + + const uint64_t key = nfc_util_bytes2num(sec_tr->key_a.data, COUNT_OF(sec_tr->key_a.data)); + if(key != cfg.keys[cfg.data_sector].a) break; + + // Point to block 0 of sector 4, value 0 + const uint8_t* temp_ptr = data->block[16].data; + // Read first 4 bytes of block 0 of sector 4 from last to first and convert them to uint32_t + // 38 18 00 00 becomes 00 00 18 38, and equals to 6200 decimal + uint32_t balance = + ((temp_ptr[3] << 24) | (temp_ptr[2] << 16) | (temp_ptr[1] << 8) | temp_ptr[0]) / 100; + // Read card number + // Point to block 0 of sector 0, value 0 + temp_ptr = data->block[0].data; + // Read first 7 bytes of block 0 of sector 0 from last to first and convert them to uint64_t + // 04 31 16 8A 23 5C 80 becomes 80 5C 23 8A 16 31 04, and equals to 36130104729284868 decimal + uint8_t card_number_arr[7]; + for(size_t i = 0; i < 7; i++) { + card_number_arr[i] = temp_ptr[6 - i]; + } + // Copy card number to uint64_t + uint64_t card_number = 0; + for(size_t i = 0; i < 7; i++) { + card_number = (card_number << 8) | card_number_arr[i]; + } + + furi_string_printf( + parsed_data, "\e#Plantain\nN:%llu-\nBalance:%lu\n", card_number, balance); + parsed = true; + } while(false); + + return parsed; +} + +/* Actual implementation of app<>plugin interface */ +static const NfcSupportedCardsPlugin plantain_plugin = { + .protocol = NfcProtocolMfClassic, + .verify = plantain_verify, + .read = plantain_read, + .parse = plantain_parse, +}; + +/* Plugin descriptor to comply with basic plugin specification */ +static const FlipperAppPluginDescriptor plantain_plugin_descriptor = { + .appid = NFC_SUPPORTED_CARD_PLUGIN_APP_ID, + .ep_api_version = NFC_SUPPORTED_CARD_PLUGIN_API_VERSION, + .entry_point = &plantain_plugin, +}; + +/* Plugin entry point - must return a pointer to const descriptor */ +const FlipperAppPluginDescriptor* plantain_plugin_ep() { + return &plantain_plugin_descriptor; +} diff --git a/applications/main/nfc/plugins/supported_cards/troika.c b/applications/main/nfc/plugins/supported_cards/troika.c new file mode 100644 index 000000000..d42b977c6 --- /dev/null +++ b/applications/main/nfc/plugins/supported_cards/troika.c @@ -0,0 +1,214 @@ +#include "nfc_supported_card_plugin.h" + +#include + +#include +#include +#include + +#define TAG "Troika" + +typedef struct { + uint64_t a; + uint64_t b; +} MfClassicKeyPair; + +typedef struct { + const MfClassicKeyPair* keys; + uint32_t data_sector; +} TroikaCardConfig; + +static const MfClassicKeyPair troika_1k_keys[] = { + {.a = 0xa0a1a2a3a4a5, .b = 0xfbf225dc5d58}, + {.a = 0xa82607b01c0d, .b = 0x2910989b6880}, + {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, + {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, + {.a = 0x73068f118c13, .b = 0x2b7f3253fac5}, + {.a = 0xfbc2793d540b, .b = 0xd3a297dc2698}, + {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, + {.a = 0xae3d65a3dad4, .b = 0x0f1c63013dba}, + {.a = 0xa73f5dc1d333, .b = 0xe35173494a81}, + {.a = 0x69a32f1c2f19, .b = 0x6b8bd9860763}, + {.a = 0x9becdf3d9273, .b = 0xf8493407799d}, + {.a = 0x08b386463229, .b = 0x5efbaecef46b}, + {.a = 0xcd4c61c26e3d, .b = 0x31c7610de3b0}, + {.a = 0xa82607b01c0d, .b = 0x2910989b6880}, + {.a = 0x0e8f64340ba4, .b = 0x4acec1205d75}, + {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, +}; + +static const MfClassicKeyPair troika_4k_keys[] = { + {.a = 0xa0a1a2a3a4a5, .b = 0xfbf225dc5d58}, {.a = 0xa82607b01c0d, .b = 0x2910989b6880}, + {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, + {.a = 0x73068f118c13, .b = 0x2b7f3253fac5}, {.a = 0xfbc2793d540b, .b = 0xd3a297dc2698}, + {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, {.a = 0xae3d65a3dad4, .b = 0x0f1c63013dbb}, + {.a = 0xa73f5dc1d333, .b = 0xe35173494a81}, {.a = 0x69a32f1c2f19, .b = 0x6b8bd9860763}, + {.a = 0x9becdf3d9273, .b = 0xf8493407799d}, {.a = 0x08b386463229, .b = 0x5efbaecef46b}, + {.a = 0xcd4c61c26e3d, .b = 0x31c7610de3b0}, {.a = 0xa82607b01c0d, .b = 0x2910989b6880}, + {.a = 0x0e8f64340ba4, .b = 0x4acec1205d75}, {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, + {.a = 0x6b02733bb6ec, .b = 0x7038cd25c408}, {.a = 0x403d706ba880, .b = 0xb39d19a280df}, + {.a = 0xc11f4597efb5, .b = 0x70d901648cb9}, {.a = 0x0db520c78c1c, .b = 0x73e5b9d9d3a4}, + {.a = 0x3ebce0925b2f, .b = 0x372cc880f216}, {.a = 0x16a27af45407, .b = 0x9868925175ba}, + {.a = 0xaba208516740, .b = 0xce26ecb95252}, {.a = 0xcd64e567abcd, .b = 0x8f79c4fd8a01}, + {.a = 0x764cd061f1e6, .b = 0xa74332f74994}, {.a = 0x1cc219e9fec1, .b = 0xb90de525ceb6}, + {.a = 0x2fe3cb83ea43, .b = 0xfba88f109b32}, {.a = 0x07894ffec1d6, .b = 0xefcb0e689db3}, + {.a = 0x04c297b91308, .b = 0xc8454c154cb5}, {.a = 0x7a38e3511a38, .b = 0xab16584c972a}, + {.a = 0x7545df809202, .b = 0xecf751084a80}, {.a = 0x5125974cd391, .b = 0xd3eafb5df46d}, + {.a = 0x7a86aa203788, .b = 0xe41242278ca2}, {.a = 0xafcef64c9913, .b = 0x9db96dca4324}, + {.a = 0x04eaa462f70b, .b = 0xac17b93e2fae}, {.a = 0xe734c210f27e, .b = 0x29ba8c3e9fda}, + {.a = 0xd5524f591eed, .b = 0x5daf42861b4d}, {.a = 0xe4821a377b75, .b = 0xe8709e486465}, + {.a = 0x518dc6eea089, .b = 0x97c64ac98ca4}, {.a = 0xbb52f8cce07f, .b = 0x6b6119752c70}, +}; + +static bool troika_get_card_config(TroikaCardConfig* config, MfClassicType type) { + bool success = true; + + if(type == MfClassicType1k) { + config->data_sector = 8; + config->keys = troika_1k_keys; + } else if(type == MfClassicType4k) { + config->data_sector = 4; + config->keys = troika_4k_keys; + } else { + success = false; + } + + return success; +} + +static bool troika_verify_type(Nfc* nfc, MfClassicType type) { + bool verified = false; + + do { + TroikaCardConfig cfg = {}; + if(!troika_get_card_config(&cfg, type)) break; + + const uint8_t block_num = mf_classic_get_first_block_num_of_sector(cfg.data_sector); + FURI_LOG_D(TAG, "Verifying sector %lu", cfg.data_sector); + + MfClassicKey key = {0}; + nfc_util_num2bytes(cfg.keys[cfg.data_sector].a, COUNT_OF(key.data), key.data); + + MfClassicAuthContext auth_context; + MfClassicError error = + mf_classic_poller_auth(nfc, block_num, &key, MfClassicKeyTypeA, &auth_context); + if(error != MfClassicErrorNone) { + FURI_LOG_D(TAG, "Failed to read block %u: %d", block_num, error); + break; + } + + verified = true; + } while(false); + + return verified; +} + +static bool troika_verify(Nfc* nfc) { + return troika_verify_type(nfc, MfClassicType1k) || troika_verify_type(nfc, MfClassicType4k); +} + +static bool troika_read(Nfc* nfc, NfcDevice* device) { + furi_assert(nfc); + furi_assert(device); + + bool is_read = false; + + MfClassicData* data = mf_classic_alloc(); + nfc_device_copy_data(device, NfcProtocolMfClassic, data); + + do { + MfClassicType type = MfClassicTypeMini; + MfClassicError error = mf_classic_poller_detect_type(nfc, &type); + if(error != MfClassicErrorNone) break; + + data->type = type; + TroikaCardConfig cfg = {}; + if(!troika_get_card_config(&cfg, data->type)) break; + + MfClassicDeviceKeys keys = { + .key_a_mask = 0, + .key_b_mask = 0, + }; + for(size_t i = 0; i < mf_classic_get_total_sectors_num(data->type); i++) { + nfc_util_num2bytes(cfg.keys[i].a, sizeof(MfClassicKey), keys.key_a[i].data); + FURI_BIT_SET(keys.key_a_mask, i); + nfc_util_num2bytes(cfg.keys[i].b, sizeof(MfClassicKey), keys.key_b[i].data); + FURI_BIT_SET(keys.key_b_mask, i); + } + + error = mf_classic_poller_read(nfc, &keys, data); + if(error != MfClassicErrorNone) { + FURI_LOG_W(TAG, "Failed to read data"); + break; + } + + nfc_device_set_data(device, NfcProtocolMfClassic, data); + + is_read = true; + } while(false); + + mf_classic_free(data); + + return is_read; +} + +static bool troika_parse(const NfcDevice* device, FuriString* parsed_data) { + furi_assert(device); + + const MfClassicData* data = nfc_device_get_data(device, NfcProtocolMfClassic); + + bool parsed = false; + + do { + // Verify card type + TroikaCardConfig cfg = {}; + if(!troika_get_card_config(&cfg, data->type)) break; + + // Verify key + const MfClassicSectorTrailer* sec_tr = + mf_classic_get_sector_trailer_by_sector(data, cfg.data_sector); + + const uint64_t key = nfc_util_bytes2num(sec_tr->key_a.data, COUNT_OF(sec_tr->key_a.data)); + if(key != cfg.keys[cfg.data_sector].a) break; + + // Parse data + const uint8_t start_block_num = mf_classic_get_first_block_num_of_sector(cfg.data_sector); + + const uint8_t* temp_ptr = &data->block[start_block_num + 1].data[5]; + uint16_t balance = ((temp_ptr[0] << 8) | temp_ptr[1]) / 25; + temp_ptr = &data->block[start_block_num].data[2]; + + uint32_t number = 0; + for(size_t i = 1; i < 5; i++) { + number <<= 8; + number |= temp_ptr[i]; + } + number >>= 4; + number |= (temp_ptr[0] & 0xf) << 28; + + furi_string_printf(parsed_data, "\e#Troika\nNum: %lu\nBalance: %u RUR", number, balance); + parsed = true; + } while(false); + + return parsed; +} + +/* Actual implementation of app<>plugin interface */ +static const NfcSupportedCardsPlugin troika_plugin = { + .protocol = NfcProtocolMfClassic, + .verify = troika_verify, + .read = troika_read, + .parse = troika_parse, +}; + +/* Plugin descriptor to comply with basic plugin specification */ +static const FlipperAppPluginDescriptor troika_plugin_descriptor = { + .appid = NFC_SUPPORTED_CARD_PLUGIN_APP_ID, + .ep_api_version = NFC_SUPPORTED_CARD_PLUGIN_API_VERSION, + .entry_point = &troika_plugin, +}; + +/* Plugin entry point - must return a pointer to const descriptor */ +const FlipperAppPluginDescriptor* troika_plugin_ep() { + return &troika_plugin_descriptor; +} diff --git a/applications/main/nfc/plugins/supported_cards/two_cities.c b/applications/main/nfc/plugins/supported_cards/two_cities.c new file mode 100644 index 000000000..fb964103e --- /dev/null +++ b/applications/main/nfc/plugins/supported_cards/two_cities.c @@ -0,0 +1,189 @@ +#include "nfc_supported_card_plugin.h" + +#include + +#include +#include +#include + +#define TAG "TwoCities" + +typedef struct { + uint64_t a; + uint64_t b; +} MfClassicKeyPair; + +static const MfClassicKeyPair two_cities_4k_keys[] = { + {.a = 0xffffffffffff, .b = 0xffffffffffff}, {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, + {.a = 0xe56ac127dd45, .b = 0x19fc84a3784b}, {.a = 0x77dabc9825e1, .b = 0x9764fec3154a}, + {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xa73f5dc1d333, .b = 0xe35173494a81}, {.a = 0x69a32f1c2f19, .b = 0x6b8bd9860763}, + {.a = 0xea0fd73cb149, .b = 0x29c35fa068fb}, {.a = 0xc76bf71a2509, .b = 0x9ba241db3f56}, + {.a = 0xacffffffffff, .b = 0x71f3a315ad26}, {.a = 0xffffffffffff, .b = 0xffffffffffff}, + {.a = 0xffffffffffff, .b = 0xffffffffffff}, {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, + {.a = 0x72f96bdd3714, .b = 0x462225cd34cf}, {.a = 0x044ce1872bc3, .b = 0x8c90c70cff4a}, + {.a = 0xbc2d1791dec1, .b = 0xca96a487de0b}, {.a = 0x8791b2ccb5c4, .b = 0xc956c3b80da3}, + {.a = 0x8e26e45e7d65, .b = 0x8e65b3af7d22}, {.a = 0x0f318130ed18, .b = 0x0c420a20e056}, + {.a = 0x045ceca15535, .b = 0x31bec3d9e510}, {.a = 0x9d993c5d4ef4, .b = 0x86120e488abf}, + {.a = 0xc65d4eaa645b, .b = 0xb69d40d1a439}, {.a = 0x3a8a139c20b4, .b = 0x8818a9c5d406}, + {.a = 0xbaff3053b496, .b = 0x4b7cb25354d3}, {.a = 0x7413b599c4ea, .b = 0xb0a2AAF3A1BA}, + {.a = 0x0ce7cd2cc72b, .b = 0xfa1fbb3f0f1f}, {.a = 0x0be5fac8b06a, .b = 0x6f95887a4fd3}, + {.a = 0x26973ea74321, .b = 0xd27058c6e2c7}, {.a = 0xeb0a8ff88ade, .b = 0x578a9ada41e3}, + {.a = 0x7a396f0d633d, .b = 0xad2bdc097023}, {.a = 0xa3faa6daff67, .b = 0x7600e889adf9}, + {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, {.a = 0x2aa05ed1856f, .b = 0xeaac88e5dc99}, + {.a = 0xa7141147d430, .b = 0xff16014fefc7}, {.a = 0x8a8d88151a00, .b = 0x038b5f9b5a2a}, + {.a = 0xb27addfb64b0, .b = 0x152fd0c420a7}, {.a = 0x7259fa0197c6, .b = 0x5583698df085}, +}; + +bool two_cities_verify(Nfc* nfc) { + bool verified = false; + + do { + const uint8_t verify_sector = 4; + uint8_t block_num = mf_classic_get_first_block_num_of_sector(verify_sector); + FURI_LOG_D(TAG, "Verifying sector %u", verify_sector); + + MfClassicKey key = {}; + nfc_util_num2bytes(two_cities_4k_keys[verify_sector].a, COUNT_OF(key.data), key.data); + + MfClassicAuthContext auth_ctx = {}; + MfClassicError error = + mf_classic_poller_auth(nfc, block_num, &key, MfClassicKeyTypeA, &auth_ctx); + if(error != MfClassicErrorNone) { + FURI_LOG_D(TAG, "Failed to read block %u: %d", block_num, error); + break; + } + + verified = true; + } while(false); + + return verified; +} + +static bool two_cities_read(Nfc* nfc, NfcDevice* device) { + furi_assert(nfc); + furi_assert(device); + + bool is_read = false; + + MfClassicData* data = mf_classic_alloc(); + nfc_device_copy_data(device, NfcProtocolMfClassic, data); + + do { + MfClassicType type = MfClassicTypeMini; + MfClassicError error = mf_classic_poller_detect_type(nfc, &type); + if(error != MfClassicErrorNone) break; + + data->type = type; + MfClassicDeviceKeys keys = {}; + for(size_t i = 0; i < mf_classic_get_total_sectors_num(data->type); i++) { + nfc_util_num2bytes(two_cities_4k_keys[i].a, sizeof(MfClassicKey), keys.key_a[i].data); + FURI_BIT_SET(keys.key_a_mask, i); + nfc_util_num2bytes(two_cities_4k_keys[i].b, sizeof(MfClassicKey), keys.key_b[i].data); + FURI_BIT_SET(keys.key_b_mask, i); + } + + error = mf_classic_poller_read(nfc, &keys, data); + if(error != MfClassicErrorNone) { + FURI_LOG_W(TAG, "Failed to read data"); + break; + } + + nfc_device_set_data(device, NfcProtocolMfClassic, data); + + is_read = true; + } while(false); + + mf_classic_free(data); + + return is_read; +} + +static bool two_cities_parse(const NfcDevice* device, FuriString* parsed_data) { + furi_assert(device); + + const MfClassicData* data = nfc_device_get_data(device, NfcProtocolMfClassic); + + bool parsed = false; + + do { + // Verify key + MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, 4); + uint64_t key = nfc_util_bytes2num(sec_tr->key_a.data, 6); + if(key != two_cities_4k_keys[4].a) return false; + + // ===== + // PLANTAIN + // ===== + + // Point to block 0 of sector 4, value 0 + const uint8_t* temp_ptr = data->block[16].data; + // Read first 4 bytes of block 0 of sector 4 from last to first and convert them to uint32_t + // 38 18 00 00 becomes 00 00 18 38, and equals to 6200 decimal + uint32_t balance = + ((temp_ptr[3] << 24) | (temp_ptr[2] << 16) | (temp_ptr[1] << 8) | temp_ptr[0]) / 100; + // Read card number + // Point to block 0 of sector 0, value 0 + temp_ptr = data->block[0].data; + // Read first 7 bytes of block 0 of sector 0 from last to first and convert them to uint64_t + // 04 31 16 8A 23 5C 80 becomes 80 5C 23 8A 16 31 04, and equals to 36130104729284868 decimal + uint8_t card_number_arr[7]; + for(size_t i = 0; i < 7; i++) { + card_number_arr[i] = temp_ptr[6 - i]; + } + // Copy card number to uint64_t + uint64_t card_number = 0; + for(size_t i = 0; i < 7; i++) { + card_number = (card_number << 8) | card_number_arr[i]; + } + + // ===== + // --PLANTAIN-- + // ===== + // TROIKA + // ===== + + const uint8_t* troika_temp_ptr = &data->block[33].data[5]; + uint16_t troika_balance = ((troika_temp_ptr[0] << 8) | troika_temp_ptr[1]) / 25; + troika_temp_ptr = &data->block[32].data[2]; + uint32_t troika_number = 0; + for(size_t i = 0; i < 4; i++) { + troika_number <<= 8; + troika_number |= troika_temp_ptr[i]; + } + troika_number >>= 4; + + furi_string_printf( + parsed_data, + "\e#Troika+Plantain\nPN: %llu-\nPB: %lu rur.\nTN: %lu\nTB: %u rur.\n", + card_number, + balance, + troika_number, + troika_balance); + + parsed = true; + } while(false); + + return parsed; +} + +/* Actual implementation of app<>plugin interface */ +static const NfcSupportedCardsPlugin two_cities_plugin = { + .protocol = NfcProtocolMfClassic, + .verify = two_cities_verify, + .read = two_cities_read, + .parse = two_cities_parse, +}; + +/* Plugin descriptor to comply with basic plugin specification */ +static const FlipperAppPluginDescriptor two_cities_plugin_descriptor = { + .appid = NFC_SUPPORTED_CARD_PLUGIN_APP_ID, + .ep_api_version = NFC_SUPPORTED_CARD_PLUGIN_API_VERSION, + .entry_point = &two_cities_plugin, +}; + +/* Plugin entry point - must return a pointer to const descriptor */ +const FlipperAppPluginDescriptor* two_cities_plugin_ep() { + return &two_cities_plugin_descriptor; +} diff --git a/assets/resources/nfc/assets/aid.nfc b/applications/main/nfc/resources/nfc/assets/aid.nfc similarity index 100% rename from assets/resources/nfc/assets/aid.nfc rename to applications/main/nfc/resources/nfc/assets/aid.nfc diff --git a/assets/resources/nfc/assets/country_code.nfc b/applications/main/nfc/resources/nfc/assets/country_code.nfc similarity index 100% rename from assets/resources/nfc/assets/country_code.nfc rename to applications/main/nfc/resources/nfc/assets/country_code.nfc diff --git a/assets/resources/nfc/assets/currency_code.nfc b/applications/main/nfc/resources/nfc/assets/currency_code.nfc similarity index 100% rename from assets/resources/nfc/assets/currency_code.nfc rename to applications/main/nfc/resources/nfc/assets/currency_code.nfc diff --git a/assets/resources/nfc/assets/mf_classic_dict.nfc b/applications/main/nfc/resources/nfc/assets/mf_classic_dict.nfc similarity index 100% rename from assets/resources/nfc/assets/mf_classic_dict.nfc rename to applications/main/nfc/resources/nfc/assets/mf_classic_dict.nfc diff --git a/applications/main/nfc/scenes/nfc_scene_config.h b/applications/main/nfc/scenes/nfc_scene_config.h index 6232aaf30..f415c66a6 100644 --- a/applications/main/nfc/scenes/nfc_scene_config.h +++ b/applications/main/nfc/scenes/nfc_scene_config.h @@ -1,73 +1,57 @@ ADD_SCENE(nfc, start, Start) -ADD_SCENE(nfc, read, Read) +ADD_SCENE(nfc, file_select, FileSelect) ADD_SCENE(nfc, saved_menu, SavedMenu) -ADD_SCENE(nfc, extra_actions, ExtraActions) -ADD_SCENE(nfc, set_type, SetType) -ADD_SCENE(nfc, set_type_mf_uid, SetTypeMfUid) -ADD_SCENE(nfc, set_sak, SetSak) -ADD_SCENE(nfc, set_atqa, SetAtqa) -ADD_SCENE(nfc, set_uid, SetUid) -ADD_SCENE(nfc, generate_info, GenerateInfo) -ADD_SCENE(nfc, read_card_success, ReadCardSuccess) ADD_SCENE(nfc, save_name, SaveName) ADD_SCENE(nfc, save_success, SaveSuccess) -ADD_SCENE(nfc, file_select, FileSelect) -ADD_SCENE(nfc, emulate_uid, EmulateUid) -ADD_SCENE(nfc, nfca_read_success, NfcaReadSuccess) -ADD_SCENE(nfc, nfca_menu, NfcaMenu) -ADD_SCENE(nfc, nfcv_menu, NfcVMenu) -ADD_SCENE(nfc, nfcv_unlock_menu, NfcVUnlockMenu) -ADD_SCENE(nfc, nfcv_key_input, NfcVKeyInput) -ADD_SCENE(nfc, nfcv_unlock, NfcVUnlock) -ADD_SCENE(nfc, nfcv_emulate, NfcVEmulate) -ADD_SCENE(nfc, nfcv_sniff, NfcVSniff) -ADD_SCENE(nfc, nfcv_read_success, NfcVReadSuccess) -ADD_SCENE(nfc, mf_ultralight_read_success, MfUltralightReadSuccess) -ADD_SCENE(nfc, mf_ultralight_data, MfUltralightData) -ADD_SCENE(nfc, mf_ultralight_menu, MfUltralightMenu) -ADD_SCENE(nfc, mf_ultralight_emulate, MfUltralightEmulate) -ADD_SCENE(nfc, mf_ultralight_read_auth, MfUltralightReadAuth) -ADD_SCENE(nfc, mf_ultralight_read_auth_result, MfUltralightReadAuthResult) -ADD_SCENE(nfc, mf_ultralight_key_input, MfUltralightKeyInput) -ADD_SCENE(nfc, mf_ultralight_unlock_auto, MfUltralightUnlockAuto) -ADD_SCENE(nfc, mf_ultralight_unlock_menu, MfUltralightUnlockMenu) -ADD_SCENE(nfc, mf_ultralight_unlock_warn, MfUltralightUnlockWarn) -ADD_SCENE(nfc, mf_desfire_read_success, MfDesfireReadSuccess) -ADD_SCENE(nfc, mf_desfire_menu, MfDesfireMenu) -ADD_SCENE(nfc, mf_desfire_data, MfDesfireData) -ADD_SCENE(nfc, mf_desfire_app, MfDesfireApp) -ADD_SCENE(nfc, mf_classic_read_success, MfClassicReadSuccess) -ADD_SCENE(nfc, mf_classic_data, MfClassicData) -ADD_SCENE(nfc, mf_classic_menu, MfClassicMenu) -ADD_SCENE(nfc, mf_classic_emulate, MfClassicEmulate) -ADD_SCENE(nfc, mf_classic_keys, MfClassicKeys) -ADD_SCENE(nfc, mf_classic_keys_add, MfClassicKeysAdd) -ADD_SCENE(nfc, mf_classic_keys_list, MfClassicKeysList) -ADD_SCENE(nfc, mf_classic_keys_delete, MfClassicKeysDelete) -ADD_SCENE(nfc, mf_classic_keys_warn_duplicate, MfClassicKeysWarnDuplicate) -ADD_SCENE(nfc, mf_classic_dict_attack, MfClassicDictAttack) -ADD_SCENE(nfc, mf_classic_write, MfClassicWrite) -ADD_SCENE(nfc, mf_classic_write_success, MfClassicWriteSuccess) -ADD_SCENE(nfc, mf_classic_write_fail, MfClassicWriteFail) -ADD_SCENE(nfc, mf_classic_update, MfClassicUpdate) -ADD_SCENE(nfc, mf_classic_update_success, MfClassicUpdateSuccess) -ADD_SCENE(nfc, mf_classic_wrong_card, MfClassicWrongCard) -ADD_SCENE(nfc, emv_read_success, EmvReadSuccess) -ADD_SCENE(nfc, emv_menu, EmvMenu) -ADD_SCENE(nfc, emulate_apdu_sequence, EmulateApduSequence) -ADD_SCENE(nfc, device_info, DeviceInfo) ADD_SCENE(nfc, delete, Delete) ADD_SCENE(nfc, delete_success, DeleteSuccess) ADD_SCENE(nfc, restore_original_confirm, RestoreOriginalConfirm) ADD_SCENE(nfc, restore_original, RestoreOriginal) + +ADD_SCENE(nfc, detect, Detect) +ADD_SCENE(nfc, read, Read) +ADD_SCENE(nfc, info, Info) +ADD_SCENE(nfc, more_info, MoreInfo) +ADD_SCENE(nfc, supported_card, SupportedCard) +ADD_SCENE(nfc, select_protocol, SelectProtocol) +ADD_SCENE(nfc, extra_actions, ExtraActions) +ADD_SCENE(nfc, read_success, ReadSuccess) +ADD_SCENE(nfc, read_menu, ReadMenu) +ADD_SCENE(nfc, emulate, Emulate) +ADD_SCENE(nfc, rpc, Rpc) ADD_SCENE(nfc, debug, Debug) ADD_SCENE(nfc, field, Field) -ADD_SCENE(nfc, dict_not_found, DictNotFound) -ADD_SCENE(nfc, rpc, Rpc) -ADD_SCENE(nfc, exit_confirm, ExitConfirm) ADD_SCENE(nfc, retry_confirm, RetryConfirm) -ADD_SCENE(nfc, detect_reader, DetectReader) -ADD_SCENE(nfc, mfkey_nonces_info, MfkeyNoncesInfo) -ADD_SCENE(nfc, mfkey_complete, MfkeyComplete) -ADD_SCENE(nfc, nfc_data_info, NfcDataInfo) -ADD_SCENE(nfc, read_card_type, ReadCardType) +ADD_SCENE(nfc, exit_confirm, ExitConfirm) + +ADD_SCENE(nfc, mf_ultralight_unlock_menu, MfUltralightUnlockMenu) +ADD_SCENE(nfc, mf_ultralight_unlock_warn, MfUltralightUnlockWarn) +ADD_SCENE(nfc, mf_ultralight_key_input, MfUltralightKeyInput) +ADD_SCENE(nfc, mf_ultralight_capture_pass, MfUltralightCapturePass) + +ADD_SCENE(nfc, mf_desfire_more_info, MfDesfireMoreInfo) +ADD_SCENE(nfc, mf_desfire_app, MfDesfireApp) + +ADD_SCENE(nfc, mf_classic_dict_attack, MfClassicDictAttack) +ADD_SCENE(nfc, mf_classic_detect_reader, MfClassicDetectReader) +ADD_SCENE(nfc, mf_classic_mfkey_nonces_info, MfClassicMfkeyNoncesInfo) +ADD_SCENE(nfc, mf_classic_mfkey_complete, MfClassicMfkeyComplete) +ADD_SCENE(nfc, mf_classic_update_initial, MfClassicUpdateInitial) +ADD_SCENE(nfc, mf_classic_update_initial_success, MfClassicUpdateInitialSuccess) +ADD_SCENE(nfc, mf_classic_write_initial, MfClassicWriteInitial) +ADD_SCENE(nfc, mf_classic_write_initial_success, MfClassicWriteInitialSuccess) +ADD_SCENE(nfc, mf_classic_write_initial_fail, MfClassicWriteInitialFail) +ADD_SCENE(nfc, mf_classic_wrong_card, MfClassicWrongCard) + +ADD_SCENE(nfc, mf_classic_keys, MfClassicKeys) +ADD_SCENE(nfc, mf_classic_keys_list, MfClassicKeysList) +ADD_SCENE(nfc, mf_classic_keys_delete, MfClassicKeysDelete) +ADD_SCENE(nfc, mf_classic_keys_add, MfClassicKeysAdd) +ADD_SCENE(nfc, mf_classic_keys_warn_duplicate, MfClassicKeysWarnDuplicate) + +ADD_SCENE(nfc, set_type, SetType) +ADD_SCENE(nfc, set_sak, SetSak) +ADD_SCENE(nfc, set_atqa, SetAtqa) +ADD_SCENE(nfc, set_uid, SetUid) + +ADD_SCENE(nfc, generate_info, GenerateInfo) diff --git a/applications/main/nfc/scenes/nfc_scene_debug.c b/applications/main/nfc/scenes/nfc_scene_debug.c index ed079c2ed..97592f2e2 100644 --- a/applications/main/nfc/scenes/nfc_scene_debug.c +++ b/applications/main/nfc/scenes/nfc_scene_debug.c @@ -1,4 +1,4 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" enum SubmenuDebugIndex { SubmenuDebugIndexField, @@ -6,29 +6,26 @@ enum SubmenuDebugIndex { }; void nfc_scene_debug_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, index); } void nfc_scene_debug_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; Submenu* submenu = nfc->submenu; submenu_add_item( submenu, "Field", SubmenuDebugIndexField, nfc_scene_debug_submenu_callback, nfc); - submenu_add_item( - submenu, "Apdu", SubmenuDebugIndexApdu, nfc_scene_debug_submenu_callback, nfc); submenu_set_selected_item( submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneDebug)); - nfc_device_clear(nfc->dev); view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); } bool nfc_scene_debug_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { @@ -37,18 +34,13 @@ bool nfc_scene_debug_on_event(void* context, SceneManagerEvent event) { nfc->scene_manager, NfcSceneDebug, SubmenuDebugIndexField); scene_manager_next_scene(nfc->scene_manager, NfcSceneField); consumed = true; - } else if(event.event == SubmenuDebugIndexApdu) { - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneDebug, SubmenuDebugIndexApdu); - scene_manager_next_scene(nfc->scene_manager, NfcSceneEmulateApduSequence); - consumed = true; } } return consumed; } void nfc_scene_debug_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; submenu_reset(nfc->submenu); } diff --git a/applications/main/nfc/scenes/nfc_scene_delete.c b/applications/main/nfc/scenes/nfc_scene_delete.c index 0808db45a..c1a676168 100644 --- a/applications/main/nfc/scenes/nfc_scene_delete.c +++ b/applications/main/nfc/scenes/nfc_scene_delete.c @@ -1,21 +1,20 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_delete_widget_callback(GuiButtonType result, InputType type, void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; if(type == InputTypeShort) { view_dispatcher_send_custom_event(nfc->view_dispatcher, result); } } void nfc_scene_delete_on_enter(void* context) { - Nfc* nfc = context; - FuriHalNfcDevData* nfc_data = &nfc->dev->dev_data.nfc_data; + NfcApp* nfc = context; // Setup Custom Widget view FuriString* temp_str; temp_str = furi_string_alloc(); - furi_string_printf(temp_str, "\e#Delete %s?\e#", nfc->dev->dev_name); + furi_string_printf(temp_str, "\e#Delete %s?\e#", furi_string_get_cstr(nfc->file_name)); widget_add_text_box_element( nfc->widget, 0, 0, 128, 23, AlignCenter, AlignCenter, furi_string_get_cstr(temp_str), false); widget_add_button_element( @@ -23,47 +22,33 @@ void nfc_scene_delete_on_enter(void* context) { widget_add_button_element( nfc->widget, GuiButtonTypeRight, "Delete", nfc_scene_delete_widget_callback, nfc); + size_t uid_len; + const uint8_t* uid = nfc_device_get_uid(nfc->nfc_device, &uid_len); + furi_string_set(temp_str, "UID:"); - for(size_t i = 0; i < nfc_data->uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", nfc_data->uid[i]); + for(size_t i = 0; i < uid_len; i++) { + furi_string_cat_printf(temp_str, " %02X", uid[i]); } widget_add_string_element( nfc->widget, 64, 24, AlignCenter, AlignTop, FontSecondary, furi_string_get_cstr(temp_str)); - NfcProtocol protocol = nfc->dev->dev_data.protocol; - const char* nfc_type = "NFC-A"; - - if(protocol == NfcDeviceProtocolEMV) { - furi_string_set(temp_str, "EMV bank card"); - } else if(protocol == NfcDeviceProtocolMifareUl) { - furi_string_set(temp_str, nfc_mf_ul_type(nfc->dev->dev_data.mf_ul_data.type, true)); - } else if(protocol == NfcDeviceProtocolMifareClassic) { - furi_string_set(temp_str, nfc_mf_classic_type(nfc->dev->dev_data.mf_classic_data.type)); - } else if(protocol == NfcDeviceProtocolMifareDesfire) { - furi_string_set(temp_str, "MIFARE DESFire"); - } else if(protocol == NfcDeviceProtocolNfcV) { - furi_string_set(temp_str, "ISO15693 tag"); - nfc_type = "NFC-V"; - } else { - furi_string_set(temp_str, "Unknown ISO tag"); - } + furi_string_set_str(temp_str, nfc_device_get_name(nfc->nfc_device, NfcDeviceNameTypeFull)); widget_add_string_element( nfc->widget, 64, 34, AlignCenter, AlignTop, FontSecondary, furi_string_get_cstr(temp_str)); - widget_add_string_element(nfc->widget, 64, 44, AlignCenter, AlignTop, FontSecondary, nfc_type); furi_string_free(temp_str); view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); } bool nfc_scene_delete_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == GuiButtonTypeLeft) { consumed = scene_manager_previous_scene(nfc->scene_manager); } else if(event.event == GuiButtonTypeRight) { - if(nfc_device_delete(nfc->dev, true)) { + if(nfc_delete(nfc)) { scene_manager_next_scene(nfc->scene_manager, NfcSceneDeleteSuccess); } else { scene_manager_search_and_switch_to_previous_scene( @@ -76,7 +61,7 @@ bool nfc_scene_delete_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_delete_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; widget_reset(nfc->widget); } diff --git a/applications/main/nfc/scenes/nfc_scene_delete_success.c b/applications/main/nfc/scenes/nfc_scene_delete_success.c index 795363527..f0c22eec4 100644 --- a/applications/main/nfc/scenes/nfc_scene_delete_success.c +++ b/applications/main/nfc/scenes/nfc_scene_delete_success.c @@ -1,12 +1,12 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_delete_success_popup_callback(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); } void nfc_scene_delete_success_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Setup view Popup* popup = nfc->popup; @@ -20,7 +20,7 @@ void nfc_scene_delete_success_on_enter(void* context) { } bool nfc_scene_delete_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { @@ -38,7 +38,7 @@ bool nfc_scene_delete_success_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_delete_success_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Clear view popup_reset(nfc->popup); diff --git a/applications/main/nfc/scenes/nfc_scene_detect.c b/applications/main/nfc/scenes/nfc_scene_detect.c new file mode 100644 index 000000000..326b1458c --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_detect.c @@ -0,0 +1,59 @@ +#include "../nfc_app_i.h" +#include + +void nfc_scene_detect_scan_callback(NfcScannerEvent event, void* context) { + furi_assert(context); + + NfcApp* instance = context; + + if(event.type == NfcScannerEventTypeDetected) { + nfc_app_set_detected_protocols(instance, event.data.protocols, event.data.protocol_num); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventWorkerExit); + } +} + +void nfc_scene_detect_on_enter(void* context) { + NfcApp* instance = context; + + // Setup view + popup_reset(instance->popup); + popup_set_text( + instance->popup, "Apply card to\nFlipper's back", 97, 24, AlignCenter, AlignTop); + popup_set_icon(instance->popup, 0, 8, &I_NFC_manual_60x50); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewPopup); + + nfc_app_reset_detected_protocols(instance); + + instance->scanner = nfc_scanner_alloc(instance->nfc); + nfc_scanner_start(instance->scanner, nfc_scene_detect_scan_callback, instance); + + nfc_blink_detect_start(instance); +} + +bool nfc_scene_detect_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventWorkerExit) { + if(instance->protocols_detected_num > 1) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSelectProtocol); + } else { + scene_manager_next_scene(instance->scene_manager, NfcSceneRead); + } + consumed = true; + } + } + + return consumed; +} + +void nfc_scene_detect_on_exit(void* context) { + NfcApp* instance = context; + + nfc_scanner_stop(instance->scanner); + nfc_scanner_free(instance->scanner); + popup_reset(instance->popup); + + nfc_blink_stop(instance); +} diff --git a/applications/main/nfc/scenes/nfc_scene_detect_reader.c b/applications/main/nfc/scenes/nfc_scene_detect_reader.c deleted file mode 100644 index 745946157..000000000 --- a/applications/main/nfc/scenes/nfc_scene_detect_reader.c +++ /dev/null @@ -1,103 +0,0 @@ -#include "../nfc_i.h" - -#define NFC_SCENE_DETECT_READER_PAIR_NONCES_MAX (10U) - -static const NotificationSequence sequence_detect_reader = { - &message_green_255, - &message_blue_255, - &message_do_not_reset, - NULL, -}; - -bool nfc_detect_reader_worker_callback(NfcWorkerEvent event, void* context) { - UNUSED(event); - furi_assert(context); - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, event); - return true; -} - -void nfc_scene_detect_reader_callback(void* context) { - furi_assert(context); - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -void nfc_scene_detect_reader_on_enter(void* context) { - Nfc* nfc = context; - - detect_reader_set_callback(nfc->detect_reader, nfc_scene_detect_reader_callback, nfc); - detect_reader_set_nonces_max(nfc->detect_reader, NFC_SCENE_DETECT_READER_PAIR_NONCES_MAX); - NfcDeviceData* dev_data = &nfc->dev->dev_data; - if(dev_data->nfc_data.uid_len) { - detect_reader_set_uid( - nfc->detect_reader, dev_data->nfc_data.uid, dev_data->nfc_data.uid_len); - } - - // Store number of collected nonces in scene state - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneDetectReader, 0); - notification_message(nfc->notifications, &sequence_detect_reader); - - nfc_worker_start( - nfc->worker, - NfcWorkerStateAnalyzeReader, - &nfc->dev->dev_data, - nfc_detect_reader_worker_callback, - nfc); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewDetectReader); -} - -bool nfc_scene_detect_reader_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - uint32_t nonces_collected = - scene_manager_get_scene_state(nfc->scene_manager, NfcSceneDetectReader); - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventViewExit) { - nfc_worker_stop(nfc->worker); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfkeyNoncesInfo); - consumed = true; - } else if(event.event == NfcWorkerEventDetectReaderMfkeyCollected) { - nonces_collected += 2; - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneDetectReader, nonces_collected); - detect_reader_set_nonces_collected(nfc->detect_reader, nonces_collected); - if(nonces_collected >= NFC_SCENE_DETECT_READER_PAIR_NONCES_MAX) { - detect_reader_set_state(nfc->detect_reader, DetectReaderStateDone); - nfc_blink_stop(nfc); - notification_message(nfc->notifications, &sequence_single_vibro); - notification_message(nfc->notifications, &sequence_set_green_255); - nfc_worker_stop(nfc->worker); - } - consumed = true; - } else if(event.event == NfcWorkerEventDetectReaderDetected) { - if(nonces_collected < NFC_SCENE_DETECT_READER_PAIR_NONCES_MAX) { - notification_message(nfc->notifications, &sequence_blink_start_cyan); - detect_reader_set_state(nfc->detect_reader, DetectReaderStateReaderDetected); - } - } else if(event.event == NfcWorkerEventDetectReaderLost) { - if(nonces_collected < NFC_SCENE_DETECT_READER_PAIR_NONCES_MAX) { - nfc_blink_stop(nfc); - notification_message(nfc->notifications, &sequence_detect_reader); - detect_reader_set_state(nfc->detect_reader, DetectReaderStateReaderLost); - } - } - } - - return consumed; -} - -void nfc_scene_detect_reader_on_exit(void* context) { - Nfc* nfc = context; - - // Stop worker - nfc_worker_stop(nfc->worker); - - // Clear view - detect_reader_reset(nfc->detect_reader); - - // Stop notifications - nfc_blink_stop(nfc); - notification_message(nfc->notifications, &sequence_reset_green); -} diff --git a/applications/main/nfc/scenes/nfc_scene_device_info.c b/applications/main/nfc/scenes/nfc_scene_device_info.c deleted file mode 100644 index 5d51c0816..000000000 --- a/applications/main/nfc/scenes/nfc_scene_device_info.c +++ /dev/null @@ -1,87 +0,0 @@ -#include "../nfc_i.h" -#include "../helpers/nfc_emv_parser.h" - -void nfc_scene_device_info_widget_callback(GuiButtonType result, InputType type, void* context) { - Nfc* nfc = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_device_info_on_enter(void* context) { - Nfc* nfc = context; - NfcDeviceData* dev_data = &nfc->dev->dev_data; - - FuriString* temp_str; - temp_str = furi_string_alloc(); - - if(dev_data->protocol == NfcDeviceProtocolEMV) { - EmvData* emv_data = &dev_data->emv_data; - furi_string_printf(temp_str, "\e#%s\n", emv_data->name); - for(uint8_t i = 0; i < emv_data->number_len; i += 2) { - furi_string_cat_printf( - temp_str, "%02X%02X ", emv_data->number[i], emv_data->number[i + 1]); - } - furi_string_trim(temp_str); - - // Add expiration date - if(emv_data->exp_mon) { - furi_string_cat_printf( - temp_str, "\nExp: %02X/%02X", emv_data->exp_mon, emv_data->exp_year); - } - // Parse currency code - if((emv_data->currency_code)) { - FuriString* currency_name; - currency_name = furi_string_alloc(); - if(nfc_emv_parser_get_currency_name( - nfc->dev->storage, emv_data->currency_code, currency_name)) { - furi_string_cat_printf( - temp_str, "\nCur: %s ", furi_string_get_cstr(currency_name)); - } - furi_string_free(currency_name); - } - // Parse country code - if((emv_data->country_code)) { - FuriString* country_name; - country_name = furi_string_alloc(); - if(nfc_emv_parser_get_country_name( - nfc->dev->storage, emv_data->country_code, country_name)) { - furi_string_cat_printf(temp_str, "Reg: %s", furi_string_get_cstr(country_name)); - } - furi_string_free(country_name); - } - } else if( - dev_data->protocol == NfcDeviceProtocolMifareClassic || - dev_data->protocol == NfcDeviceProtocolMifareDesfire || - dev_data->protocol == NfcDeviceProtocolMifareUl) { - furi_string_set(temp_str, nfc->dev->dev_data.parsed_data); - } - - widget_add_text_scroll_element(nfc->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - widget_add_button_element( - nfc->widget, GuiButtonTypeRight, "More", nfc_scene_device_info_widget_callback, nfc); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_device_info_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeRight) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcDataInfo); - consumed = true; - } - } - return consumed; -} - -void nfc_scene_device_info_on_exit(void* context) { - Nfc* nfc = context; - - // Clear views - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_dict_not_found.c b/applications/main/nfc/scenes/nfc_scene_dict_not_found.c deleted file mode 100644 index 781c5a932..000000000 --- a/applications/main/nfc/scenes/nfc_scene_dict_not_found.c +++ /dev/null @@ -1,52 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_dict_not_found_popup_callback(void* context) { - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -void nfc_scene_dict_not_found_on_enter(void* context) { - Nfc* nfc = context; - - // Setup view - Popup* popup = nfc->popup; - popup_set_text( - popup, - "Function requires\nan SD card with\nfresh databases.", - 82, - 24, - AlignCenter, - AlignCenter); - popup_set_icon(popup, 6, 10, &I_SDQuestion_35x43); - popup_set_timeout(popup, 2500); - popup_set_context(popup, nfc); - popup_set_callback(popup, nfc_scene_dict_not_found_popup_callback); - popup_enable_timeout(popup); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); -} - -bool nfc_scene_dict_not_found_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventViewExit) { - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneMfClassicKeys)) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneMfClassicKeys); - } else if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneExtraActions)) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneExtraActions); - } else { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneStart); - } - } - } - return consumed; -} - -void nfc_scene_dict_not_found_on_exit(void* context) { - Nfc* nfc = context; - popup_reset(nfc->popup); -} diff --git a/applications/main/nfc/scenes/nfc_scene_emulate.c b/applications/main/nfc/scenes/nfc_scene_emulate.c new file mode 100644 index 000000000..6f217f315 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_emulate.c @@ -0,0 +1,13 @@ +#include "../helpers/protocol_support/nfc_protocol_support.h" + +void nfc_scene_emulate_on_enter(void* context) { + nfc_protocol_support_on_enter(NfcProtocolSupportSceneEmulate, context); +} + +bool nfc_scene_emulate_on_event(void* context, SceneManagerEvent event) { + return nfc_protocol_support_on_event(NfcProtocolSupportSceneEmulate, context, event); +} + +void nfc_scene_emulate_on_exit(void* context) { + nfc_protocol_support_on_exit(NfcProtocolSupportSceneEmulate, context); +} diff --git a/applications/main/nfc/scenes/nfc_scene_emulate_apdu_sequence.c b/applications/main/nfc/scenes/nfc_scene_emulate_apdu_sequence.c deleted file mode 100644 index 358ad2ab6..000000000 --- a/applications/main/nfc/scenes/nfc_scene_emulate_apdu_sequence.c +++ /dev/null @@ -1,34 +0,0 @@ -#include "../nfc_i.h" -#include - -void nfc_scene_emulate_apdu_sequence_on_enter(void* context) { - Nfc* nfc = context; - - // Setup view - Popup* popup = nfc->popup; - popup_set_header(popup, "Run APDU reader", 64, 31, AlignCenter, AlignTop); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - nfc_worker_start(nfc->worker, NfcWorkerStateEmulateApdu, &nfc->dev->dev_data, NULL, nfc); - - nfc_blink_emulate_start(nfc); -} - -bool nfc_scene_emulate_apdu_sequence_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - bool consumed = false; - return consumed; -} - -void nfc_scene_emulate_apdu_sequence_on_exit(void* context) { - Nfc* nfc = context; - - // Stop worker - nfc_worker_stop(nfc->worker); - // Clear view - popup_reset(nfc->popup); - - nfc_blink_stop(nfc); -} diff --git a/applications/main/nfc/scenes/nfc_scene_emulate_uid.c b/applications/main/nfc/scenes/nfc_scene_emulate_uid.c deleted file mode 100644 index 7316eebe0..000000000 --- a/applications/main/nfc/scenes/nfc_scene_emulate_uid.c +++ /dev/null @@ -1,144 +0,0 @@ -#include "../nfc_i.h" - -#define NFC_SCENE_EMULATE_UID_LOG_SIZE_MAX (200) - -enum { - NfcSceneEmulateUidStateWidget, - NfcSceneEmulateUidStateTextBox, -}; - -bool nfc_emulate_uid_worker_callback(NfcWorkerEvent event, void* context) { - UNUSED(event); - furi_assert(context); - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventWorkerExit); - return true; -} - -void nfc_scene_emulate_uid_widget_callback(GuiButtonType result, InputType type, void* context) { - furi_assert(context); - Nfc* nfc = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_emulate_uid_textbox_callback(void* context) { - furi_assert(context); - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -// Add widget with device name or inform that data received -static void nfc_scene_emulate_uid_widget_config(Nfc* nfc, bool data_received) { - FuriHalNfcDevData* data = &nfc->dev->dev_data.nfc_data; - Widget* widget = nfc->widget; - widget_reset(widget); - FuriString* info_str; - info_str = furi_string_alloc(); - - widget_add_icon_element(widget, 0, 3, &I_NFC_dolphin_emulation_47x61); - widget_add_string_element(widget, 57, 13, AlignLeft, AlignTop, FontPrimary, "Emulating UID"); - if(strcmp(nfc->dev->dev_name, "") != 0) { - furi_string_printf(info_str, "%s", nfc->dev->dev_name); - } else { - for(uint8_t i = 0; i < data->uid_len; i++) { - furi_string_cat_printf(info_str, "%02X ", data->uid[i]); - } - } - furi_string_trim(info_str); - widget_add_text_box_element( - widget, 57, 28, 67, 25, AlignCenter, AlignTop, furi_string_get_cstr(info_str), true); - furi_string_free(info_str); - if(data_received) { - widget_add_button_element( - widget, GuiButtonTypeCenter, "Log", nfc_scene_emulate_uid_widget_callback, nfc); - } -} - -void nfc_scene_emulate_uid_on_enter(void* context) { - Nfc* nfc = context; - - // Setup Widget - nfc_scene_emulate_uid_widget_config(nfc, false); - // Setup TextBox - TextBox* text_box = nfc->text_box; - text_box_set_font(text_box, TextBoxFontHex); - text_box_set_focus(text_box, TextBoxFocusEnd); - furi_string_reset(nfc->text_box_store); - - // Set Widget state and view - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneEmulateUid, NfcSceneEmulateUidStateWidget); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - // Start worker - memset(&nfc->dev->dev_data.reader_data, 0, sizeof(NfcReaderRequestData)); - nfc_worker_start( - nfc->worker, - NfcWorkerStateUidEmulate, - &nfc->dev->dev_data, - nfc_emulate_uid_worker_callback, - nfc); - - nfc_blink_emulate_start(nfc); -} - -bool nfc_scene_emulate_uid_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - NfcReaderRequestData* reader_data = &nfc->dev->dev_data.reader_data; - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneEmulateUid); - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventWorkerExit) { - // Add data button to widget if data is received for the first time - if(!furi_string_size(nfc->text_box_store)) { - nfc_scene_emulate_uid_widget_config(nfc, true); - } - // Update TextBox data - if(furi_string_size(nfc->text_box_store) < NFC_SCENE_EMULATE_UID_LOG_SIZE_MAX) { - furi_string_cat_printf(nfc->text_box_store, "R:"); - for(uint16_t i = 0; i < reader_data->size; i++) { - furi_string_cat_printf(nfc->text_box_store, " %02X", reader_data->data[i]); - } - furi_string_push_back(nfc->text_box_store, '\n'); - text_box_set_text(nfc->text_box, furi_string_get_cstr(nfc->text_box_store)); - } - memset(reader_data, 0, sizeof(NfcReaderRequestData)); - consumed = true; - } else if(event.event == GuiButtonTypeCenter && state == NfcSceneEmulateUidStateWidget) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewTextBox); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneEmulateUid, NfcSceneEmulateUidStateTextBox); - consumed = true; - } else if(event.event == NfcCustomEventViewExit && state == NfcSceneEmulateUidStateTextBox) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneEmulateUid, NfcSceneEmulateUidStateWidget); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - if(state == NfcSceneEmulateUidStateTextBox) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneEmulateUid, NfcSceneEmulateUidStateWidget); - consumed = true; - } - } - - return consumed; -} - -void nfc_scene_emulate_uid_on_exit(void* context) { - Nfc* nfc = context; - - // Stop worker - nfc_worker_stop(nfc->worker); - - // Clear view - widget_reset(nfc->widget); - text_box_reset(nfc->text_box); - furi_string_reset(nfc->text_box_store); - - nfc_blink_stop(nfc); -} diff --git a/applications/main/nfc/scenes/nfc_scene_emv_menu.c b/applications/main/nfc/scenes/nfc_scene_emv_menu.c deleted file mode 100644 index 1da630fcf..000000000 --- a/applications/main/nfc/scenes/nfc_scene_emv_menu.c +++ /dev/null @@ -1,54 +0,0 @@ -#include "../nfc_i.h" - -enum SubmenuIndex { - SubmenuIndexSave, - SubmenuIndexInfo, -}; - -void nfc_scene_emv_menu_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_emv_menu_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - - submenu_add_item(submenu, "Save", SubmenuIndexSave, nfc_scene_emv_menu_submenu_callback, nfc); - submenu_add_item(submenu, "Info", SubmenuIndexInfo, nfc_scene_emv_menu_submenu_callback, nfc); - submenu_set_selected_item( - nfc->submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneEmvMenu)); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_emv_menu_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexSave) { - nfc->dev->format = NfcDeviceSaveFormatBankCard; - // Clear device name - nfc_device_set_name(nfc->dev, ""); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); - consumed = true; - } else if(event.event == SubmenuIndexInfo) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcDataInfo); - consumed = true; - } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneEmvMenu, event.event); - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_previous_scene(nfc->scene_manager); - } - - return consumed; -} - -void nfc_scene_emv_menu_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_emv_read_success.c b/applications/main/nfc/scenes/nfc_scene_emv_read_success.c deleted file mode 100644 index 005b76cb2..000000000 --- a/applications/main/nfc/scenes/nfc_scene_emv_read_success.c +++ /dev/null @@ -1,113 +0,0 @@ -#include "../nfc_i.h" -#include "../helpers/nfc_emv_parser.h" - -void nfc_scene_emv_read_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - Nfc* nfc = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_emv_read_success_on_enter(void* context) { - Nfc* nfc = context; - EmvData* emv_data = &nfc->dev->dev_data.emv_data; - - // Setup Custom Widget view - widget_add_button_element( - nfc->widget, GuiButtonTypeLeft, "Retry", nfc_scene_emv_read_success_widget_callback, nfc); - widget_add_button_element( - nfc->widget, GuiButtonTypeRight, "More", nfc_scene_emv_read_success_widget_callback, nfc); - - FuriString* temp_str; - if(emv_data->name[0] != '\0') { - temp_str = furi_string_alloc_printf("\e#%s\n", emv_data->name); - } else { - temp_str = furi_string_alloc_printf("\e#Unknown Bank Card\n"); - } - if(emv_data->number_len) { - for(uint8_t i = 0; i < emv_data->number_len; i += 2) { - furi_string_cat_printf( - temp_str, "%02X%02X ", emv_data->number[i], emv_data->number[i + 1]); - } - furi_string_trim(temp_str); - } else if(emv_data->aid_len) { - furi_string_cat_printf(temp_str, "Can't parse data from app\n"); - // Parse AID name - FuriString* aid_name; - aid_name = furi_string_alloc(); - if(nfc_emv_parser_get_aid_name( - nfc->dev->storage, emv_data->aid, emv_data->aid_len, aid_name)) { - furi_string_cat_printf(temp_str, "AID: %s", furi_string_get_cstr(aid_name)); - } else { - furi_string_cat_printf(temp_str, "AID: "); - for(uint8_t i = 0; i < emv_data->aid_len; i++) { - furi_string_cat_printf(temp_str, "%02X", emv_data->aid[i]); - } - } - furi_string_free(aid_name); - } - - // Add expiration date - if(emv_data->exp_mon) { - furi_string_cat_printf( - temp_str, "\nExp: %02X/%02X", emv_data->exp_mon, emv_data->exp_year); - } - // Parse currency code - if((emv_data->currency_code)) { - FuriString* currency_name; - currency_name = furi_string_alloc(); - if(nfc_emv_parser_get_currency_name( - nfc->dev->storage, emv_data->currency_code, currency_name)) { - furi_string_cat_printf(temp_str, "\nCur: %s ", furi_string_get_cstr(currency_name)); - } - furi_string_free(currency_name); - } - // Parse country code - if((emv_data->country_code)) { - FuriString* country_name; - country_name = furi_string_alloc(); - if(nfc_emv_parser_get_country_name( - nfc->dev->storage, emv_data->country_code, country_name)) { - furi_string_cat_printf(temp_str, "Reg: %s", furi_string_get_cstr(country_name)); - } - furi_string_free(country_name); - } - - notification_message_block(nfc->notifications, &sequence_set_green_255); - - widget_add_text_scroll_element(nfc->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_emv_read_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneRetryConfirm); - consumed = true; - } else if(event.event == GuiButtonTypeRight) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneEmvMenu); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneExitConfirm); - consumed = true; - } - return consumed; -} - -void nfc_scene_emv_read_success_on_exit(void* context) { - Nfc* nfc = context; - - notification_message_block(nfc->notifications, &sequence_reset_green); - - // Clear view - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_exit_confirm.c b/applications/main/nfc/scenes/nfc_scene_exit_confirm.c index 3ce4f6de8..c024d3129 100644 --- a/applications/main/nfc/scenes/nfc_scene_exit_confirm.c +++ b/applications/main/nfc/scenes/nfc_scene_exit_confirm.c @@ -1,13 +1,13 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_exit_confirm_dialog_callback(DialogExResult result, void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, result); } void nfc_scene_exit_confirm_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; DialogEx* dialog_ex = nfc->dialog_ex; dialog_ex_set_left_button_text(dialog_ex, "Exit"); @@ -22,16 +22,16 @@ void nfc_scene_exit_confirm_on_enter(void* context) { } bool nfc_scene_exit_confirm_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == DialogExResultRight) { consumed = scene_manager_previous_scene(nfc->scene_manager); } else if(event.event == DialogExResultLeft) { - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneReadCardType)) { + if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSelectProtocol)) { consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneReadCardType); + nfc->scene_manager, NfcSceneSelectProtocol); } else { consumed = scene_manager_search_and_switch_to_previous_scene( nfc->scene_manager, NfcSceneStart); @@ -45,7 +45,7 @@ bool nfc_scene_exit_confirm_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_exit_confirm_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Clean view dialog_ex_reset(nfc->dialog_ex); diff --git a/applications/main/nfc/scenes/nfc_scene_extra_actions.c b/applications/main/nfc/scenes/nfc_scene_extra_actions.c index 7f5bc7e75..7f51b7174 100644 --- a/applications/main/nfc/scenes/nfc_scene_extra_actions.c +++ b/applications/main/nfc/scenes/nfc_scene_extra_actions.c @@ -1,92 +1,72 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" enum SubmenuIndex { SubmenuIndexReadCardType, SubmenuIndexMfClassicKeys, SubmenuIndexMfUltralightUnlock, - SubmenuIndexNfcVUnlock, - SubmenuIndexNfcVSniff, }; void nfc_scene_extra_actions_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; + NfcApp* instance = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); + view_dispatcher_send_custom_event(instance->view_dispatcher, index); } void nfc_scene_extra_actions_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; + NfcApp* instance = context; + Submenu* submenu = instance->submenu; submenu_add_item( submenu, "Read Specific Card Type", SubmenuIndexReadCardType, nfc_scene_extra_actions_submenu_callback, - nfc); + instance); submenu_add_item( submenu, "Mifare Classic Keys", SubmenuIndexMfClassicKeys, nfc_scene_extra_actions_submenu_callback, - nfc); + instance); submenu_add_item( submenu, "Unlock NTAG/Ultralight", SubmenuIndexMfUltralightUnlock, nfc_scene_extra_actions_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Unlock SLIX-L", - SubmenuIndexNfcVUnlock, - nfc_scene_extra_actions_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Listen NfcV Reader", - SubmenuIndexNfcVSniff, - nfc_scene_extra_actions_submenu_callback, - nfc); + instance); submenu_set_selected_item( - submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneExtraActions)); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); + submenu, scene_manager_get_scene_state(instance->scene_manager, NfcSceneExtraActions)); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewMenu); } bool nfc_scene_extra_actions_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == SubmenuIndexMfClassicKeys) { - if(mf_classic_dict_check_presence(MfClassicDictTypeSystem)) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicKeys); + if(nfc_dict_check_presence(NFC_APP_MF_CLASSIC_DICT_USER_PATH)) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicKeys); } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDictNotFound); + scene_manager_previous_scene(instance->scene_manager); } consumed = true; } else if(event.event == SubmenuIndexMfUltralightUnlock) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightUnlockMenu); + mf_ultralight_auth_reset(instance->mf_ul_auth); + scene_manager_next_scene(instance->scene_manager, NfcSceneMfUltralightUnlockMenu); consumed = true; } else if(event.event == SubmenuIndexReadCardType) { - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneReadCardType, 0); - scene_manager_next_scene(nfc->scene_manager, NfcSceneReadCardType); - consumed = true; - } else if(event.event == SubmenuIndexNfcVUnlock) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVUnlockMenu); - consumed = true; - } else if(event.event == SubmenuIndexNfcVSniff) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVSniff); + scene_manager_next_scene(instance->scene_manager, NfcSceneSelectProtocol); consumed = true; } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneExtraActions, event.event); + scene_manager_set_scene_state(instance->scene_manager, NfcSceneExtraActions, event.event); } return consumed; } void nfc_scene_extra_actions_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; - submenu_reset(nfc->submenu); + submenu_reset(instance->submenu); } diff --git a/applications/main/nfc/scenes/nfc_scene_field.c b/applications/main/nfc/scenes/nfc_scene_field.c index e3eb6a708..d5eb916a8 100644 --- a/applications/main/nfc/scenes/nfc_scene_field.c +++ b/applications/main/nfc/scenes/nfc_scene_field.c @@ -1,10 +1,10 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_field_on_enter(void* context) { - Nfc* nfc = context; - - furi_hal_nfc_field_on(); + NfcApp* nfc = context; + furi_hal_nfc_low_power_mode_stop(); + furi_hal_nfc_poller_field_on(); Popup* popup = nfc->popup; popup_set_header( popup, @@ -25,9 +25,9 @@ bool nfc_scene_field_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_field_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; - furi_hal_nfc_field_off(); + furi_hal_nfc_low_power_mode_start(); notification_internal_message(nfc->notifications, &sequence_reset_blue); popup_reset(nfc->popup); } diff --git a/applications/main/nfc/scenes/nfc_scene_file_select.c b/applications/main/nfc/scenes/nfc_scene_file_select.c index ce7ec92f4..e1edcadb1 100644 --- a/applications/main/nfc/scenes/nfc_scene_file_select.c +++ b/applications/main/nfc/scenes/nfc_scene_file_select.c @@ -1,28 +1,20 @@ -#include "../nfc_i.h" -#include "nfc/nfc_device.h" +#include "../nfc_app_i.h" void nfc_scene_file_select_on_enter(void* context) { - Nfc* nfc = context; - nfc_device_data_clear(&nfc->dev->dev_data); + NfcApp* instance = context; - // Process file_select return - nfc_device_set_loading_callback(nfc->dev, nfc_show_loading_popup, nfc); - if(!furi_string_size(nfc->dev->load_path)) { - furi_string_set_str(nfc->dev->load_path, NFC_APP_FOLDER); - } - if(nfc_file_select(nfc->dev)) { - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneSavedMenu, 0); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSavedMenu); + if(nfc_load_from_file_select(instance)) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSavedMenu); } else { - scene_manager_search_and_switch_to_previous_scene(nfc->scene_manager, NfcSceneStart); + scene_manager_previous_scene(instance->scene_manager); } - nfc_device_set_loading_callback(nfc->dev, NULL, nfc); } bool nfc_scene_file_select_on_event(void* context, SceneManagerEvent event) { UNUSED(context); UNUSED(event); - return false; + bool consumed = false; + return consumed; } void nfc_scene_file_select_on_exit(void* context) { diff --git a/applications/main/nfc/scenes/nfc_scene_generate_info.c b/applications/main/nfc/scenes/nfc_scene_generate_info.c index 7b84ae43b..c4f86ff4a 100644 --- a/applications/main/nfc/scenes/nfc_scene_generate_info.c +++ b/applications/main/nfc/scenes/nfc_scene_generate_info.c @@ -1,50 +1,55 @@ -#include "../nfc_i.h" -#include "lib/nfc/helpers/nfc_generators.h" +#include "../nfc_app_i.h" -void nfc_scene_generate_info_dialog_callback(DialogExResult result, void* context) { - Nfc* nfc = context; +void nfc_scene_generate_info_widget_callback(GuiButtonType result, InputType type, void* context) { + NfcApp* instance = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); + if(type == InputTypeShort) { + if(result == GuiButtonTypeRight) { + view_dispatcher_send_custom_event(instance->view_dispatcher, result); + } + } } void nfc_scene_generate_info_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; + + NfcProtocol protocol = nfc_device_get_protocol(instance->nfc_device); + furi_assert((protocol == NfcProtocolMfUltralight) || (protocol == NfcProtocolMfClassic)); + + const Iso14443_3aData* iso14443_3a_data = + nfc_device_get_data(instance->nfc_device, NfcProtocolIso14443_3a); // Setup dialog view - FuriHalNfcDevData* data = &nfc->dev->dev_data.nfc_data; - DialogEx* dialog_ex = nfc->dialog_ex; - dialog_ex_set_right_button_text(dialog_ex, "More"); + Widget* widget = instance->widget; + widget_add_button_element( + widget, GuiButtonTypeRight, "More", nfc_scene_generate_info_widget_callback, instance); // Create info text - FuriString* info_str = furi_string_alloc_printf( - "%s\n%s\nUID:", nfc->generator->name, nfc_get_dev_type(data->type)); + NfcDataGeneratorType type = + scene_manager_get_scene_state(instance->scene_manager, NfcSceneGenerateInfo); + const char* name = nfc_data_generator_get_name(type); + widget_add_string_element(widget, 0, 0, AlignLeft, AlignTop, FontPrimary, name); + widget_add_string_element(widget, 0, 13, AlignLeft, AlignTop, FontSecondary, "NFC-A"); + FuriString* temp_str = furi_string_alloc_printf("UID:"); // Append UID - for(int i = 0; i < data->uid_len; ++i) { - furi_string_cat_printf(info_str, " %02X", data->uid[i]); + for(int i = 0; i < iso14443_3a_data->uid_len; i++) { + furi_string_cat_printf(temp_str, " %02X", iso14443_3a_data->uid[i]); } - nfc_text_store_set(nfc, furi_string_get_cstr(info_str)); - furi_string_free(info_str); + widget_add_string_element( + widget, 0, 25, AlignLeft, AlignTop, FontSecondary, furi_string_get_cstr(temp_str)); + furi_string_free(temp_str); - dialog_ex_set_text(dialog_ex, nfc->text_store, 0, 0, AlignLeft, AlignTop); - dialog_ex_set_context(dialog_ex, nfc); - dialog_ex_set_result_callback(dialog_ex, nfc_scene_generate_info_dialog_callback); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewDialogEx); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); } bool nfc_scene_generate_info_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { - if(event.event == DialogExResultRight) { - // Switch either to NfcSceneMfClassicMenu or NfcSceneMfUltralightMenu - if(nfc->dev->dev_data.protocol == NfcDeviceProtocolMifareClassic) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicMenu); - } else if(nfc->dev->dev_data.protocol == NfcDeviceProtocolMifareUl) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightMenu); - } + if(event.event == GuiButtonTypeRight) { + scene_manager_next_scene(instance->scene_manager, NfcSceneReadMenu); consumed = true; } } @@ -53,8 +58,8 @@ bool nfc_scene_generate_info_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_generate_info_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; // Clean views - dialog_ex_reset(nfc->dialog_ex); + widget_reset(instance->widget); } diff --git a/applications/main/nfc/scenes/nfc_scene_info.c b/applications/main/nfc/scenes/nfc_scene_info.c new file mode 100644 index 000000000..6e9d50497 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_info.c @@ -0,0 +1,13 @@ +#include "../helpers/protocol_support/nfc_protocol_support.h" + +void nfc_scene_info_on_enter(void* context) { + nfc_protocol_support_on_enter(NfcProtocolSupportSceneInfo, context); +} + +bool nfc_scene_info_on_event(void* context, SceneManagerEvent event) { + return nfc_protocol_support_on_event(NfcProtocolSupportSceneInfo, context, event); +} + +void nfc_scene_info_on_exit(void* context) { + nfc_protocol_support_on_exit(NfcProtocolSupportSceneInfo, context); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_data.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_data.c deleted file mode 100644 index dcb02d364..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_data.c +++ /dev/null @@ -1,106 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_mf_classic_data_on_enter(void* context) { - Nfc* nfc = context; - MfClassicType type = nfc->dev->dev_data.mf_classic_data.type; - MfClassicData* data = &nfc->dev->dev_data.mf_classic_data; - TextBox* text_box = nfc->text_box; - - text_box_set_font(text_box, TextBoxFontHex); - - int card_blocks = 0; - if(type == MfClassicType1k) { - card_blocks = MF_CLASSIC_1K_TOTAL_SECTORS_NUM * 4; - } else if(type == MfClassicType4k) { - // 16 sectors of 4 blocks each plus 8 sectors of 16 blocks each - card_blocks = MF_CLASSIC_1K_TOTAL_SECTORS_NUM * 4 + 8 * 16; - } else if(type == MfClassicTypeMini) { - card_blocks = MF_MINI_TOTAL_SECTORS_NUM * 4; - } - - int bytes_written = 0; - for(int block_num = 0; block_num < card_blocks; block_num++) { - bool is_sec_trailer = mf_classic_is_sector_trailer(block_num); - if(is_sec_trailer) { - uint8_t sector_num = mf_classic_get_sector_by_block(block_num); - MfClassicSectorTrailer* sec_tr = - mf_classic_get_sector_trailer_by_sector(data, sector_num); - // Key A - for(size_t i = 0; i < sizeof(sec_tr->key_a); i += 2) { - if((bytes_written % 8 == 0) && (bytes_written != 0)) { - furi_string_push_back(nfc->text_box_store, '\n'); - } - if(mf_classic_is_key_found(data, sector_num, MfClassicKeyA)) { - furi_string_cat_printf( - nfc->text_box_store, "%02X%02X ", sec_tr->key_a[i], sec_tr->key_a[i + 1]); - } else { - furi_string_cat_printf(nfc->text_box_store, "???? "); - } - bytes_written += 2; - } - // Access bytes - for(size_t i = 0; i < MF_CLASSIC_ACCESS_BYTES_SIZE; i += 2) { - if((bytes_written % 8 == 0) && (bytes_written != 0)) { - furi_string_push_back(nfc->text_box_store, '\n'); - } - if(mf_classic_is_block_read(data, block_num)) { - furi_string_cat_printf( - nfc->text_box_store, - "%02X%02X ", - sec_tr->access_bits[i], - sec_tr->access_bits[i + 1]); - } else { - furi_string_cat_printf(nfc->text_box_store, "???? "); - } - bytes_written += 2; - } - // Key B - for(size_t i = 0; i < sizeof(sec_tr->key_b); i += 2) { - if((bytes_written % 8 == 0) && (bytes_written != 0)) { - furi_string_push_back(nfc->text_box_store, '\n'); - } - if(mf_classic_is_key_found(data, sector_num, MfClassicKeyB)) { - furi_string_cat_printf( - nfc->text_box_store, "%02X%02X ", sec_tr->key_b[i], sec_tr->key_b[i + 1]); - } else { - furi_string_cat_printf(nfc->text_box_store, "???? "); - } - bytes_written += 2; - } - } else { - // Write data block - for(size_t i = 0; i < MF_CLASSIC_BLOCK_SIZE; i += 2) { - if((bytes_written % 8 == 0) && (bytes_written != 0)) { - furi_string_push_back(nfc->text_box_store, '\n'); - } - if(mf_classic_is_block_read(data, block_num)) { - furi_string_cat_printf( - nfc->text_box_store, - "%02X%02X ", - data->block[block_num].value[i], - data->block[block_num].value[i + 1]); - } else { - furi_string_cat_printf(nfc->text_box_store, "???? "); - } - bytes_written += 2; - } - } - } - text_box_set_text(text_box, furi_string_get_cstr(nfc->text_box_store)); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewTextBox); -} - -bool nfc_scene_mf_classic_data_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void nfc_scene_mf_classic_data_on_exit(void* context) { - Nfc* nfc = context; - - // Clean view - text_box_reset(nfc->text_box); - furi_string_reset(nfc->text_box_store); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_detect_reader.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_detect_reader.c new file mode 100644 index 000000000..987f81837 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_detect_reader.c @@ -0,0 +1,154 @@ +#include "../nfc_app_i.h" + +#include + +#define NXP_MANUFACTURER_ID (0x04) + +#define NFC_SCENE_DETECT_READER_PAIR_NONCES_MAX (10U) +#define NFC_SCENE_DETECT_READER_WAIT_NONCES_TIMEOUT_MS (1000) + +static const NotificationSequence sequence_detect_reader = { + &message_green_255, + &message_blue_255, + &message_do_not_reset, + NULL, +}; + +void nfc_scene_mf_classic_detect_reader_view_callback(void* context) { + NfcApp* instance = context; + + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventViewExit); +} + +NfcCommand nfc_scene_mf_classic_detect_listener_callback(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolMfClassic); + + NfcApp* instance = context; + MfClassicListenerEvent* mfc_event = event.event_data; + + if(mfc_event->type == MfClassicListenerEventTypeAuthContextPartCollected) { + MfClassicAuthContext* auth_ctx = &mfc_event->data->auth_context; + mfkey32_logger_add_nonce(instance->mfkey32_logger, auth_ctx); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventWorkerUpdate); + } + + return NfcCommandContinue; +} + +void nfc_scene_mf_classic_timer_callback(void* context) { + NfcApp* instance = context; + + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventTimerExpired); +} + +void nfc_scene_mf_classic_detect_reader_on_enter(void* context) { + NfcApp* instance = context; + + if(nfc_device_get_protocol(instance->nfc_device) == NfcProtocolInvalid) { + Iso14443_3aData iso3_data = { + .uid_len = 7, + .uid = {0}, + .atqa = {0x44, 0x00}, + .sak = 0x08, + }; + iso3_data.uid[0] = NXP_MANUFACTURER_ID; + furi_hal_random_fill_buf(&iso3_data.uid[1], iso3_data.uid_len - 1); + MfClassicData* mfc_data = mf_classic_alloc(); + + mfc_data->type = MfClassicType4k; + iso14443_3a_copy(mfc_data->iso14443_3a_data, &iso3_data); + nfc_device_set_data(instance->nfc_device, NfcProtocolMfClassic, mfc_data); + + mf_classic_free(mfc_data); + } + + const Iso14443_3aData* iso3_data = + nfc_device_get_data(instance->nfc_device, NfcProtocolIso14443_3a); + uint32_t cuid = iso14443_3a_get_cuid(iso3_data); + + instance->mfkey32_logger = mfkey32_logger_alloc(cuid); + instance->timer = + furi_timer_alloc(nfc_scene_mf_classic_timer_callback, FuriTimerTypeOnce, instance); + + detect_reader_set_nonces_max(instance->detect_reader, NFC_SCENE_DETECT_READER_PAIR_NONCES_MAX); + detect_reader_set_callback( + instance->detect_reader, nfc_scene_mf_classic_detect_reader_view_callback, instance); + + notification_message(instance->notifications, &sequence_detect_reader); + + instance->listener = nfc_listener_alloc( + instance->nfc, + NfcProtocolMfClassic, + nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic)); + nfc_listener_start( + instance->listener, nfc_scene_mf_classic_detect_listener_callback, instance); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewDetectReader); +} + +bool nfc_scene_mf_classic_detect_reader_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventWorkerUpdate) { + furi_timer_stop(instance->timer); + notification_message(instance->notifications, &sequence_blink_start_cyan); + + size_t nonces_pairs = 2 * mfkey32_logger_get_params_num(instance->mfkey32_logger); + detect_reader_set_state(instance->detect_reader, DetectReaderStateReaderDetected); + detect_reader_set_nonces_collected(instance->detect_reader, nonces_pairs); + if(nonces_pairs >= NFC_SCENE_DETECT_READER_PAIR_NONCES_MAX) { + if(instance->listener) { + nfc_listener_stop(instance->listener); + nfc_listener_free(instance->listener); + instance->listener = NULL; + } + detect_reader_set_state(instance->detect_reader, DetectReaderStateDone); + nfc_blink_stop(instance); + notification_message(instance->notifications, &sequence_single_vibro); + notification_message(instance->notifications, &sequence_set_green_255); + } else { + furi_timer_start(instance->timer, NFC_SCENE_DETECT_READER_WAIT_NONCES_TIMEOUT_MS); + } + consumed = true; + } else if(event.event == NfcCustomEventTimerExpired) { + detect_reader_set_state(instance->detect_reader, DetectReaderStateReaderLost); + nfc_blink_stop(instance); + notification_message(instance->notifications, &sequence_detect_reader); + } else if(event.event == NfcCustomEventViewExit) { + if(instance->listener) { + nfc_listener_stop(instance->listener); + nfc_listener_free(instance->listener); + instance->listener = NULL; + } + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicMfkeyNoncesInfo); + consumed = true; + } + } else if(event.type == SceneManagerEventTypeBack) { + if(instance->listener) { + nfc_listener_stop(instance->listener); + nfc_listener_free(instance->listener); + instance->listener = NULL; + } + mfkey32_logger_free(instance->mfkey32_logger); + } + + return consumed; +} + +void nfc_scene_mf_classic_detect_reader_on_exit(void* context) { + NfcApp* instance = context; + + // Clear view + detect_reader_reset(instance->detect_reader); + + furi_timer_stop(instance->timer); + furi_timer_free(instance->timer); + + // Stop notifications + nfc_blink_stop(instance); + notification_message(instance->notifications, &sequence_reset_green); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_dict_attack.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_dict_attack.c index 5bd24d7ea..ff7af9e1e 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_dict_attack.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_dict_attack.c @@ -1,186 +1,270 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" + #include +#include #define TAG "NfcMfClassicDictAttack" typedef enum { - DictAttackStateIdle, DictAttackStateUserDictInProgress, - DictAttackStateFlipperDictInProgress, + DictAttackStateSystemDictInProgress, } DictAttackState; -bool nfc_dict_attack_worker_callback(NfcWorkerEvent event, void* context) { +NfcCommand nfc_dict_attack_worker_callback(NfcGenericEvent event, void* context) { furi_assert(context); - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, event); - return true; -} + furi_assert(event.event_data); + furi_assert(event.instance); + furi_assert(event.protocol == NfcProtocolMfClassic); -void nfc_dict_attack_dict_attack_result_callback(void* context) { - furi_assert(context); - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventDictAttackSkip); -} + NfcCommand command = NfcCommandContinue; + MfClassicPollerEvent* mfc_event = event.event_data; -static void nfc_scene_mf_classic_dict_attack_update_view(Nfc* nfc) { - MfClassicData* data = &nfc->dev->dev_data.mf_classic_data; - uint8_t sectors_read = 0; - uint8_t keys_found = 0; - - // Calculate found keys and read sectors - mf_classic_get_read_sectors_and_keys(data, §ors_read, &keys_found); - dict_attack_set_keys_found(nfc->dict_attack, keys_found); - dict_attack_set_sector_read(nfc->dict_attack, sectors_read); -} - -static void nfc_scene_mf_classic_dict_attack_prepare_view(Nfc* nfc, DictAttackState state) { - MfClassicData* data = &nfc->dev->dev_data.mf_classic_data; - NfcMfClassicDictAttackData* dict_attack_data = &nfc->dev->dev_data.mf_classic_dict_attack_data; - NfcWorkerState worker_state = NfcWorkerStateReady; - MfClassicDict* dict = NULL; - - // Identify scene state - if(state == DictAttackStateIdle) { - if(mf_classic_dict_check_presence(MfClassicDictTypeUser)) { - state = DictAttackStateUserDictInProgress; + NfcApp* instance = context; + if(mfc_event->type == MfClassicPollerEventTypeCardDetected) { + instance->nfc_dict_context.is_card_present = true; + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventCardDetected); + } else if(mfc_event->type == MfClassicPollerEventTypeCardLost) { + instance->nfc_dict_context.is_card_present = false; + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventCardLost); + } else if(mfc_event->type == MfClassicPollerEventTypeRequestMode) { + const MfClassicData* mfc_data = + nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic); + mfc_event->data->poller_mode.mode = MfClassicPollerModeDictAttack; + mfc_event->data->poller_mode.data = mfc_data; + instance->nfc_dict_context.sectors_total = + mf_classic_get_total_sectors_num(mfc_data->type); + mf_classic_get_read_sectors_and_keys( + mfc_data, + &instance->nfc_dict_context.sectors_read, + &instance->nfc_dict_context.keys_found); + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventDictAttackDataUpdate); + } else if(mfc_event->type == MfClassicPollerEventTypeRequestKey) { + MfClassicKey key = {}; + if(nfc_dict_get_next_key(instance->nfc_dict_context.dict, key.data, sizeof(MfClassicKey))) { + mfc_event->data->key_request_data.key = key; + mfc_event->data->key_request_data.key_provided = true; + instance->nfc_dict_context.dict_keys_current++; + if(instance->nfc_dict_context.dict_keys_current % 10 == 0) { + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventDictAttackDataUpdate); + } } else { - state = DictAttackStateFlipperDictInProgress; + mfc_event->data->key_request_data.key_provided = false; } - } else if(state == DictAttackStateUserDictInProgress) { - state = DictAttackStateFlipperDictInProgress; + } else if(mfc_event->type == MfClassicPollerEventTypeDataUpdate) { + MfClassicPollerEventDataUpdate* data_update = &mfc_event->data->data_update; + instance->nfc_dict_context.sectors_read = data_update->sectors_read; + instance->nfc_dict_context.keys_found = data_update->keys_found; + instance->nfc_dict_context.current_sector = data_update->current_sector; + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventDictAttackDataUpdate); + } else if(mfc_event->type == MfClassicPollerEventTypeNextSector) { + nfc_dict_rewind(instance->nfc_dict_context.dict); + instance->nfc_dict_context.dict_keys_current = 0; + instance->nfc_dict_context.current_sector = + mfc_event->data->next_sector_data.current_sector; + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventDictAttackDataUpdate); + } else if(mfc_event->type == MfClassicPollerEventTypeFoundKeyA) { + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventDictAttackDataUpdate); + } else if(mfc_event->type == MfClassicPollerEventTypeFoundKeyB) { + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventDictAttackDataUpdate); + } else if(mfc_event->type == MfClassicPollerEventTypeKeyAttackStart) { + instance->nfc_dict_context.key_attack_current_sector = + mfc_event->data->key_attack_data.current_sector; + instance->nfc_dict_context.is_key_attack = true; + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventDictAttackDataUpdate); + } else if(mfc_event->type == MfClassicPollerEventTypeKeyAttackStop) { + nfc_dict_rewind(instance->nfc_dict_context.dict); + instance->nfc_dict_context.is_key_attack = false; + instance->nfc_dict_context.dict_keys_current = 0; + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventDictAttackDataUpdate); + } else if(mfc_event->type == MfClassicPollerEventTypeSuccess) { + const MfClassicData* mfc_data = nfc_poller_get_data(instance->poller); + nfc_device_set_data(instance->nfc_device, NfcProtocolMfClassic, mfc_data); + view_dispatcher_send_custom_event( + instance->view_dispatcher, NfcCustomEventDictAttackComplete); + command = NfcCommandStop; } - // Setup view + return command; +} + +void nfc_dict_attack_dict_attack_result_callback(DictAttackEvent event, void* context) { + furi_assert(context); + NfcApp* instance = context; + + if(event == DictAttackEventSkipPressed) { + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventDictAttackSkip); + } +} + +static void nfc_scene_mf_classic_dict_attack_update_view(NfcApp* instance) { + NfcMfClassicDictAttackContext* mfc_dict = &instance->nfc_dict_context; + + if(mfc_dict->is_key_attack) { + dict_attack_set_key_attack(instance->dict_attack, mfc_dict->key_attack_current_sector); + } else { + dict_attack_reset_key_attack(instance->dict_attack); + dict_attack_set_sectors_total(instance->dict_attack, mfc_dict->sectors_total); + dict_attack_set_sectors_read(instance->dict_attack, mfc_dict->sectors_read); + dict_attack_set_keys_found(instance->dict_attack, mfc_dict->keys_found); + dict_attack_set_current_dict_key(instance->dict_attack, mfc_dict->dict_keys_current); + dict_attack_set_current_sector(instance->dict_attack, mfc_dict->current_sector); + } +} + +static void nfc_scene_mf_classic_dict_attack_prepare_view(NfcApp* instance) { + uint32_t state = + scene_manager_get_scene_state(instance->scene_manager, NfcSceneMfClassicDictAttack); if(state == DictAttackStateUserDictInProgress) { - worker_state = NfcWorkerStateMfClassicDictAttack; - dict_attack_set_header(nfc->dict_attack, "MF Classic User Dictionary"); - dict = mf_classic_dict_alloc(MfClassicDictTypeUser); + do { + if(!nfc_dict_check_presence(NFC_APP_MF_CLASSIC_DICT_USER_PATH)) { + state = DictAttackStateSystemDictInProgress; + break; + } - // If failed to load user dictionary - try the system dictionary - if(!dict) { - FURI_LOG_E(TAG, "User dictionary not found"); - state = DictAttackStateFlipperDictInProgress; - } + instance->nfc_dict_context.dict = nfc_dict_alloc( + NFC_APP_MF_CLASSIC_DICT_USER_PATH, NfcDictModeOpenAlways, sizeof(MfClassicKey)); + if(nfc_dict_get_total_keys(instance->nfc_dict_context.dict) == 0) { + nfc_dict_free(instance->nfc_dict_context.dict); + state = DictAttackStateSystemDictInProgress; + break; + } + + dict_attack_set_header(instance->dict_attack, "MF Classic User Dictionary"); + } while(false); } - if(state == DictAttackStateFlipperDictInProgress) { - worker_state = NfcWorkerStateMfClassicDictAttack; - dict_attack_set_header(nfc->dict_attack, "MF Classic System Dictionary"); - dict = mf_classic_dict_alloc(MfClassicDictTypeSystem); - if(!dict) { - FURI_LOG_E(TAG, "Flipper dictionary not found"); - // Pass through to let the worker handle the failure - } + if(state == DictAttackStateSystemDictInProgress) { + instance->nfc_dict_context.dict = nfc_dict_alloc( + NFC_APP_MF_CLASSIC_DICT_SYSTEM_PATH, NfcDictModeOpenExisting, sizeof(MfClassicKey)); + dict_attack_set_header(instance->dict_attack, "MF Classic System Dictionary"); } - // Free previous dictionary - if(dict_attack_data->dict) { - mf_classic_dict_free(dict_attack_data->dict); - } - dict_attack_data->dict = dict; - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneMfClassicDictAttack, state); - dict_attack_set_callback(nfc->dict_attack, nfc_dict_attack_dict_attack_result_callback, nfc); - dict_attack_set_current_sector(nfc->dict_attack, 0); - dict_attack_set_card_detected(nfc->dict_attack, data->type); + + instance->nfc_dict_context.dict_keys_total = + nfc_dict_get_total_keys(instance->nfc_dict_context.dict); dict_attack_set_total_dict_keys( - nfc->dict_attack, dict ? mf_classic_dict_get_total_keys(dict) : 0); - nfc_scene_mf_classic_dict_attack_update_view(nfc); - nfc_worker_start( - nfc->worker, worker_state, &nfc->dev->dev_data, nfc_dict_attack_worker_callback, nfc); + instance->dict_attack, instance->nfc_dict_context.dict_keys_total); + instance->nfc_dict_context.dict_keys_current = 0; + + dict_attack_set_callback( + instance->dict_attack, nfc_dict_attack_dict_attack_result_callback, instance); + nfc_scene_mf_classic_dict_attack_update_view(instance); + + scene_manager_set_scene_state(instance->scene_manager, NfcSceneMfClassicDictAttack, state); } void nfc_scene_mf_classic_dict_attack_on_enter(void* context) { - Nfc* nfc = context; - nfc_scene_mf_classic_dict_attack_prepare_view(nfc, DictAttackStateIdle); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewDictAttack); - nfc_blink_read_start(nfc); - notification_message(nfc->notifications, &sequence_display_backlight_enforce_on); + NfcApp* instance = context; + + scene_manager_set_scene_state( + instance->scene_manager, NfcSceneMfClassicDictAttack, DictAttackStateUserDictInProgress); + nfc_scene_mf_classic_dict_attack_prepare_view(instance); + dict_attack_set_card_state(instance->dict_attack, true); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewDictAttack); + nfc_blink_read_start(instance); + notification_message(instance->notifications, &sequence_display_backlight_enforce_on); + + instance->poller = nfc_poller_alloc(instance->nfc, NfcProtocolMfClassic); + nfc_poller_start(instance->poller, nfc_dict_attack_worker_callback, instance); } bool nfc_scene_mf_classic_dict_attack_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - MfClassicData* data = &nfc->dev->dev_data.mf_classic_data; + NfcApp* instance = context; bool consumed = false; uint32_t state = - scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfClassicDictAttack); + scene_manager_get_scene_state(instance->scene_manager, NfcSceneMfClassicDictAttack); if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcWorkerEventSuccess) { + if(event.event == NfcCustomEventDictAttackComplete) { if(state == DictAttackStateUserDictInProgress) { - nfc_worker_stop(nfc->worker); - nfc_scene_mf_classic_dict_attack_prepare_view(nfc, state); + nfc_poller_stop(instance->poller); + nfc_poller_free(instance->poller); + nfc_dict_free(instance->nfc_dict_context.dict); + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicDictAttack, + DictAttackStateSystemDictInProgress); + nfc_scene_mf_classic_dict_attack_prepare_view(instance); + instance->poller = nfc_poller_alloc(instance->nfc, NfcProtocolMfClassic); + nfc_poller_start(instance->poller, nfc_dict_attack_worker_callback, instance); consumed = true; } else { - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicReadSuccess); + notification_message(instance->notifications, &sequence_success); + scene_manager_next_scene(instance->scene_manager, NfcSceneReadSuccess); dolphin_deed(DolphinDeedNfcReadSuccess); consumed = true; } - } else if(event.event == NfcWorkerEventAborted) { - if(state == DictAttackStateUserDictInProgress && - dict_attack_get_card_state(nfc->dict_attack)) { - nfc_scene_mf_classic_dict_attack_prepare_view(nfc, state); - consumed = true; - } else { - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicReadSuccess); - // Counting failed attempts too - dolphin_deed(DolphinDeedNfcReadSuccess); - consumed = true; - } - } else if(event.event == NfcWorkerEventCardDetected) { - dict_attack_set_card_detected(nfc->dict_attack, data->type); + } else if(event.event == NfcCustomEventCardDetected) { + dict_attack_set_card_state(instance->dict_attack, true); consumed = true; - } else if(event.event == NfcWorkerEventNoCardDetected) { - dict_attack_set_card_removed(nfc->dict_attack); - consumed = true; - } else if(event.event == NfcWorkerEventFoundKeyA) { - dict_attack_inc_keys_found(nfc->dict_attack); - consumed = true; - } else if(event.event == NfcWorkerEventFoundKeyB) { - dict_attack_inc_keys_found(nfc->dict_attack); - consumed = true; - } else if(event.event == NfcWorkerEventNewSector) { - nfc_scene_mf_classic_dict_attack_update_view(nfc); - dict_attack_inc_current_sector(nfc->dict_attack); - consumed = true; - } else if(event.event == NfcWorkerEventNewDictKeyBatch) { - nfc_scene_mf_classic_dict_attack_update_view(nfc); - dict_attack_inc_current_dict_key(nfc->dict_attack, NFC_DICT_KEY_BATCH_SIZE); + } else if(event.event == NfcCustomEventCardLost) { + dict_attack_set_card_state(instance->dict_attack, false); consumed = true; + } else if(event.event == NfcCustomEventDictAttackDataUpdate) { + nfc_scene_mf_classic_dict_attack_update_view(instance); } else if(event.event == NfcCustomEventDictAttackSkip) { + const MfClassicData* mfc_data = nfc_poller_get_data(instance->poller); + nfc_device_set_data(instance->nfc_device, NfcProtocolMfClassic, mfc_data); if(state == DictAttackStateUserDictInProgress) { - nfc_worker_stop(nfc->worker); + if(instance->nfc_dict_context.is_card_present) { + nfc_poller_stop(instance->poller); + nfc_poller_free(instance->poller); + nfc_dict_free(instance->nfc_dict_context.dict); + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicDictAttack, + DictAttackStateSystemDictInProgress); + nfc_scene_mf_classic_dict_attack_prepare_view(instance); + instance->poller = nfc_poller_alloc(instance->nfc, NfcProtocolMfClassic); + nfc_poller_start(instance->poller, nfc_dict_attack_worker_callback, instance); + } else { + notification_message(instance->notifications, &sequence_success); + scene_manager_next_scene(instance->scene_manager, NfcSceneReadSuccess); + dolphin_deed(DolphinDeedNfcReadSuccess); + } consumed = true; - } else if(state == DictAttackStateFlipperDictInProgress) { - nfc_worker_stop(nfc->worker); + } else if(state == DictAttackStateSystemDictInProgress) { + notification_message(instance->notifications, &sequence_success); + scene_manager_next_scene(instance->scene_manager, NfcSceneReadSuccess); + dolphin_deed(DolphinDeedNfcReadSuccess); consumed = true; } - } else if(event.event == NfcWorkerEventKeyAttackStart) { - dict_attack_set_key_attack( - nfc->dict_attack, - true, - nfc->dev->dev_data.mf_classic_dict_attack_data.current_sector); - } else if(event.event == NfcWorkerEventKeyAttackStop) { - dict_attack_set_key_attack(nfc->dict_attack, false, 0); - } else if(event.event == NfcWorkerEventKeyAttackNextSector) { - dict_attack_inc_key_attack_current_sector(nfc->dict_attack); } } else if(event.type == SceneManagerEventTypeBack) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneExitConfirm); + scene_manager_next_scene(instance->scene_manager, NfcSceneExitConfirm); consumed = true; } return consumed; } void nfc_scene_mf_classic_dict_attack_on_exit(void* context) { - Nfc* nfc = context; - NfcMfClassicDictAttackData* dict_attack_data = &nfc->dev->dev_data.mf_classic_dict_attack_data; - // Stop worker - nfc_worker_stop(nfc->worker); - if(dict_attack_data->dict) { - mf_classic_dict_free(dict_attack_data->dict); - dict_attack_data->dict = NULL; - } - dict_attack_reset(nfc->dict_attack); - nfc_blink_stop(nfc); - notification_message(nfc->notifications, &sequence_display_backlight_enforce_auto); + NfcApp* instance = context; + + nfc_poller_stop(instance->poller); + nfc_poller_free(instance->poller); + + dict_attack_reset(instance->dict_attack); + scene_manager_set_scene_state( + instance->scene_manager, NfcSceneMfClassicDictAttack, DictAttackStateUserDictInProgress); + + nfc_dict_free(instance->nfc_dict_context.dict); + + instance->nfc_dict_context.current_sector = 0; + instance->nfc_dict_context.sectors_total = 0; + instance->nfc_dict_context.sectors_read = 0; + instance->nfc_dict_context.keys_found = 0; + instance->nfc_dict_context.dict_keys_total = 0; + instance->nfc_dict_context.dict_keys_current = 0; + instance->nfc_dict_context.is_key_attack = false; + instance->nfc_dict_context.key_attack_current_sector = 0; + instance->nfc_dict_context.is_card_present = false; + + nfc_blink_stop(instance); + notification_message(instance->notifications, &sequence_display_backlight_enforce_auto); } diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_emulate.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_emulate.c deleted file mode 100644 index 8c0f493e1..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_emulate.c +++ /dev/null @@ -1,69 +0,0 @@ -#include "../nfc_i.h" - -#define NFC_MF_CLASSIC_DATA_NOT_CHANGED (0UL) -#define NFC_MF_CLASSIC_DATA_CHANGED (1UL) - -bool nfc_mf_classic_emulate_worker_callback(NfcWorkerEvent event, void* context) { - UNUSED(event); - Nfc* nfc = context; - - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfClassicEmulate, NFC_MF_CLASSIC_DATA_CHANGED); - return true; -} - -void nfc_scene_mf_classic_emulate_on_enter(void* context) { - Nfc* nfc = context; - - // Setup view - Popup* popup = nfc->popup; - popup_set_header(popup, "Emulating", 67, 13, AlignLeft, AlignTop); - if(strcmp(nfc->dev->dev_name, "") != 0) { - nfc_text_store_set(nfc, "%s", nfc->dev->dev_name); - } else { - nfc_text_store_set(nfc, "MIFARE\nClassic"); - } - popup_set_icon(popup, 0, 3, &I_NFC_dolphin_emulation_47x61); - popup_set_text(popup, nfc->text_store, 90, 28, AlignCenter, AlignTop); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - nfc_worker_start( - nfc->worker, - NfcWorkerStateMfClassicEmulate, - &nfc->dev->dev_data, - nfc_mf_classic_emulate_worker_callback, - nfc); - nfc_blink_emulate_start(nfc); -} - -bool nfc_scene_mf_classic_emulate_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeBack) { - // Stop worker - nfc_worker_stop(nfc->worker); - // Check if data changed and save in shadow file - if(scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfClassicEmulate) == - NFC_MF_CLASSIC_DATA_CHANGED) { - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfClassicEmulate, NFC_MF_CLASSIC_DATA_NOT_CHANGED); - // Save shadow file - if(furi_string_size(nfc->dev->load_path)) { - nfc_device_save_shadow(nfc->dev, furi_string_get_cstr(nfc->dev->load_path)); - } - } - consumed = false; - } - return consumed; -} - -void nfc_scene_mf_classic_emulate_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - popup_reset(nfc->popup); - - nfc_blink_stop(nfc); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys.c index 8a7dc2c18..3106c740a 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys.c @@ -1,62 +1,86 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" + +#define NFC_SCENE_MF_CLASSIC_KEYS_MAX (100) void nfc_scene_mf_classic_keys_widget_callback(GuiButtonType result, InputType type, void* context) { - Nfc* nfc = context; + NfcApp* instance = context; if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); + view_dispatcher_send_custom_event(instance->view_dispatcher, result); } } void nfc_scene_mf_classic_keys_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; // Load flipper dict keys total uint32_t flipper_dict_keys_total = 0; - MfClassicDict* dict = mf_classic_dict_alloc(MfClassicDictTypeSystem); + NfcDict* dict = nfc_dict_alloc( + NFC_APP_MF_CLASSIC_DICT_SYSTEM_PATH, NfcDictModeOpenExisting, sizeof(MfClassicKey)); if(dict) { - flipper_dict_keys_total = mf_classic_dict_get_total_keys(dict); - mf_classic_dict_free(dict); - } - // Load user dict keys total - uint32_t user_dict_keys_total = 0; - dict = mf_classic_dict_alloc(MfClassicDictTypeUser); - if(dict) { - user_dict_keys_total = mf_classic_dict_get_total_keys(dict); - mf_classic_dict_free(dict); + flipper_dict_keys_total = nfc_dict_get_total_keys(dict); + nfc_dict_free(dict); } + // Load user dict keys total + uint32_t user_dict_keys_total = 0; + dict = nfc_dict_alloc( + NFC_APP_MF_CLASSIC_DICT_USER_PATH, NfcDictModeOpenAlways, sizeof(MfClassicKey)); + if(dict) { + user_dict_keys_total = nfc_dict_get_total_keys(dict); + nfc_dict_free(dict); + } + + FuriString* temp_str = furi_string_alloc(); widget_add_string_element( - nfc->widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "MIFARE Classic Keys"); - char temp_str[32]; - snprintf(temp_str, sizeof(temp_str), "System dict: %lu", flipper_dict_keys_total); - widget_add_string_element(nfc->widget, 0, 20, AlignLeft, AlignTop, FontSecondary, temp_str); - snprintf(temp_str, sizeof(temp_str), "User dict: %lu", user_dict_keys_total); - widget_add_string_element(nfc->widget, 0, 32, AlignLeft, AlignTop, FontSecondary, temp_str); + instance->widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "MIFARE Classic Keys"); + furi_string_printf(temp_str, "System dict: %lu", flipper_dict_keys_total); + widget_add_string_element( + instance->widget, + 0, + 20, + AlignLeft, + AlignTop, + FontSecondary, + furi_string_get_cstr(temp_str)); + furi_string_printf(temp_str, "User dict: %lu", user_dict_keys_total); + widget_add_string_element( + instance->widget, + 0, + 32, + AlignLeft, + AlignTop, + FontSecondary, + furi_string_get_cstr(temp_str)); + widget_add_icon_element(instance->widget, 87, 13, &I_Keychain_39x36); widget_add_button_element( - nfc->widget, GuiButtonTypeCenter, "Add", nfc_scene_mf_classic_keys_widget_callback, nfc); - widget_add_icon_element(nfc->widget, 87, 13, &I_Keychain_39x36); + instance->widget, + GuiButtonTypeCenter, + "Add", + nfc_scene_mf_classic_keys_widget_callback, + instance); if(user_dict_keys_total > 0) { widget_add_button_element( - nfc->widget, + instance->widget, GuiButtonTypeRight, "List", nfc_scene_mf_classic_keys_widget_callback, - nfc); + instance); } + furi_string_free(temp_str); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); } bool nfc_scene_mf_classic_keys_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == GuiButtonTypeCenter) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicKeysAdd); + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicKeysAdd); consumed = true; } else if(event.event == GuiButtonTypeRight) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicKeysList); + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicKeysList); consumed = true; } } @@ -65,7 +89,7 @@ bool nfc_scene_mf_classic_keys_on_event(void* context, SceneManagerEvent event) } void nfc_scene_mf_classic_keys_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; - widget_reset(nfc->widget); + widget_reset(instance->widget); } diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_add.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_add.c index 3a999f031..824000343 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_add.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_add.c @@ -1,60 +1,62 @@ -#include "../nfc_i.h" -#include +#include "../nfc_app_i.h" void nfc_scene_mf_classic_keys_add_byte_input_callback(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventByteInputDone); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventByteInputDone); } void nfc_scene_mf_classic_keys_add_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; // Setup view - ByteInput* byte_input = nfc->byte_input; + ByteInput* byte_input = instance->byte_input; byte_input_set_header_text(byte_input, "Enter the key in hex"); byte_input_set_result_callback( byte_input, nfc_scene_mf_classic_keys_add_byte_input_callback, NULL, - nfc, - nfc->byte_input_store, - 6); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewByteInput); + instance, + instance->byte_input_store, + sizeof(MfClassicKey)); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewByteInput); } bool nfc_scene_mf_classic_keys_add_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == NfcCustomEventByteInputDone) { // Add key to dict - MfClassicDict* dict = mf_classic_dict_alloc(MfClassicDictTypeUser); - if(dict) { - if(mf_classic_dict_is_key_present(dict, nfc->byte_input_store)) { - scene_manager_next_scene( - nfc->scene_manager, NfcSceneMfClassicKeysWarnDuplicate); - } else if(mf_classic_dict_add_key(dict, nfc->byte_input_store)) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveSuccess); - dolphin_deed(DolphinDeedNfcMfcAdd); - } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDictNotFound); - } + NfcDict* dict = nfc_dict_alloc( + NFC_APP_MF_CLASSIC_DICT_USER_PATH, NfcDictModeOpenAlways, sizeof(MfClassicKey)); + furi_assert(dict); + + MfClassicKey key = {}; + memcpy(key.data, instance->byte_input_store, sizeof(MfClassicKey)); + if(nfc_dict_is_key_present(dict, key.data, sizeof(MfClassicKey))) { + scene_manager_next_scene( + instance->scene_manager, NfcSceneMfClassicKeysWarnDuplicate); + } else if(nfc_dict_add_key(dict, key.data, sizeof(MfClassicKey))) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSaveSuccess); + dolphin_deed(DolphinDeedNfcMfcAdd); } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDictNotFound); + scene_manager_previous_scene(instance->scene_manager); } - mf_classic_dict_free(dict); + + nfc_dict_free(dict); consumed = true; } } + return consumed; } void nfc_scene_mf_classic_keys_add_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; // Clear view - byte_input_set_result_callback(nfc->byte_input, NULL, NULL, NULL, NULL, 0); - byte_input_set_header_text(nfc->byte_input, ""); + byte_input_set_result_callback(instance->byte_input, NULL, NULL, NULL, NULL, 0); + byte_input_set_header_text(instance->byte_input, ""); } diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_delete.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_delete.c index 0ea3f59a4..b245a2a55 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_delete.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_delete.c @@ -1,42 +1,40 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_mf_classic_keys_delete_widget_callback( GuiButtonType result, InputType type, void* context) { - Nfc* nfc = context; + NfcApp* instance = context; if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); + view_dispatcher_send_custom_event(instance->view_dispatcher, result); } } void nfc_scene_mf_classic_keys_delete_on_enter(void* context) { - Nfc* nfc = context; - MfClassicDict* dict = mf_classic_dict_alloc(MfClassicDictTypeUser); + NfcApp* instance = context; + uint32_t key_index = - scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfClassicKeysDelete); - // Setup Custom Widget view - FuriString* key_str; - key_str = furi_string_alloc(); + scene_manager_get_scene_state(instance->scene_manager, NfcSceneMfClassicKeysDelete); + FuriString* key_str = furi_string_alloc(); widget_add_string_element( - nfc->widget, 64, 0, AlignCenter, AlignTop, FontPrimary, "Delete this key?"); + instance->widget, 64, 0, AlignCenter, AlignTop, FontPrimary, "Delete this key?"); widget_add_button_element( - nfc->widget, + instance->widget, GuiButtonTypeLeft, "Cancel", nfc_scene_mf_classic_keys_delete_widget_callback, - nfc); + instance); widget_add_button_element( - nfc->widget, + instance->widget, GuiButtonTypeRight, "Delete", nfc_scene_mf_classic_keys_delete_widget_callback, - nfc); + instance); - mf_classic_dict_get_key_at_index_str(dict, key_str, key_index); + mf_user_dict_get_key_str(instance->mf_user_dict, key_index, key_str); widget_add_string_element( - nfc->widget, + instance->widget, 64, 32, AlignCenter, @@ -45,39 +43,35 @@ void nfc_scene_mf_classic_keys_delete_on_enter(void* context) { furi_string_get_cstr(key_str)); furi_string_free(key_str); - mf_classic_dict_free(dict); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); } bool nfc_scene_mf_classic_keys_delete_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; - uint32_t key_index = - scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfClassicKeysDelete); if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneMfClassicKeys); - } else if(event.event == GuiButtonTypeRight) { - MfClassicDict* dict = mf_classic_dict_alloc(MfClassicDictTypeUser); - if(mf_classic_dict_delete_index(dict, key_index)) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDeleteSuccess); + if(event.event == GuiButtonTypeRight) { + uint32_t key_index = scene_manager_get_scene_state( + instance->scene_manager, NfcSceneMfClassicKeysDelete); + if(mf_user_dict_delete_key(instance->mf_user_dict, key_index)) { + scene_manager_next_scene(instance->scene_manager, NfcSceneDeleteSuccess); } else { - scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneMfClassicKeys); + scene_manager_previous_scene(instance->scene_manager); } - mf_classic_dict_free(dict); - consumed = true; + } else if(event.event == GuiButtonTypeLeft) { + scene_manager_previous_scene(instance->scene_manager); } + consumed = true; } return consumed; } void nfc_scene_mf_classic_keys_delete_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; - widget_reset(nfc->widget); + mf_user_dict_free(instance->mf_user_dict); + widget_reset(instance->widget); } diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_list.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_list.c index 57f9fe656..7370c0684 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_list.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_list.c @@ -1,100 +1,51 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" #define NFC_SCENE_MF_CLASSIC_KEYS_LIST_MAX (100) void nfc_scene_mf_classic_keys_list_submenu_callback(void* context, uint32_t index) { - furi_assert(context); + NfcApp* instance = context; - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_mf_classic_keys_list_popup_callback(void* context) { - furi_assert(context); - - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -void nfc_scene_mf_classic_keys_list_prepare(Nfc* nfc, MfClassicDict* dict) { - Submenu* submenu = nfc->submenu; - uint32_t index = 0; - FuriString* temp_key; - temp_key = furi_string_alloc(); - - submenu_set_header(submenu, "Select key to delete:"); - while(mf_classic_dict_get_next_key_str(dict, temp_key)) { - char* current_key = (char*)malloc(sizeof(char) * 13); - strncpy(current_key, furi_string_get_cstr(temp_key), 12); - MfClassicUserKeys_push_back(nfc->mfc_key_strs, current_key); - FURI_LOG_D("ListKeys", "Key %lu: %s", index, current_key); - submenu_add_item( - submenu, current_key, index++, nfc_scene_mf_classic_keys_list_submenu_callback, nfc); - } - furi_string_free(temp_key); + view_dispatcher_send_custom_event(instance->view_dispatcher, index); } void nfc_scene_mf_classic_keys_list_on_enter(void* context) { - Nfc* nfc = context; - MfClassicDict* dict = mf_classic_dict_alloc(MfClassicDictTypeUser); - MfClassicUserKeys_init(nfc->mfc_key_strs); - if(dict) { - uint32_t total_user_keys = mf_classic_dict_get_total_keys(dict); - if(total_user_keys < NFC_SCENE_MF_CLASSIC_KEYS_LIST_MAX) { - nfc_scene_mf_classic_keys_list_prepare(nfc, dict); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); - } else { - popup_set_header(nfc->popup, "Too many keys!", 64, 0, AlignCenter, AlignTop); - popup_set_text( - nfc->popup, - "Edit user dictionary\nwith file browser", - 64, - 12, - AlignCenter, - AlignTop); - popup_set_callback(nfc->popup, nfc_scene_mf_classic_keys_list_popup_callback); - popup_set_context(nfc->popup, nfc); - popup_set_timeout(nfc->popup, 3000); - popup_enable_timeout(nfc->popup); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - } - mf_classic_dict_free(dict); - } else { - popup_set_header( - nfc->popup, "Failed to load dictionary", 64, 32, AlignCenter, AlignCenter); - popup_set_callback(nfc->popup, nfc_scene_mf_classic_keys_list_popup_callback); - popup_set_context(nfc->popup, nfc); - popup_set_timeout(nfc->popup, 3000); - popup_enable_timeout(nfc->popup); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); + NfcApp* instance = context; + + instance->mf_user_dict = mf_user_dict_alloc(NFC_SCENE_MF_CLASSIC_KEYS_LIST_MAX); + + submenu_set_header(instance->submenu, "Select key to delete:"); + FuriString* temp_str = furi_string_alloc(); + for(size_t i = 0; i < mf_user_dict_get_keys_cnt(instance->mf_user_dict); i++) { + mf_user_dict_get_key_str(instance->mf_user_dict, i, temp_str); + submenu_add_item( + instance->submenu, + furi_string_get_cstr(temp_str), + i, + nfc_scene_mf_classic_keys_list_submenu_callback, + instance); } + furi_string_free(temp_str); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewMenu); } bool nfc_scene_mf_classic_keys_list_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; + bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventViewExit) { - consumed = scene_manager_previous_scene(nfc->scene_manager); - } else { - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfClassicKeysDelete, event.event); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicKeysDelete); - consumed = true; - } + scene_manager_set_scene_state( + instance->scene_manager, NfcSceneMfClassicKeysDelete, event.event); + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicKeysDelete); + } else if(event.type == SceneManagerEventTypeBack) { + mf_user_dict_free(instance->mf_user_dict); } + return consumed; } void nfc_scene_mf_classic_keys_list_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; - MfClassicUserKeys_it_t it; - for(MfClassicUserKeys_it(it, nfc->mfc_key_strs); !MfClassicUserKeys_end_p(it); - MfClassicUserKeys_next(it)) { - free(*MfClassicUserKeys_ref(it)); - } - MfClassicUserKeys_clear(nfc->mfc_key_strs); - submenu_reset(nfc->submenu); - popup_reset(nfc->popup); + submenu_reset(instance->submenu); } diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_warn_duplicate.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_warn_duplicate.c index ab41989b2..991c956c1 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_warn_duplicate.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_keys_warn_duplicate.c @@ -1,15 +1,16 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_mf_classic_keys_warn_duplicate_popup_callback(void* context) { - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); + NfcApp* instance = context; + + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventViewExit); } void nfc_scene_mf_classic_keys_warn_duplicate_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; // Setup view - Popup* popup = nfc->popup; + Popup* popup = instance->popup; popup_set_icon(popup, 72, 16, &I_DolphinCommon_56x48); popup_set_header(popup, "Key already exists!", 64, 3, AlignCenter, AlignTop); popup_set_text( @@ -20,28 +21,29 @@ void nfc_scene_mf_classic_keys_warn_duplicate_on_enter(void* context) { 24, AlignLeft, AlignTop); - popup_set_timeout(popup, 5000); - popup_set_context(popup, nfc); + popup_set_timeout(popup, 1500); + popup_set_context(popup, instance); popup_set_callback(popup, nfc_scene_mf_classic_keys_warn_duplicate_popup_callback); popup_enable_timeout(popup); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewPopup); } bool nfc_scene_mf_classic_keys_warn_duplicate_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == NfcCustomEventViewExit) { consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneMfClassicKeysAdd); + instance->scene_manager, NfcSceneMfClassicKeysAdd); } } + return consumed; } void nfc_scene_mf_classic_keys_warn_duplicate_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; - popup_reset(nfc->popup); + popup_reset(instance->popup); } diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_menu.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_menu.c deleted file mode 100644 index 9c4163676..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_menu.c +++ /dev/null @@ -1,82 +0,0 @@ -#include "../nfc_i.h" -#include - -enum SubmenuIndex { - SubmenuIndexSave, - SubmenuIndexEmulate, - SubmenuIndexDetectReader, - SubmenuIndexInfo, -}; - -void nfc_scene_mf_classic_menu_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_mf_classic_menu_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - - submenu_add_item( - submenu, "Save", SubmenuIndexSave, nfc_scene_mf_classic_menu_submenu_callback, nfc); - submenu_add_item( - submenu, "Emulate", SubmenuIndexEmulate, nfc_scene_mf_classic_menu_submenu_callback, nfc); - if(!mf_classic_is_card_read(&nfc->dev->dev_data.mf_classic_data)) { - submenu_add_item( - submenu, - "Detect Reader", - SubmenuIndexDetectReader, - nfc_scene_mf_classic_menu_submenu_callback, - nfc); - } - submenu_add_item( - submenu, "Info", SubmenuIndexInfo, nfc_scene_mf_classic_menu_submenu_callback, nfc); - - submenu_set_selected_item( - nfc->submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfClassicMenu)); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_mf_classic_menu_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneMfClassicMenu, event.event); - if(event.event == SubmenuIndexSave) { - nfc->dev->format = NfcDeviceSaveFormatMifareClassic; - // Clear device name - nfc_device_set_name(nfc->dev, ""); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); - consumed = true; - } else if(event.event == SubmenuIndexEmulate) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicEmulate); - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSetType)) { - dolphin_deed(DolphinDeedNfcAddEmulate); - } else { - dolphin_deed(DolphinDeedNfcEmulate); - } - consumed = true; - } else if(event.event == SubmenuIndexDetectReader) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDetectReader); - dolphin_deed(DolphinDeedNfcDetectReader); - consumed = true; - } else if(event.event == SubmenuIndexInfo) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcDataInfo); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_previous_scene(nfc->scene_manager); - } - - return consumed; -} - -void nfc_scene_mf_classic_menu_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_mfkey_complete.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_mfkey_complete.c new file mode 100644 index 000000000..8e07043e2 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_mfkey_complete.c @@ -0,0 +1,58 @@ +#include "../nfc_app_i.h" + +void nfc_scene_mf_classic_mfkey_complete_callback( + GuiButtonType result, + InputType type, + void* context) { + NfcApp* instance = context; + if(type == InputTypeShort) { + view_dispatcher_send_custom_event(instance->view_dispatcher, result); + } +} + +void nfc_scene_mf_classic_mfkey_complete_on_enter(void* context) { + NfcApp* instance = context; + + widget_add_string_element( + instance->widget, 64, 0, AlignCenter, AlignTop, FontPrimary, "Complete!"); + widget_add_string_multiline_element( + instance->widget, + 64, + 32, + AlignCenter, + AlignCenter, + FontSecondary, + "Now use Mfkey32\nto extract keys"); + widget_add_button_element( + instance->widget, + GuiButtonTypeCenter, + "OK", + nfc_scene_mf_classic_mfkey_complete_callback, + instance); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); +} + +bool nfc_scene_mf_classic_mfkey_complete_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == GuiButtonTypeCenter) { + consumed = scene_manager_search_and_switch_to_previous_scene( + instance->scene_manager, NfcSceneStart); + } + } else if(event.type == SceneManagerEventTypeBack) { + const uint32_t prev_scenes[] = {NfcSceneSavedMenu, NfcSceneStart}; + consumed = scene_manager_search_and_switch_to_previous_scene_one_of( + instance->scene_manager, prev_scenes, COUNT_OF(prev_scenes)); + } + + return consumed; +} + +void nfc_scene_mf_classic_mfkey_complete_on_exit(void* context) { + NfcApp* instance = context; + + widget_reset(instance->widget); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_mfkey_nonces_info.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_mfkey_nonces_info.c new file mode 100644 index 000000000..7f968b1dd --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_mfkey_nonces_info.c @@ -0,0 +1,72 @@ +#include "../nfc_app_i.h" + +void nfc_scene_mf_classic_mfkey_nonces_info_callback( + GuiButtonType result, + InputType type, + void* context) { + NfcApp* instance = context; + + if(type == InputTypeShort) { + view_dispatcher_send_custom_event(instance->view_dispatcher, result); + } +} + +void nfc_scene_mf_classic_mfkey_nonces_info_on_enter(void* context) { + NfcApp* instance = context; + + FuriString* temp_str = furi_string_alloc(); + + size_t mfkey_params_saved = mfkey32_logger_get_params_num(instance->mfkey32_logger); + furi_string_printf(temp_str, "Nonce pairs saved: %zu\n", mfkey_params_saved); + widget_add_string_element( + instance->widget, 0, 0, AlignLeft, AlignTop, FontPrimary, furi_string_get_cstr(temp_str)); + widget_add_string_element( + instance->widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "Authenticated sectors:"); + + mfkey32_logger_get_params_data(instance->mfkey32_logger, temp_str); + widget_add_text_scroll_element( + instance->widget, 0, 22, 128, 42, furi_string_get_cstr(temp_str)); + widget_add_button_element( + instance->widget, + GuiButtonTypeCenter, + "OK", + nfc_scene_mf_classic_mfkey_nonces_info_callback, + instance); + + furi_string_free(temp_str); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); +} + +bool nfc_scene_mf_classic_mfkey_nonces_info_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == GuiButtonTypeCenter) { + if(mfkey32_logger_save_params( + instance->mfkey32_logger, NFC_APP_MFKEY32_LOGS_FILE_PATH)) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicMfkeyComplete); + } else { + scene_manager_search_and_switch_to_previous_scene( + instance->scene_manager, NfcSceneStart); + } + consumed = true; + } + } else if(event.type == SceneManagerEventTypeBack) { + const uint32_t prev_scenes[] = {NfcSceneSavedMenu, NfcSceneStart}; + consumed = scene_manager_search_and_switch_to_previous_scene_one_of( + instance->scene_manager, prev_scenes, COUNT_OF(prev_scenes)); + } + + return consumed; +} + +void nfc_scene_mf_classic_mfkey_nonces_info_on_exit(void* context) { + NfcApp* instance = context; + + mfkey32_logger_free(instance->mfkey32_logger); + + // Clear view + widget_reset(instance->widget); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_read_success.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_read_success.c deleted file mode 100644 index 444c9a540..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_read_success.c +++ /dev/null @@ -1,82 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_mf_classic_read_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - furi_assert(context); - Nfc* nfc = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_mf_classic_read_success_on_enter(void* context) { - Nfc* nfc = context; - NfcDeviceData* dev_data = &nfc->dev->dev_data; - MfClassicData* mf_data = &dev_data->mf_classic_data; - - // Setup view - Widget* widget = nfc->widget; - widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_scene_mf_classic_read_success_widget_callback, nfc); - widget_add_button_element( - widget, GuiButtonTypeRight, "More", nfc_scene_mf_classic_read_success_widget_callback, nfc); - - FuriString* temp_str = NULL; - if(furi_string_size(nfc->dev->dev_data.parsed_data)) { - temp_str = furi_string_alloc_set(nfc->dev->dev_data.parsed_data); - } else { - temp_str = furi_string_alloc_printf("\e#%s\n", nfc_mf_classic_type(mf_data->type)); - furi_string_cat_printf(temp_str, "UID:"); - for(size_t i = 0; i < dev_data->nfc_data.uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", dev_data->nfc_data.uid[i]); - } - uint8_t sectors_total = mf_classic_get_total_sectors_num(mf_data->type); - uint8_t keys_total = sectors_total * 2; - uint8_t keys_found = 0; - uint8_t sectors_read = 0; - mf_classic_get_read_sectors_and_keys(mf_data, §ors_read, &keys_found); - furi_string_cat_printf(temp_str, "\nKeys Found: %d/%d", keys_found, keys_total); - furi_string_cat_printf(temp_str, "\nSectors Read: %d/%d", sectors_read, sectors_total); - } - - widget_add_text_scroll_element(widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - notification_message_block(nfc->notifications, &sequence_set_green_255); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_mf_classic_read_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneRetryConfirm); - consumed = true; - } else if(event.event == GuiButtonTypeRight) { - // Clear device name - nfc_device_set_name(nfc->dev, ""); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicMenu); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneExitConfirm); - consumed = true; - } - - return consumed; -} - -void nfc_scene_mf_classic_read_success_on_exit(void* context) { - Nfc* nfc = context; - - notification_message_block(nfc->notifications, &sequence_reset_green); - - // Clear view - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_update.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_update.c deleted file mode 100644 index ffef1b7b9..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_update.c +++ /dev/null @@ -1,98 +0,0 @@ -#include "../nfc_i.h" -#include - -enum { - NfcSceneMfClassicUpdateStateCardSearch, - NfcSceneMfClassicUpdateStateCardFound, -}; - -bool nfc_mf_classic_update_worker_callback(NfcWorkerEvent event, void* context) { - furi_assert(context); - - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, event); - - return true; -} - -static void nfc_scene_mf_classic_update_setup_view(Nfc* nfc) { - Popup* popup = nfc->popup; - popup_reset(popup); - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfClassicUpdate); - - if(state == NfcSceneMfClassicUpdateStateCardSearch) { - popup_set_text( - nfc->popup, "Apply the initial\ncard only", 128, 32, AlignRight, AlignCenter); - popup_set_icon(nfc->popup, 0, 8, &I_NFC_manual_60x50); - } else { - popup_set_header(popup, "Updating\nDon't move...", 52, 32, AlignLeft, AlignCenter); - popup_set_icon(popup, 12, 23, &A_Loading_24); - } - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); -} - -void nfc_scene_mf_classic_update_on_enter(void* context) { - Nfc* nfc = context; - dolphin_deed(DolphinDeedNfcEmulate); - - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfClassicUpdate, NfcSceneMfClassicUpdateStateCardSearch); - nfc_scene_mf_classic_update_setup_view(nfc); - - // Setup and start worker - nfc_worker_start( - nfc->worker, - NfcWorkerStateMfClassicUpdate, - &nfc->dev->dev_data, - nfc_mf_classic_update_worker_callback, - nfc); - nfc_blink_emulate_start(nfc); -} - -bool nfc_scene_mf_classic_update_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcWorkerEventSuccess) { - nfc_worker_stop(nfc->worker); - if(nfc_device_save_shadow(nfc->dev, furi_string_get_cstr(nfc->dev->load_path))) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicUpdateSuccess); - } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicWrongCard); - } - consumed = true; - } else if(event.event == NfcWorkerEventWrongCard) { - nfc_worker_stop(nfc->worker); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicWrongCard); - consumed = true; - } else if(event.event == NfcWorkerEventCardDetected) { - scene_manager_set_scene_state( - nfc->scene_manager, - NfcSceneMfClassicUpdate, - NfcSceneMfClassicUpdateStateCardFound); - nfc_scene_mf_classic_update_setup_view(nfc); - consumed = true; - } else if(event.event == NfcWorkerEventNoCardDetected) { - scene_manager_set_scene_state( - nfc->scene_manager, - NfcSceneMfClassicUpdate, - NfcSceneMfClassicUpdateStateCardSearch); - nfc_scene_mf_classic_update_setup_view(nfc); - consumed = true; - } - } - return consumed; -} - -void nfc_scene_mf_classic_update_on_exit(void* context) { - Nfc* nfc = context; - nfc_worker_stop(nfc->worker); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfClassicUpdate, NfcSceneMfClassicUpdateStateCardSearch); - // Clear view - popup_reset(nfc->popup); - - nfc_blink_stop(nfc); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_update_initial.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_update_initial.c new file mode 100644 index 000000000..961afdf53 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_update_initial.c @@ -0,0 +1,144 @@ +#include "../nfc_app_i.h" + +#include + +enum { + NfcSceneMfClassicUpdateInitialStateCardSearch, + NfcSceneMfClassicUpdateInitialStateCardFound, +}; + +NfcCommand nfc_mf_classic_update_initial_worker_callback(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolMfClassic); + + NfcCommand command = NfcCommandContinue; + const MfClassicPollerEvent* mfc_event = event.event_data; + NfcApp* instance = context; + + if(mfc_event->type == MfClassicPollerEventTypeCardDetected) { + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventCardDetected); + } else if(mfc_event->type == MfClassicPollerEventTypeCardLost) { + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventCardLost); + } else if(mfc_event->type == MfClassicPollerEventTypeRequestMode) { + const MfClassicData* updated_data = nfc_poller_get_data(instance->poller); + const MfClassicData* old_data = + nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic); + if(iso14443_3a_is_equal(updated_data->iso14443_3a_data, old_data->iso14443_3a_data)) { + mfc_event->data->poller_mode.mode = MfClassicPollerModeRead; + } else { + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventWrongCard); + command = NfcCommandStop; + } + } else if(mfc_event->type == MfClassicPollerEventTypeRequestReadSector) { + uint8_t sector_num = 0; + MfClassicKey key = {}; + MfClassicKeyType key_type = MfClassicKeyTypeA; + if(mf_classic_key_cahce_get_next_key( + instance->mfc_key_cache, §or_num, &key, &key_type)) { + mfc_event->data->read_sector_request_data.sector_num = sector_num; + mfc_event->data->read_sector_request_data.key = key; + mfc_event->data->read_sector_request_data.key_type = key_type; + mfc_event->data->read_sector_request_data.key_provided = true; + } else { + mfc_event->data->read_sector_request_data.key_provided = false; + } + } else if(mfc_event->type == MfClassicPollerEventTypeSuccess) { + const MfClassicData* updated_data = nfc_poller_get_data(instance->poller); + nfc_device_set_data(instance->nfc_device, NfcProtocolMfClassic, updated_data); + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventWorkerExit); + command = NfcCommandStop; + } + + return command; +} + +static void nfc_scene_mf_classic_update_initial_setup_view(NfcApp* instance) { + Popup* popup = instance->popup; + popup_reset(popup); + uint32_t state = + scene_manager_get_scene_state(instance->scene_manager, NfcSceneMfClassicUpdateInitial); + + if(state == NfcSceneMfClassicUpdateInitialStateCardSearch) { + popup_set_text( + instance->popup, "Apply the initial\ncard only", 128, 32, AlignRight, AlignCenter); + popup_set_icon(instance->popup, 0, 8, &I_NFC_manual_60x50); + } else { + popup_set_header(popup, "Updating\nDon't move...", 52, 32, AlignLeft, AlignCenter); + popup_set_icon(popup, 12, 23, &A_Loading_24); + } + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewPopup); +} + +void nfc_scene_mf_classic_update_initial_on_enter(void* context) { + NfcApp* instance = context; + dolphin_deed(DolphinDeedNfcEmulate); + + const MfClassicData* mfc_data = + nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic); + mf_classic_key_cache_load_from_data(instance->mfc_key_cache, mfc_data); + + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicUpdateInitial, + NfcSceneMfClassicUpdateInitialStateCardSearch); + nfc_scene_mf_classic_update_initial_setup_view(instance); + + // Setup and start worker + instance->poller = nfc_poller_alloc(instance->nfc, NfcProtocolMfClassic); + nfc_poller_start(instance->poller, nfc_mf_classic_update_initial_worker_callback, instance); + nfc_blink_emulate_start(instance); +} + +bool nfc_scene_mf_classic_update_initial_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventCardDetected) { + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicUpdateInitial, + NfcSceneMfClassicUpdateInitialStateCardFound); + nfc_scene_mf_classic_update_initial_setup_view(instance); + consumed = true; + } else if(event.event == NfcCustomEventCardLost) { + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicUpdateInitial, + NfcSceneMfClassicUpdateInitialStateCardSearch); + nfc_scene_mf_classic_update_initial_setup_view(instance); + consumed = true; + } else if(event.event == NfcCustomEventWrongCard) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicWrongCard); + consumed = true; + } else if(event.event == NfcCustomEventWorkerExit) { + if(nfc_save_shadow_file(instance)) { + scene_manager_next_scene( + instance->scene_manager, NfcSceneMfClassicUpdateInitialSuccess); + } else { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicWrongCard); + consumed = true; + } + } + } + + return consumed; +} + +void nfc_scene_mf_classic_update_initial_on_exit(void* context) { + NfcApp* instance = context; + + nfc_poller_stop(instance->poller); + nfc_poller_free(instance->poller); + + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicUpdateInitial, + NfcSceneMfClassicUpdateInitialStateCardSearch); + // Clear view + popup_reset(instance->popup); + + nfc_blink_stop(instance); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_update_initial_success.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_update_initial_success.c new file mode 100644 index 000000000..02e307b01 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_update_initial_success.c @@ -0,0 +1,43 @@ +#include "../nfc_app_i.h" + +void nfc_scene_mf_classic_update_initial_success_popup_callback(void* context) { + NfcApp* instance = context; + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventViewExit); +} + +void nfc_scene_mf_classic_update_initial_success_on_enter(void* context) { + NfcApp* instance = context; + dolphin_deed(DolphinDeedNfcSave); + + notification_message(instance->notifications, &sequence_success); + + Popup* popup = instance->popup; + popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); + popup_set_header(popup, "Updated!", 11, 20, AlignLeft, AlignBottom); + popup_set_timeout(popup, 1500); + popup_set_context(popup, instance); + popup_set_callback(popup, nfc_scene_mf_classic_update_initial_success_popup_callback); + popup_enable_timeout(popup); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewPopup); +} + +bool nfc_scene_mf_classic_update_initial_success_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventViewExit) { + consumed = scene_manager_search_and_switch_to_previous_scene( + instance->scene_manager, NfcSceneSavedMenu); + } + } + return consumed; +} + +void nfc_scene_mf_classic_update_initial_success_on_exit(void* context) { + NfcApp* instance = context; + + // Clear view + popup_reset(instance->popup); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_update_success.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_update_success.c deleted file mode 100644 index fb1868459..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_update_success.c +++ /dev/null @@ -1,44 +0,0 @@ -#include "../nfc_i.h" -#include - -void nfc_scene_mf_classic_update_success_popup_callback(void* context) { - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -void nfc_scene_mf_classic_update_success_on_enter(void* context) { - Nfc* nfc = context; - dolphin_deed(DolphinDeedNfcSave); - - notification_message(nfc->notifications, &sequence_success); - - Popup* popup = nfc->popup; - popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); - popup_set_header(popup, "Updated!", 11, 20, AlignLeft, AlignBottom); - popup_set_timeout(popup, 1500); - popup_set_context(popup, nfc); - popup_set_callback(popup, nfc_scene_mf_classic_update_success_popup_callback); - popup_enable_timeout(popup); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); -} - -bool nfc_scene_mf_classic_update_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventViewExit) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneFileSelect); - } - } - return consumed; -} - -void nfc_scene_mf_classic_update_success_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - popup_reset(nfc->popup); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_write.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_write.c deleted file mode 100644 index 20ebfcc70..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_write.c +++ /dev/null @@ -1,92 +0,0 @@ -#include "../nfc_i.h" -#include - -enum { - NfcSceneMfClassicWriteStateCardSearch, - NfcSceneMfClassicWriteStateCardFound, -}; - -bool nfc_mf_classic_write_worker_callback(NfcWorkerEvent event, void* context) { - furi_assert(context); - - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, event); - - return true; -} - -static void nfc_scene_mf_classic_write_setup_view(Nfc* nfc) { - Popup* popup = nfc->popup; - popup_reset(popup); - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfClassicWrite); - - if(state == NfcSceneMfClassicWriteStateCardSearch) { - popup_set_text( - nfc->popup, "Apply the initial\ncard only", 128, 32, AlignRight, AlignCenter); - popup_set_icon(nfc->popup, 0, 8, &I_NFC_manual_60x50); - } else { - popup_set_header(popup, "Writing\nDon't move...", 52, 32, AlignLeft, AlignCenter); - popup_set_icon(popup, 12, 23, &A_Loading_24); - } - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); -} - -void nfc_scene_mf_classic_write_on_enter(void* context) { - Nfc* nfc = context; - dolphin_deed(DolphinDeedNfcEmulate); - - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfClassicWrite, NfcSceneMfClassicWriteStateCardSearch); - nfc_scene_mf_classic_write_setup_view(nfc); - - // Setup and start worker - nfc_worker_start( - nfc->worker, - NfcWorkerStateMfClassicWrite, - &nfc->dev->dev_data, - nfc_mf_classic_write_worker_callback, - nfc); - nfc_blink_emulate_start(nfc); -} - -bool nfc_scene_mf_classic_write_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcWorkerEventSuccess) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicWriteSuccess); - consumed = true; - } else if(event.event == NfcWorkerEventFail) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicWriteFail); - consumed = true; - } else if(event.event == NfcWorkerEventWrongCard) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicWrongCard); - consumed = true; - } else if(event.event == NfcWorkerEventCardDetected) { - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfClassicWrite, NfcSceneMfClassicWriteStateCardFound); - nfc_scene_mf_classic_write_setup_view(nfc); - consumed = true; - } else if(event.event == NfcWorkerEventNoCardDetected) { - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfClassicWrite, NfcSceneMfClassicWriteStateCardSearch); - nfc_scene_mf_classic_write_setup_view(nfc); - consumed = true; - } - } - return consumed; -} - -void nfc_scene_mf_classic_write_on_exit(void* context) { - Nfc* nfc = context; - - nfc_worker_stop(nfc->worker); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfClassicWrite, NfcSceneMfClassicWriteStateCardSearch); - // Clear view - popup_reset(nfc->popup); - - nfc_blink_stop(nfc); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_write_fail.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_write_fail.c deleted file mode 100644 index aeea6eef0..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_write_fail.c +++ /dev/null @@ -1,58 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_mf_classic_write_fail_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - Nfc* nfc = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_mf_classic_write_fail_on_enter(void* context) { - Nfc* nfc = context; - Widget* widget = nfc->widget; - - notification_message(nfc->notifications, &sequence_error); - - widget_add_icon_element(widget, 72, 17, &I_DolphinCommon_56x48); - widget_add_string_element( - widget, 7, 4, AlignLeft, AlignTop, FontPrimary, "Writing gone wrong!"); - widget_add_string_multiline_element( - widget, - 7, - 17, - AlignLeft, - AlignTop, - FontSecondary, - "Not all sectors\nwere written\ncorrectly."); - - widget_add_button_element( - widget, GuiButtonTypeLeft, "Finish", nfc_scene_mf_classic_write_fail_widget_callback, nfc); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_mf_classic_write_fail_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneFileSelect); - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneSavedMenu); - } - return consumed; -} - -void nfc_scene_mf_classic_write_fail_on_exit(void* context) { - Nfc* nfc = context; - - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_write_initial.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_write_initial.c new file mode 100644 index 000000000..79f1def1d --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_write_initial.c @@ -0,0 +1,146 @@ +#include "../nfc_app_i.h" + +#include + +enum { + NfcSceneMfClassicWriteInitialStateCardSearch, + NfcSceneMfClassicWriteInitialStateCardFound, +}; + +NfcCommand + nfc_scene_mf_classic_write_initial_worker_callback(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolMfClassic); + + NfcCommand command = NfcCommandContinue; + NfcApp* instance = context; + MfClassicPollerEvent* mfc_event = event.event_data; + const MfClassicData* write_data = + nfc_device_get_data(instance->nfc_device, NfcProtocolMfClassic); + + if(mfc_event->type == MfClassicPollerEventTypeCardDetected) { + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventCardDetected); + } else if(mfc_event->type == MfClassicPollerEventTypeCardLost) { + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventCardLost); + } else if(mfc_event->type == MfClassicPollerEventTypeRequestMode) { + const MfClassicData* tag_data = nfc_poller_get_data(instance->poller); + if(iso14443_3a_is_equal(tag_data->iso14443_3a_data, write_data->iso14443_3a_data)) { + mfc_event->data->poller_mode.mode = MfClassicPollerModeWrite; + } else { + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventWrongCard); + command = NfcCommandStop; + } + } else if(mfc_event->type == MfClassicPollerEventTypeRequestSectorTrailer) { + uint8_t sector = mfc_event->data->sec_tr_data.sector_num; + uint8_t sec_tr = mf_classic_get_sector_trailer_num_by_sector(sector); + if(mf_classic_is_block_read(write_data, sec_tr)) { + mfc_event->data->sec_tr_data.sector_trailer = write_data->block[sec_tr]; + mfc_event->data->sec_tr_data.sector_trailer_provided = true; + } else { + mfc_event->data->sec_tr_data.sector_trailer_provided = false; + } + } else if(mfc_event->type == MfClassicPollerEventTypeRequestWriteBlock) { + uint8_t block_num = mfc_event->data->write_block_data.block_num; + if(mf_classic_is_block_read(write_data, block_num)) { + mfc_event->data->write_block_data.write_block = write_data->block[block_num]; + mfc_event->data->write_block_data.write_block_provided = true; + } else { + mfc_event->data->write_block_data.write_block_provided = false; + } + } else if(mfc_event->type == MfClassicPollerEventTypeSuccess) { + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerSuccess); + command = NfcCommandStop; + } else if(mfc_event->type == MfClassicPollerEventTypeFail) { + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventPollerFailure); + command = NfcCommandStop; + } + return command; +} + +static void nfc_scene_mf_classic_write_initial_setup_view(NfcApp* instance) { + Popup* popup = instance->popup; + popup_reset(popup); + uint32_t state = + scene_manager_get_scene_state(instance->scene_manager, NfcSceneMfClassicWriteInitial); + + if(state == NfcSceneMfClassicWriteInitialStateCardSearch) { + popup_set_text( + instance->popup, "Apply the initial\ncard only", 128, 32, AlignRight, AlignCenter); + popup_set_icon(instance->popup, 0, 8, &I_NFC_manual_60x50); + } else { + popup_set_header(popup, "Writing\nDon't move...", 52, 32, AlignLeft, AlignCenter); + popup_set_icon(popup, 12, 23, &A_Loading_24); + } + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewPopup); +} + +void nfc_scene_mf_classic_write_initial_on_enter(void* context) { + NfcApp* instance = context; + dolphin_deed(DolphinDeedNfcEmulate); + + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicWriteInitial, + NfcSceneMfClassicWriteInitialStateCardSearch); + nfc_scene_mf_classic_write_initial_setup_view(instance); + + // Setup and start worker + instance->poller = nfc_poller_alloc(instance->nfc, NfcProtocolMfClassic); + nfc_poller_start( + instance->poller, nfc_scene_mf_classic_write_initial_worker_callback, instance); + + nfc_blink_emulate_start(instance); +} + +bool nfc_scene_mf_classic_write_initial_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventCardDetected) { + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicWriteInitial, + NfcSceneMfClassicWriteInitialStateCardFound); + nfc_scene_mf_classic_write_initial_setup_view(instance); + consumed = true; + } else if(event.event == NfcCustomEventCardLost) { + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicWriteInitial, + NfcSceneMfClassicWriteInitialStateCardSearch); + nfc_scene_mf_classic_write_initial_setup_view(instance); + consumed = true; + } else if(event.event == NfcCustomEventWrongCard) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicWrongCard); + consumed = true; + } else if(event.event == NfcCustomEventPollerSuccess) { + scene_manager_next_scene( + instance->scene_manager, NfcSceneMfClassicWriteInitialSuccess); + consumed = true; + } else if(event.event == NfcCustomEventPollerFailure) { + scene_manager_next_scene(instance->scene_manager, NfcSceneMfClassicWriteInitialFail); + consumed = true; + } + } + + return consumed; +} + +void nfc_scene_mf_classic_write_initial_on_exit(void* context) { + NfcApp* instance = context; + + nfc_poller_stop(instance->poller); + nfc_poller_free(instance->poller); + + scene_manager_set_scene_state( + instance->scene_manager, + NfcSceneMfClassicWriteInitial, + NfcSceneMfClassicWriteInitialStateCardSearch); + // Clear view + popup_reset(instance->popup); + + nfc_blink_stop(instance); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_write_initial_fail.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_write_initial_fail.c new file mode 100644 index 000000000..f85e5a80c --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_write_initial_fail.c @@ -0,0 +1,62 @@ +#include "../nfc_app_i.h" + +void nfc_scene_mf_classic_write_initial_fail_widget_callback( + GuiButtonType result, + InputType type, + void* context) { + NfcApp* instance = context; + if(type == InputTypeShort) { + view_dispatcher_send_custom_event(instance->view_dispatcher, result); + } +} + +void nfc_scene_mf_classic_write_initial_fail_on_enter(void* context) { + NfcApp* instance = context; + Widget* widget = instance->widget; + + notification_message(instance->notifications, &sequence_error); + + widget_add_icon_element(widget, 72, 17, &I_DolphinCommon_56x48); + widget_add_string_element( + widget, 7, 4, AlignLeft, AlignTop, FontPrimary, "Writing gone wrong!"); + widget_add_string_multiline_element( + widget, + 7, + 17, + AlignLeft, + AlignTop, + FontSecondary, + "Not all sectors\nwere written\ncorrectly."); + + widget_add_button_element( + widget, + GuiButtonTypeLeft, + "Finish", + nfc_scene_mf_classic_write_initial_fail_widget_callback, + instance); + + // Setup and start worker + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); +} + +bool nfc_scene_mf_classic_write_initial_fail_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == GuiButtonTypeLeft) { + consumed = scene_manager_search_and_switch_to_previous_scene( + instance->scene_manager, NfcSceneSavedMenu); + } + } else if(event.type == SceneManagerEventTypeBack) { + consumed = scene_manager_search_and_switch_to_previous_scene( + instance->scene_manager, NfcSceneSavedMenu); + } + return consumed; +} + +void nfc_scene_mf_classic_write_initial_fail_on_exit(void* context) { + NfcApp* instance = context; + + widget_reset(instance->widget); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_write_initial_success.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_write_initial_success.c new file mode 100644 index 000000000..acb75cd2e --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_write_initial_success.c @@ -0,0 +1,43 @@ +#include "../nfc_app_i.h" + +void nfc_scene_mf_classic_write_initial_success_popup_callback(void* context) { + NfcApp* instance = context; + view_dispatcher_send_custom_event(instance->view_dispatcher, NfcCustomEventViewExit); +} + +void nfc_scene_mf_classic_write_initial_success_on_enter(void* context) { + NfcApp* instance = context; + dolphin_deed(DolphinDeedNfcSave); + + notification_message(instance->notifications, &sequence_success); + + Popup* popup = instance->popup; + popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); + popup_set_header(popup, "Successfully\nwritten", 13, 22, AlignLeft, AlignBottom); + popup_set_timeout(popup, 1500); + popup_set_context(popup, instance); + popup_set_callback(popup, nfc_scene_mf_classic_write_initial_success_popup_callback); + popup_enable_timeout(popup); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewPopup); +} + +bool nfc_scene_mf_classic_write_initial_success_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == NfcCustomEventViewExit) { + consumed = scene_manager_search_and_switch_to_previous_scene( + instance->scene_manager, NfcSceneSavedMenu); + } + } + return consumed; +} + +void nfc_scene_mf_classic_write_initial_success_on_exit(void* context) { + NfcApp* instance = context; + + // Clear view + popup_reset(instance->popup); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_write_success.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_write_success.c deleted file mode 100644 index 00030d4fe..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_write_success.c +++ /dev/null @@ -1,44 +0,0 @@ -#include "../nfc_i.h" -#include - -void nfc_scene_mf_classic_write_success_popup_callback(void* context) { - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -void nfc_scene_mf_classic_write_success_on_enter(void* context) { - Nfc* nfc = context; - dolphin_deed(DolphinDeedNfcSave); - - notification_message(nfc->notifications, &sequence_success); - - Popup* popup = nfc->popup; - popup_set_icon(popup, 32, 5, &I_DolphinNice_96x59); - popup_set_header(popup, "Successfully\nwritten", 13, 22, AlignLeft, AlignBottom); - popup_set_timeout(popup, 1500); - popup_set_context(popup, nfc); - popup_set_callback(popup, nfc_scene_mf_classic_write_success_popup_callback); - popup_enable_timeout(popup); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); -} - -bool nfc_scene_mf_classic_write_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventViewExit) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneFileSelect); - } - } - return consumed; -} - -void nfc_scene_mf_classic_write_success_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - popup_reset(nfc->popup); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_classic_wrong_card.c b/applications/main/nfc/scenes/nfc_scene_mf_classic_wrong_card.c index 2c56270e3..50025048a 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_classic_wrong_card.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_classic_wrong_card.c @@ -1,20 +1,20 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_mf_classic_wrong_card_widget_callback( GuiButtonType result, InputType type, void* context) { - Nfc* nfc = context; + NfcApp* instance = context; if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); + view_dispatcher_send_custom_event(instance->view_dispatcher, result); } } void nfc_scene_mf_classic_wrong_card_on_enter(void* context) { - Nfc* nfc = context; - Widget* widget = nfc->widget; + NfcApp* instance = context; + Widget* widget = instance->widget; - notification_message(nfc->notifications, &sequence_error); + notification_message(instance->notifications, &sequence_error); widget_add_icon_element(widget, 73, 17, &I_DolphinCommon_56x48); widget_add_string_element( @@ -28,26 +28,30 @@ void nfc_scene_mf_classic_wrong_card_on_enter(void* context) { FontSecondary, "Data management\nis only possible\nwith initial card"); widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_scene_mf_classic_wrong_card_widget_callback, nfc); + widget, + GuiButtonTypeLeft, + "Retry", + nfc_scene_mf_classic_wrong_card_widget_callback, + instance); // Setup and start worker - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); } bool nfc_scene_mf_classic_wrong_card_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(nfc->scene_manager); + consumed = scene_manager_previous_scene(instance->scene_manager); } } return consumed; } void nfc_scene_mf_classic_wrong_card_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; - widget_reset(nfc->widget); + widget_reset(instance->widget); } \ No newline at end of file diff --git a/applications/main/nfc/scenes/nfc_scene_mf_desfire_app.c b/applications/main/nfc/scenes/nfc_scene_mf_desfire_app.c index 882dc5fea..8d6a92b6c 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_desfire_app.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_desfire_app.c @@ -1,103 +1,93 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" -#define TAG "NfcSceneMfDesfireApp" +#include "../helpers/protocol_support/mf_desfire/mf_desfire_render.h" enum SubmenuIndex { SubmenuIndexAppInfo, SubmenuIndexDynamic, // dynamic indexes start here }; -void nfc_scene_mf_desfire_popup_callback(void* context) { - furi_assert(context); - - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -MifareDesfireApplication* nfc_scene_mf_desfire_app_get_app(Nfc* nfc) { - uint32_t app_idx = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireApp) >> - 1; - MifareDesfireApplication* app = nfc->dev->dev_data.mf_df_data.app_head; - for(uint32_t i = 0; i < app_idx && app; i++) { - app = app->next; - } - return app; -} - -void nfc_scene_mf_desfire_app_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; +static void nfc_scene_mf_desfire_app_submenu_callback(void* context, uint32_t index) { + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, index); } void nfc_scene_mf_desfire_app_on_enter(void* context) { - Nfc* nfc = context; - MifareDesfireApplication* app = nfc_scene_mf_desfire_app_get_app(nfc); - if(!app) { - popup_set_icon(nfc->popup, 5, 5, &I_WarningDolphin_45x42); - popup_set_header(nfc->popup, "Empty card!", 55, 12, AlignLeft, AlignBottom); - popup_set_callback(nfc->popup, nfc_scene_mf_desfire_popup_callback); - popup_set_context(nfc->popup, nfc); - popup_set_timeout(nfc->popup, 3000); - popup_enable_timeout(nfc->popup); - popup_set_text(nfc->popup, "No application\nfound.", 55, 15, AlignLeft, AlignTop); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - } else { - text_box_set_font(nfc->text_box, TextBoxFontHex); + NfcApp* nfc = context; + + text_box_set_font(nfc->text_box, TextBoxFontHex); + submenu_add_item( + nfc->submenu, + "App info", + SubmenuIndexAppInfo, + nfc_scene_mf_desfire_app_submenu_callback, + nfc); + + const uint32_t app_idx = + scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireApp) >> 1; + + const MfDesfireData* data = nfc_device_get_data(nfc->nfc_device, NfcProtocolMfDesfire); + const MfDesfireApplication* app = simple_array_cget(data->applications, app_idx); + + FuriString* label = furi_string_alloc(); + + for(uint32_t i = 0; i < simple_array_get_count(app->file_ids); ++i) { + const MfDesfireFileId file_id = + *(const MfDesfireFileId*)simple_array_cget(app->file_ids, i); + furi_string_printf(label, "File %d", file_id); submenu_add_item( nfc->submenu, - "App info", - SubmenuIndexAppInfo, + furi_string_get_cstr(label), + i + SubmenuIndexDynamic, nfc_scene_mf_desfire_app_submenu_callback, nfc); - - FuriString* label = furi_string_alloc(); - int idx = SubmenuIndexDynamic; - for(MifareDesfireFile* file = app->file_head; file; file = file->next) { - furi_string_printf(label, "File %d", file->id); - submenu_add_item( - nfc->submenu, - furi_string_get_cstr(label), - idx++, - nfc_scene_mf_desfire_app_submenu_callback, - nfc); - } - furi_string_free(label); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); } + + furi_string_free(label); + + view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); } bool nfc_scene_mf_desfire_app_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireApp); + + const uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireApp); if(event.type == SceneManagerEventTypeCustom) { if(event.event == NfcCustomEventViewExit) { consumed = scene_manager_previous_scene(nfc->scene_manager); } else { - MifareDesfireApplication* app = nfc_scene_mf_desfire_app_get_app(nfc); + const MfDesfireData* data = nfc_device_get_data(nfc->nfc_device, NfcProtocolMfDesfire); + + const uint32_t app_index = + scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireApp) >> 1; + const MfDesfireApplication* app = simple_array_cget(data->applications, app_index); + TextBox* text_box = nfc->text_box; furi_string_reset(nfc->text_box_store); if(event.event == SubmenuIndexAppInfo) { - mf_df_cat_application_info(app, nfc->text_box_store); + const MfDesfireApplicationId* app_id = + simple_array_cget(data->application_ids, app_index); + nfc_render_mf_desfire_application_id(app_id, nfc->text_box_store); + nfc_render_mf_desfire_application(app, nfc->text_box_store); } else { - uint16_t index = event.event - SubmenuIndexDynamic; - MifareDesfireFile* file = app->file_head; - for(int i = 0; file && i < index; i++) { - file = file->next; - } - if(!file) { - return false; - } - mf_df_cat_file(file, nfc->text_box_store); + const uint32_t file_index = event.event - SubmenuIndexDynamic; + const MfDesfireFileId* file_id = simple_array_cget(app->file_ids, file_index); + const MfDesfireFileSettings* file_settings = + simple_array_cget(app->file_settings, file_index); + const MfDesfireFileData* file_data = simple_array_cget(app->file_data, file_index); + nfc_render_mf_desfire_file_id(file_id, nfc->text_box_store); + nfc_render_mf_desfire_file_settings_data( + file_settings, file_data, nfc->text_box_store); } text_box_set_text(text_box, furi_string_get_cstr(nfc->text_box_store)); scene_manager_set_scene_state(nfc->scene_manager, NfcSceneMfDesfireApp, state | 1); view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewTextBox); consumed = true; } + } else if(event.type == SceneManagerEventTypeBack) { if(state & 1) { view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); @@ -110,10 +100,9 @@ bool nfc_scene_mf_desfire_app_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_mf_desfire_app_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Clear views - popup_reset(nfc->popup); text_box_reset(nfc->text_box); furi_string_reset(nfc->text_box_store); submenu_reset(nfc->submenu); diff --git a/applications/main/nfc/scenes/nfc_scene_mf_desfire_data.c b/applications/main/nfc/scenes/nfc_scene_mf_desfire_data.c deleted file mode 100644 index c7caee8dc..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_desfire_data.c +++ /dev/null @@ -1,104 +0,0 @@ -#include "../nfc_i.h" - -#define TAG "NfcSceneMfDesfireData" - -enum { - MifareDesfireDataStateMenu, - MifareDesfireDataStateItem, // MUST be last, states >= this correspond with submenu index -}; - -enum SubmenuIndex { - SubmenuIndexCardInfo, - SubmenuIndexDynamic, // dynamic indexes start here -}; - -void nfc_scene_mf_desfire_data_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = (Nfc*)context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_mf_desfire_data_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireData); - MifareDesfireData* data = &nfc->dev->dev_data.mf_df_data; - - text_box_set_font(nfc->text_box, TextBoxFontHex); - - submenu_add_item( - submenu, - "Card info", - SubmenuIndexCardInfo, - nfc_scene_mf_desfire_data_submenu_callback, - nfc); - - FuriString* label = furi_string_alloc(); - int idx = SubmenuIndexDynamic; - for(MifareDesfireApplication* app = data->app_head; app; app = app->next) { - furi_string_printf(label, "App %02x%02x%02x", app->id[0], app->id[1], app->id[2]); - submenu_add_item( - submenu, - furi_string_get_cstr(label), - idx++, - nfc_scene_mf_desfire_data_submenu_callback, - nfc); - } - furi_string_free(label); - - if(state >= MifareDesfireDataStateItem) { - submenu_set_selected_item( - nfc->submenu, state - MifareDesfireDataStateItem + SubmenuIndexDynamic); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfDesfireData, MifareDesfireDataStateMenu); - } - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_mf_desfire_data_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireData); - MifareDesfireData* data = &nfc->dev->dev_data.mf_df_data; - - if(event.type == SceneManagerEventTypeCustom) { - TextBox* text_box = nfc->text_box; - furi_string_reset(nfc->text_box_store); - if(event.event == SubmenuIndexCardInfo) { - mf_df_cat_card_info(data, nfc->text_box_store); - text_box_set_text(text_box, furi_string_get_cstr(nfc->text_box_store)); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewTextBox); - scene_manager_set_scene_state( - nfc->scene_manager, - NfcSceneMfDesfireData, - MifareDesfireDataStateItem + SubmenuIndexCardInfo); - consumed = true; - } else { - uint16_t index = event.event - SubmenuIndexDynamic; - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfDesfireData, MifareDesfireDataStateItem + index); - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneMfDesfireApp, index << 1); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfDesfireApp); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - if(state >= MifareDesfireDataStateItem) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfDesfireData, MifareDesfireDataStateMenu); - consumed = true; - } - } - - return consumed; -} - -void nfc_scene_mf_desfire_data_on_exit(void* context) { - Nfc* nfc = context; - - // Clear views - text_box_reset(nfc->text_box); - furi_string_reset(nfc->text_box_store); - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_desfire_menu.c b/applications/main/nfc/scenes/nfc_scene_mf_desfire_menu.c deleted file mode 100644 index 9cebefedf..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_desfire_menu.c +++ /dev/null @@ -1,72 +0,0 @@ -#include "../nfc_i.h" -#include - -enum SubmenuIndex { - SubmenuIndexSave, - SubmenuIndexEmulateUid, - SubmenuIndexInfo, -}; - -void nfc_scene_mf_desfire_menu_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_mf_desfire_menu_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - - submenu_add_item( - submenu, "Save", SubmenuIndexSave, nfc_scene_mf_desfire_menu_submenu_callback, nfc); - submenu_add_item( - submenu, - "Emulate UID", - SubmenuIndexEmulateUid, - nfc_scene_mf_desfire_menu_submenu_callback, - nfc); - submenu_add_item( - submenu, "Info", SubmenuIndexInfo, nfc_scene_mf_desfire_menu_submenu_callback, nfc); - - submenu_set_selected_item( - nfc->submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireMenu)); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_mf_desfire_menu_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexSave) { - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfDesfireMenu, SubmenuIndexSave); - nfc->dev->format = NfcDeviceSaveFormatMifareDesfire; - // Clear device name - nfc_device_set_name(nfc->dev, ""); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); - consumed = true; - } else if(event.event == SubmenuIndexEmulateUid) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneEmulateUid); - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSetType)) { - dolphin_deed(DolphinDeedNfcAddEmulate); - } else { - dolphin_deed(DolphinDeedNfcEmulate); - } - consumed = true; - } else if(event.event == SubmenuIndexInfo) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcDataInfo); - consumed = true; - } - } - - return consumed; -} - -void nfc_scene_mf_desfire_menu_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_desfire_more_info.c b/applications/main/nfc/scenes/nfc_scene_mf_desfire_more_info.c new file mode 100644 index 000000000..76834e3f4 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_desfire_more_info.c @@ -0,0 +1,112 @@ +#include "../nfc_app_i.h" + +#include "../helpers/protocol_support/nfc_protocol_support_gui_common.h" +#include "../helpers/protocol_support/mf_desfire/mf_desfire_render.h" + +enum { + MifareDesfireMoreInfoStateMenu, + MifareDesfireMoreInfoStateItem, // MUST be last, states >= this correspond with submenu index +}; + +enum SubmenuIndex { + SubmenuIndexCardInfo, + SubmenuIndexDynamic, // dynamic indices start here +}; + +void nfc_scene_mf_desfire_more_info_on_enter(void* context) { + NfcApp* nfc = context; + Submenu* submenu = nfc->submenu; + + const uint32_t state = + scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireMoreInfo); + const MfDesfireData* data = nfc_device_get_data(nfc->nfc_device, NfcProtocolMfDesfire); + + text_box_set_font(nfc->text_box, TextBoxFontHex); + + submenu_add_item( + submenu, + "Card info", + SubmenuIndexCardInfo, + nfc_protocol_support_common_submenu_callback, + nfc); + + FuriString* label = furi_string_alloc(); + + for(uint32_t i = 0; i < simple_array_get_count(data->application_ids); ++i) { + const MfDesfireApplicationId* app_id = simple_array_cget(data->application_ids, i); + furi_string_printf( + label, "App %02x%02x%02x", app_id->data[0], app_id->data[1], app_id->data[2]); + submenu_add_item( + submenu, + furi_string_get_cstr(label), + i + SubmenuIndexDynamic, + nfc_protocol_support_common_submenu_callback, + nfc); + } + + furi_string_free(label); + + if(state >= MifareDesfireMoreInfoStateItem) { + submenu_set_selected_item( + nfc->submenu, state - MifareDesfireMoreInfoStateItem + SubmenuIndexDynamic); + scene_manager_set_scene_state( + nfc->scene_manager, NfcSceneMfDesfireMoreInfo, MifareDesfireMoreInfoStateMenu); + } + + view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); +} + +bool nfc_scene_mf_desfire_more_info_on_event(void* context, SceneManagerEvent event) { + NfcApp* nfc = context; + bool consumed = false; + + const uint32_t state = + scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfDesfireMoreInfo); + const MfDesfireData* data = nfc_device_get_data(nfc->nfc_device, NfcProtocolMfDesfire); + + if(event.type == SceneManagerEventTypeCustom) { + TextBox* text_box = nfc->text_box; + furi_string_reset(nfc->text_box_store); + + if(event.event == SubmenuIndexCardInfo) { + nfc_render_mf_desfire_data(data, nfc->text_box_store); + text_box_set_text(text_box, furi_string_get_cstr(nfc->text_box_store)); + view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewTextBox); + scene_manager_set_scene_state( + nfc->scene_manager, + NfcSceneMfDesfireMoreInfo, + MifareDesfireMoreInfoStateItem + SubmenuIndexCardInfo); + consumed = true; + } else { + const uint32_t index = event.event - SubmenuIndexDynamic; + scene_manager_set_scene_state( + nfc->scene_manager, + NfcSceneMfDesfireMoreInfo, + MifareDesfireMoreInfoStateItem + index); + scene_manager_set_scene_state(nfc->scene_manager, NfcSceneMfDesfireApp, index << 1); + scene_manager_next_scene(nfc->scene_manager, NfcSceneMfDesfireApp); + consumed = true; + } + } else if(event.type == SceneManagerEventTypeBack) { + if(state >= MifareDesfireMoreInfoStateItem) { + view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); + scene_manager_set_scene_state( + nfc->scene_manager, NfcSceneMfDesfireMoreInfo, MifareDesfireMoreInfoStateMenu); + } else { + // Return directly to the Info scene + scene_manager_search_and_switch_to_previous_scene(nfc->scene_manager, NfcSceneInfo); + } + consumed = true; + } + + return consumed; +} + +void nfc_scene_mf_desfire_more_info_on_exit(void* context) { + NfcApp* nfc = context; + + // Clear views + text_box_reset(nfc->text_box); + furi_string_reset(nfc->text_box_store); + submenu_reset(nfc->submenu); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_desfire_read_success.c b/applications/main/nfc/scenes/nfc_scene_mf_desfire_read_success.c deleted file mode 100644 index 633549eb5..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_desfire_read_success.c +++ /dev/null @@ -1,101 +0,0 @@ -#include "../nfc_i.h" -#include - -void nfc_scene_mf_desfire_read_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - Nfc* nfc = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_mf_desfire_read_success_on_enter(void* context) { - Nfc* nfc = context; - - FuriHalNfcDevData* nfc_data = &nfc->dev->dev_data.nfc_data; - MifareDesfireData* data = &nfc->dev->dev_data.mf_df_data; - Widget* widget = nfc->widget; - - // Prepare string for data display - FuriString* temp_str = NULL; - if(furi_string_size(nfc->dev->dev_data.parsed_data)) { - temp_str = furi_string_alloc_set(nfc->dev->dev_data.parsed_data); - } else { - temp_str = furi_string_alloc_printf("\e#MIFARE DESFire\n"); - furi_string_cat_printf(temp_str, "UID:"); - for(size_t i = 0; i < nfc_data->uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", nfc_data->uid[i]); - } - - uint32_t bytes_total = 1UL << (data->version.sw_storage >> 1); - uint32_t bytes_free = data->free_memory ? data->free_memory->bytes : 0; - furi_string_cat_printf(temp_str, "\n%lu", bytes_total); - if(data->version.sw_storage & 1) { - furi_string_push_back(temp_str, '+'); - } - furi_string_cat_printf(temp_str, " bytes, %lu bytes free\n", bytes_free); - - uint16_t n_apps = 0; - uint16_t n_files = 0; - for(MifareDesfireApplication* app = data->app_head; app; app = app->next) { - n_apps++; - for(MifareDesfireFile* file = app->file_head; file; file = file->next) { - n_files++; - } - } - furi_string_cat_printf(temp_str, "%d Application", n_apps); - if(n_apps != 1) { - furi_string_push_back(temp_str, 's'); - } - furi_string_cat_printf(temp_str, ", %d file", n_files); - if(n_files != 1) { - furi_string_push_back(temp_str, 's'); - } - } - - notification_message_block(nfc->notifications, &sequence_set_green_255); - - // Add text scroll element - widget_add_text_scroll_element(widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - // Add button elements - widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_scene_mf_desfire_read_success_widget_callback, nfc); - widget_add_button_element( - widget, GuiButtonTypeRight, "More", nfc_scene_mf_desfire_read_success_widget_callback, nfc); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_mf_desfire_read_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneRetryConfirm); - consumed = true; - } else if(event.event == GuiButtonTypeRight) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfDesfireMenu); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneExitConfirm); - consumed = true; - } - - return consumed; -} - -void nfc_scene_mf_desfire_read_success_on_exit(void* context) { - Nfc* nfc = context; - - notification_message_block(nfc->notifications, &sequence_reset_green); - - // Clean dialog - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_capture_pass.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_capture_pass.c new file mode 100644 index 000000000..1c4be4630 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_capture_pass.c @@ -0,0 +1,67 @@ +#include "../nfc_app_i.h" + +NfcCommand + nfc_scene_mf_ultralight_capture_pass_worker_callback(NfcGenericEvent event, void* context) { + NfcApp* instance = context; + MfUltralightListenerEvent* mfu_event = event.event_data; + MfUltralightAuth* mauth = instance->mf_ul_auth; + + if(mfu_event->type == MfUltralightListenerEventTypeAuth) { + mauth->password = mfu_event->data->password; + view_dispatcher_send_custom_event( + instance->view_dispatcher, MfUltralightListenerEventTypeAuth); + } + + return NfcCommandContinue; +} + +void nfc_scene_mf_ultralight_capture_pass_on_enter(void* context) { + NfcApp* instance = context; + + // Setup view + widget_add_string_multiline_element( + instance->widget, + 54, + 30, + AlignLeft, + AlignCenter, + FontPrimary, + "Touch the\nreader to get\npassword..."); + widget_add_icon_element(instance->widget, 0, 15, &I_Modern_reader_18x34); + widget_add_icon_element(instance->widget, 20, 12, &I_Move_flipper_26x39); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); + + // Start worker + const MfUltralightData* data = + nfc_device_get_data(instance->nfc_device, NfcProtocolMfUltralight); + instance->listener = nfc_listener_alloc(instance->nfc, NfcProtocolMfUltralight, data); + nfc_listener_start( + instance->listener, nfc_scene_mf_ultralight_capture_pass_worker_callback, instance); + + nfc_blink_read_start(instance); +} + +bool nfc_scene_mf_ultralight_capture_pass_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == MfUltralightListenerEventTypeAuth) { + notification_message(instance->notifications, &sequence_success); + scene_manager_next_scene(instance->scene_manager, NfcSceneMfUltralightUnlockWarn); + consumed = true; + } + } + return consumed; +} + +void nfc_scene_mf_ultralight_capture_pass_on_exit(void* context) { + NfcApp* instance = context; + + // Clear view + nfc_listener_stop(instance->listener); + nfc_listener_free(instance->listener); + widget_reset(instance->widget); + + nfc_blink_stop(instance); +} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_data.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_data.c deleted file mode 100644 index 8cd223ee6..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_data.c +++ /dev/null @@ -1,32 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_mf_ultralight_data_on_enter(void* context) { - Nfc* nfc = context; - MfUltralightData* data = &nfc->dev->dev_data.mf_ul_data; - TextBox* text_box = nfc->text_box; - - text_box_set_font(text_box, TextBoxFontHex); - for(uint16_t i = 0; i < data->data_size; i += 2) { - if(!(i % 8) && i) { - furi_string_push_back(nfc->text_box_store, '\n'); - } - furi_string_cat_printf(nfc->text_box_store, "%02X%02X ", data->data[i], data->data[i + 1]); - } - text_box_set_text(text_box, furi_string_get_cstr(nfc->text_box_store)); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewTextBox); -} - -bool nfc_scene_mf_ultralight_data_on_event(void* context, SceneManagerEvent event) { - UNUSED(context); - UNUSED(event); - return false; -} - -void nfc_scene_mf_ultralight_data_on_exit(void* context) { - Nfc* nfc = context; - - // Clean view - text_box_reset(nfc->text_box); - furi_string_reset(nfc->text_box_store); -} \ No newline at end of file diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_emulate.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_emulate.c deleted file mode 100644 index 9d8f17f9a..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_emulate.c +++ /dev/null @@ -1,74 +0,0 @@ -#include "../nfc_i.h" - -#define NFC_MF_UL_DATA_NOT_CHANGED (0UL) -#define NFC_MF_UL_DATA_CHANGED (1UL) - -bool nfc_mf_ultralight_emulate_worker_callback(NfcWorkerEvent event, void* context) { - UNUSED(event); - Nfc* nfc = context; - - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfUltralightEmulate, NFC_MF_UL_DATA_CHANGED); - return true; -} - -void nfc_scene_mf_ultralight_emulate_on_enter(void* context) { - Nfc* nfc = context; - - // Setup view - MfUltralightType type = nfc->dev->dev_data.mf_ul_data.type; - bool is_ultralight = (type == MfUltralightTypeUL11) || (type == MfUltralightTypeUL21) || - (type == MfUltralightTypeUnknown); - Popup* popup = nfc->popup; - popup_set_header(popup, "Emulating", 67, 13, AlignLeft, AlignTop); - if(strcmp(nfc->dev->dev_name, "") != 0) { - nfc_text_store_set(nfc, "%s", nfc->dev->dev_name); - } else if(is_ultralight) { - nfc_text_store_set(nfc, "MIFARE\nUltralight"); - } else { - nfc_text_store_set(nfc, "MIFARE\nNTAG"); - } - popup_set_icon(popup, 0, 3, &I_NFC_dolphin_emulation_47x61); - popup_set_text(popup, nfc->text_store, 90, 28, AlignCenter, AlignTop); - - // Setup and start worker - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - nfc_worker_start( - nfc->worker, - NfcWorkerStateMfUltralightEmulate, - &nfc->dev->dev_data, - nfc_mf_ultralight_emulate_worker_callback, - nfc); - nfc_blink_emulate_start(nfc); -} - -bool nfc_scene_mf_ultralight_emulate_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeBack) { - // Stop worker - nfc_worker_stop(nfc->worker); - // Check if data changed and save in shadow file - if(scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfUltralightEmulate) == - NFC_MF_UL_DATA_CHANGED) { - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfUltralightEmulate, NFC_MF_UL_DATA_NOT_CHANGED); - // Save shadow file - if(furi_string_size(nfc->dev->load_path)) { - nfc_device_save_shadow(nfc->dev, furi_string_get_cstr(nfc->dev->load_path)); - } - } - consumed = false; - } - return consumed; -} - -void nfc_scene_mf_ultralight_emulate_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - popup_reset(nfc->popup); - - nfc_blink_stop(nfc); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_key_input.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_key_input.c index 089187d5b..6db6023d2 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_key_input.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_key_input.c @@ -1,13 +1,13 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_mf_ultralight_key_input_byte_input_callback(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventByteInputDone); } void nfc_scene_mf_ultralight_key_input_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Setup view ByteInput* byte_input = nfc->byte_input; @@ -17,13 +17,13 @@ void nfc_scene_mf_ultralight_key_input_on_enter(void* context) { nfc_scene_mf_ultralight_key_input_byte_input_callback, NULL, nfc, - nfc->byte_input_store, + nfc->mf_ul_auth->password.data, 4); view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewByteInput); } bool nfc_scene_mf_ultralight_key_input_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { @@ -36,7 +36,7 @@ bool nfc_scene_mf_ultralight_key_input_on_event(void* context, SceneManagerEvent } void nfc_scene_mf_ultralight_key_input_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Clear view byte_input_set_result_callback(nfc->byte_input, NULL, NULL, NULL, NULL, 0); diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_menu.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_menu.c deleted file mode 100644 index b3bd780f4..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_menu.c +++ /dev/null @@ -1,89 +0,0 @@ -#include "../nfc_i.h" -#include - -enum SubmenuIndex { - SubmenuIndexUnlock, - SubmenuIndexSave, - SubmenuIndexEmulate, - SubmenuIndexInfo, -}; - -void nfc_scene_mf_ultralight_menu_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_mf_ultralight_menu_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - MfUltralightData* data = &nfc->dev->dev_data.mf_ul_data; - - if(!mf_ul_is_full_capture(data) && data->type != MfUltralightTypeULC) { - submenu_add_item( - submenu, - "Unlock", - SubmenuIndexUnlock, - nfc_scene_mf_ultralight_menu_submenu_callback, - nfc); - } - submenu_add_item( - submenu, "Save", SubmenuIndexSave, nfc_scene_mf_ultralight_menu_submenu_callback, nfc); - if(mf_ul_emulation_supported(data)) { - submenu_add_item( - submenu, - "Emulate", - SubmenuIndexEmulate, - nfc_scene_mf_ultralight_menu_submenu_callback, - nfc); - } - submenu_add_item( - submenu, "Info", SubmenuIndexInfo, nfc_scene_mf_ultralight_menu_submenu_callback, nfc); - - submenu_set_selected_item( - nfc->submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfUltralightMenu)); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_mf_ultralight_menu_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexSave) { - nfc->dev->format = NfcDeviceSaveFormatMifareUl; - // Clear device name - nfc_device_set_name(nfc->dev, ""); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); - consumed = true; - } else if(event.event == SubmenuIndexEmulate) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightEmulate); - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSetType)) { - dolphin_deed(DolphinDeedNfcAddEmulate); - } else { - dolphin_deed(DolphinDeedNfcEmulate); - } - consumed = true; - } else if(event.event == SubmenuIndexUnlock) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightUnlockMenu); - consumed = true; - } else if(event.event == SubmenuIndexInfo) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcDataInfo); - consumed = true; - } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneMfUltralightMenu, event.event); - - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_previous_scene(nfc->scene_manager); - } - - return consumed; -} - -void nfc_scene_mf_ultralight_menu_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_read_auth.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_read_auth.c deleted file mode 100644 index 2ab5e3f3f..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_read_auth.c +++ /dev/null @@ -1,116 +0,0 @@ -#include "../nfc_i.h" - -typedef enum { - NfcSceneMfUlReadStateIdle, - NfcSceneMfUlReadStateDetecting, - NfcSceneMfUlReadStateReading, - NfcSceneMfUlReadStateNotSupportedCard, -} NfcSceneMfUlReadState; - -bool nfc_scene_mf_ultralight_read_auth_worker_callback(NfcWorkerEvent event, void* context) { - Nfc* nfc = context; - - if(event == NfcWorkerEventMfUltralightPassKey) { - memcpy(nfc->dev->dev_data.mf_ul_data.auth_key, nfc->byte_input_store, 4); - } else { - view_dispatcher_send_custom_event(nfc->view_dispatcher, event); - } - return true; -} - -void nfc_scene_mf_ultralight_read_auth_set_state(Nfc* nfc, NfcSceneMfUlReadState state) { - uint32_t curr_state = - scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfUltralightReadAuth); - if(curr_state != state) { - if(state == NfcSceneMfUlReadStateDetecting) { - popup_reset(nfc->popup); - popup_set_text(nfc->popup, "Apply the\ntarget card", 97, 24, AlignCenter, AlignTop); - popup_set_icon(nfc->popup, 0, 8, &I_NFC_manual_60x50); - nfc_blink_read_start(nfc); - } else if(state == NfcSceneMfUlReadStateReading) { - popup_reset(nfc->popup); - popup_set_header( - nfc->popup, "Reading card\nDon't move...", 85, 24, AlignCenter, AlignTop); - popup_set_icon(nfc->popup, 12, 23, &A_Loading_24); - nfc_blink_detect_start(nfc); - } else if(state == NfcSceneMfUlReadStateNotSupportedCard) { - popup_reset(nfc->popup); - popup_set_header(nfc->popup, "Wrong type of card!", 64, 3, AlignCenter, AlignTop); - popup_set_text( - nfc->popup, - "Only MIFARE\nUltralight & NTAG\nare supported", - 4, - 22, - AlignLeft, - AlignTop); - popup_set_icon(nfc->popup, 73, 20, &I_DolphinCommon_56x48); - nfc_blink_stop(nfc); - notification_message(nfc->notifications, &sequence_error); - notification_message(nfc->notifications, &sequence_set_red_255); - } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneMfUltralightReadAuth, state); - } -} - -void nfc_scene_mf_ultralight_read_auth_on_enter(void* context) { - Nfc* nfc = context; - - nfc_device_clear(nfc->dev); - // Setup view - nfc_scene_mf_ultralight_read_auth_set_state(nfc, NfcSceneMfUlReadStateDetecting); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - // Start worker - nfc_worker_start( - nfc->worker, - NfcWorkerStateReadMfUltralightReadAuth, - &nfc->dev->dev_data, - nfc_scene_mf_ultralight_read_auth_worker_callback, - nfc); -} - -bool nfc_scene_mf_ultralight_read_auth_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if((event.event == NfcWorkerEventSuccess) || (event.event == NfcWorkerEventFail)) { - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightReadAuthResult); - consumed = true; - } else if(event.event == NfcWorkerEventCardDetected) { - nfc_scene_mf_ultralight_read_auth_set_state(nfc, NfcSceneMfUlReadStateReading); - consumed = true; - } else if(event.event == NfcWorkerEventNoCardDetected) { - nfc_scene_mf_ultralight_read_auth_set_state(nfc, NfcSceneMfUlReadStateDetecting); - consumed = true; - } else if(event.event == NfcWorkerEventWrongCardDetected) { - nfc_scene_mf_ultralight_read_auth_set_state( - nfc, NfcSceneMfUlReadStateNotSupportedCard); - } - } else if(event.type == SceneManagerEventTypeBack) { - MfUltralightData* mf_ul_data = &nfc->dev->dev_data.mf_ul_data; - NfcScene next_scene; - if(mf_ul_data->auth_method == MfUltralightAuthMethodManual) { - next_scene = NfcSceneMfUltralightKeyInput; - } else if(mf_ul_data->auth_method == MfUltralightAuthMethodAuto) { - next_scene = NfcSceneMfUltralightUnlockAuto; - } else { - next_scene = NfcSceneMfUltralightUnlockMenu; - } - consumed = - scene_manager_search_and_switch_to_previous_scene(nfc->scene_manager, next_scene); - } - return consumed; -} - -void nfc_scene_mf_ultralight_read_auth_on_exit(void* context) { - Nfc* nfc = context; - - // Stop worker - nfc_worker_stop(nfc->worker); - // Clear view - popup_reset(nfc->popup); - nfc_blink_stop(nfc); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneMfUltralightReadAuth, NfcSceneMfUlReadStateIdle); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_read_auth_result.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_read_auth_result.c deleted file mode 100644 index b125e9991..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_read_auth_result.c +++ /dev/null @@ -1,116 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_mf_ultralight_read_auth_result_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - Nfc* nfc = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_mf_ultralight_read_auth_result_on_enter(void* context) { - Nfc* nfc = context; - - // Setup dialog view - FuriHalNfcDevData* nfc_data = &nfc->dev->dev_data.nfc_data; - MfUltralightData* mf_ul_data = &nfc->dev->dev_data.mf_ul_data; - MfUltralightConfigPages* config_pages = mf_ultralight_get_config_pages(mf_ul_data); - Widget* widget = nfc->widget; - const char* title; - FuriString* temp_str; - temp_str = furi_string_alloc(); - - if((mf_ul_data->data_read == mf_ul_data->data_size) && (mf_ul_data->data_read > 0)) { - if(mf_ul_data->auth_success) { - title = "All pages are unlocked!"; - } else { - title = "All unlocked but failed auth!"; - } - } else { - title = "Not all pages unlocked!"; - } - widget_add_string_element(widget, 64, 0, AlignCenter, AlignTop, FontPrimary, title); - furi_string_set(temp_str, "UID:"); - for(size_t i = 0; i < nfc_data->uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", nfc_data->uid[i]); - } - widget_add_string_element( - widget, 0, 17, AlignLeft, AlignTop, FontSecondary, furi_string_get_cstr(temp_str)); - if(mf_ul_data->auth_success) { - furi_string_printf( - temp_str, - "Password: %02X %02X %02X %02X", - config_pages->auth_data.pwd.raw[0], - config_pages->auth_data.pwd.raw[1], - config_pages->auth_data.pwd.raw[2], - config_pages->auth_data.pwd.raw[3]); - widget_add_string_element( - widget, 0, 28, AlignLeft, AlignTop, FontSecondary, furi_string_get_cstr(temp_str)); - furi_string_printf( - temp_str, - "PACK: %02X %02X", - config_pages->auth_data.pack.raw[0], - config_pages->auth_data.pack.raw[1]); - widget_add_string_element( - widget, 0, 39, AlignLeft, AlignTop, FontSecondary, furi_string_get_cstr(temp_str)); - } - furi_string_printf( - temp_str, "Pages Read: %d/%d", mf_ul_data->data_read / 4, mf_ul_data->data_size / 4); - widget_add_string_element( - widget, 0, 50, AlignLeft, AlignTop, FontSecondary, furi_string_get_cstr(temp_str)); - widget_add_button_element( - widget, - GuiButtonTypeRight, - "Save", - nfc_scene_mf_ultralight_read_auth_result_widget_callback, - nfc); - - furi_string_free(temp_str); - notification_message(nfc->notifications, &sequence_set_green_255); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_mf_ultralight_read_auth_result_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeRight) { - nfc->dev->format = NfcDeviceSaveFormatMifareUl; - // Clear device name - nfc_device_set_name(nfc->dev, ""); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - MfUltralightData* mf_ul_data = &nfc->dev->dev_data.mf_ul_data; - if(mf_ul_data->auth_method == MfUltralightAuthMethodManual || - mf_ul_data->auth_method == MfUltralightAuthMethodAuto) { - consumed = scene_manager_previous_scene(nfc->scene_manager); - } else { - NfcScene next_scene; - if((mf_ul_data->data_read == mf_ul_data->data_size) && (mf_ul_data->data_read > 0)) { - next_scene = NfcSceneMfUltralightMenu; - } else { - next_scene = NfcSceneMfUltralightUnlockMenu; - } - - consumed = - scene_manager_search_and_switch_to_previous_scene(nfc->scene_manager, next_scene); - } - } - - return consumed; -} - -void nfc_scene_mf_ultralight_read_auth_result_on_exit(void* context) { - Nfc* nfc = context; - - // Clean views - widget_reset(nfc->widget); - - notification_message_block(nfc->notifications, &sequence_reset_green); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_read_success.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_read_success.c deleted file mode 100644 index cb5ccd6e8..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_read_success.c +++ /dev/null @@ -1,84 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_mf_ultralight_read_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - Nfc* nfc = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_mf_ultralight_read_success_on_enter(void* context) { - Nfc* nfc = context; - - // Setup widget view - FuriHalNfcDevData* data = &nfc->dev->dev_data.nfc_data; - MfUltralightData* mf_ul_data = &nfc->dev->dev_data.mf_ul_data; - Widget* widget = nfc->widget; - widget_add_button_element( - widget, - GuiButtonTypeLeft, - "Retry", - nfc_scene_mf_ultralight_read_success_widget_callback, - nfc); - widget_add_button_element( - widget, - GuiButtonTypeRight, - "More", - nfc_scene_mf_ultralight_read_success_widget_callback, - nfc); - - FuriString* temp_str = NULL; - if(furi_string_size(nfc->dev->dev_data.parsed_data)) { - temp_str = furi_string_alloc_set(nfc->dev->dev_data.parsed_data); - } else { - temp_str = furi_string_alloc_printf("\e#%s\n", nfc_mf_ul_type(mf_ul_data->type, true)); - furi_string_cat_printf(temp_str, "UID:"); - for(size_t i = 0; i < data->uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", data->uid[i]); - } - furi_string_cat_printf( - temp_str, "\nPages Read: %d/%d", mf_ul_data->data_read / 4, mf_ul_data->data_size / 4); - if(mf_ul_data->data_read != mf_ul_data->data_size) { - furi_string_cat_printf(temp_str, "\nPassword-protected pages!"); - } - } - widget_add_text_scroll_element(widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - notification_message_block(nfc->notifications, &sequence_set_green_255); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_mf_ultralight_read_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneRetryConfirm); - consumed = true; - } else if(event.event == GuiButtonTypeRight) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightMenu); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneExitConfirm); - consumed = true; - } - - return consumed; -} - -void nfc_scene_mf_ultralight_read_success_on_exit(void* context) { - Nfc* nfc = context; - - notification_message_block(nfc->notifications, &sequence_reset_green); - - // Clean view - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_auto.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_auto.c deleted file mode 100644 index c59fe3a7d..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_auto.c +++ /dev/null @@ -1,64 +0,0 @@ -#include "../nfc_i.h" - -bool nfc_scene_mf_ultralight_unlock_auto_worker_callback(NfcWorkerEvent event, void* context) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, event); - return true; -} - -void nfc_scene_mf_ultralight_unlock_auto_on_enter(void* context) { - Nfc* nfc = context; - - // Setup view - widget_add_string_multiline_element( - nfc->widget, - 54, - 30, - AlignLeft, - AlignCenter, - FontPrimary, - "Touch the\nreader to get\npassword..."); - widget_add_icon_element(nfc->widget, 0, 15, &I_Modern_reader_18x34); - widget_add_icon_element(nfc->widget, 20, 12, &I_Move_flipper_26x39); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - - // Start worker - nfc_worker_start( - nfc->worker, - NfcWorkerStateMfUltralightEmulate, - &nfc->dev->dev_data, - nfc_scene_mf_ultralight_unlock_auto_worker_callback, - nfc); - - nfc_blink_read_start(nfc); -} - -bool nfc_scene_mf_ultralight_unlock_auto_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if((event.event == NfcWorkerEventMfUltralightPwdAuth)) { - MfUltralightAuth* auth = &nfc->dev->dev_data.mf_ul_auth; - memcpy(nfc->byte_input_store, auth->pwd.raw, sizeof(auth->pwd.raw)); - nfc->dev->dev_data.mf_ul_data.auth_method = MfUltralightAuthMethodAuto; - nfc_worker_stop(nfc->worker); - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightUnlockWarn); - consumed = true; - } - } - return consumed; -} - -void nfc_scene_mf_ultralight_unlock_auto_on_exit(void* context) { - Nfc* nfc = context; - - // Stop worker - nfc_worker_stop(nfc->worker); - // Clear view - widget_reset(nfc->widget); - - nfc_blink_stop(nfc); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_menu.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_menu.c index 484629b0b..4d97040ee 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_menu.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_menu.c @@ -1,29 +1,29 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" enum SubmenuIndex { - SubmenuIndexMfUlUnlockMenuAuto, + SubmenuIndexMfUlUnlockMenuReader, SubmenuIndexMfUlUnlockMenuAmeebo, SubmenuIndexMfUlUnlockMenuXiaomi, SubmenuIndexMfUlUnlockMenuManual, }; void nfc_scene_mf_ultralight_unlock_menu_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, index); } void nfc_scene_mf_ultralight_unlock_menu_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; Submenu* submenu = nfc->submenu; uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneMfUltralightUnlockMenu); - if(nfc->dev->dev_data.protocol == NfcDeviceProtocolMifareUl) { + if(nfc_device_get_protocol(nfc->nfc_device) == NfcProtocolMfUltralight) { submenu_add_item( submenu, "Unlock With Reader", - SubmenuIndexMfUlUnlockMenuAuto, + SubmenuIndexMfUlUnlockMenuReader, nfc_scene_mf_ultralight_unlock_menu_submenu_callback, nfc); } @@ -50,24 +50,25 @@ void nfc_scene_mf_ultralight_unlock_menu_on_enter(void* context) { } bool nfc_scene_mf_ultralight_unlock_menu_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == SubmenuIndexMfUlUnlockMenuManual) { - nfc->dev->dev_data.mf_ul_data.auth_method = MfUltralightAuthMethodManual; + nfc->mf_ul_auth->type = MfUltralightAuthTypeManual; scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightKeyInput); consumed = true; } else if(event.event == SubmenuIndexMfUlUnlockMenuAmeebo) { - nfc->dev->dev_data.mf_ul_data.auth_method = MfUltralightAuthMethodAmeebo; + nfc->mf_ul_auth->type = MfUltralightAuthTypeAmiibo; scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightUnlockWarn); consumed = true; } else if(event.event == SubmenuIndexMfUlUnlockMenuXiaomi) { - nfc->dev->dev_data.mf_ul_data.auth_method = MfUltralightAuthMethodXiaomi; + nfc->mf_ul_auth->type = MfUltralightAuthTypeXiaomi; scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightUnlockWarn); consumed = true; - } else if(event.event == SubmenuIndexMfUlUnlockMenuAuto) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightUnlockAuto); + } else if(event.event == SubmenuIndexMfUlUnlockMenuReader) { + nfc->mf_ul_auth->type = MfUltralightAuthTypeReader; + scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightCapturePass); consumed = true; } scene_manager_set_scene_state( @@ -77,7 +78,7 @@ bool nfc_scene_mf_ultralight_unlock_menu_on_event(void* context, SceneManagerEve } void nfc_scene_mf_ultralight_unlock_menu_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; submenu_reset(nfc->submenu); } diff --git a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_warn.c b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_warn.c index af2eca0ce..6be051ced 100644 --- a/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_warn.c +++ b/applications/main/nfc/scenes/nfc_scene_mf_ultralight_unlock_warn.c @@ -1,45 +1,41 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" #include void nfc_scene_mf_ultralight_unlock_warn_dialog_callback(DialogExResult result, void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, result); } void nfc_scene_mf_ultralight_unlock_warn_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; DialogEx* dialog_ex = nfc->dialog_ex; - MfUltralightAuthMethod auth_method = nfc->dev->dev_data.mf_ul_data.auth_method; dialog_ex_set_context(dialog_ex, nfc); dialog_ex_set_result_callback(dialog_ex, nfc_scene_mf_ultralight_unlock_warn_dialog_callback); - if(auth_method == MfUltralightAuthMethodManual || auth_method == MfUltralightAuthMethodAuto) { + MfUltralightAuthType type = nfc->mf_ul_auth->type; + if((type == MfUltralightAuthTypeReader) || (type == MfUltralightAuthTypeManual)) { // Build dialog text - MfUltralightAuth* auth = &nfc->dev->dev_data.mf_ul_auth; FuriString* password_str = furi_string_alloc_set_str("Try to unlock the card with\npassword: "); - for(size_t i = 0; i < sizeof(auth->pwd.raw); ++i) { - furi_string_cat_printf(password_str, "%02X ", nfc->byte_input_store[i]); + for(size_t i = 0; i < sizeof(nfc->mf_ul_auth->password.data); i++) { + furi_string_cat_printf(password_str, "%02X ", nfc->mf_ul_auth->password.data[i]); } furi_string_cat_str(password_str, "?\nCaution, a wrong password\ncan block the card!"); nfc_text_store_set(nfc, furi_string_get_cstr(password_str)); furi_string_free(password_str); - dialog_ex_set_header( - dialog_ex, - auth_method == MfUltralightAuthMethodAuto ? "Password captured!" : "Risky function!", - 64, - 0, - AlignCenter, - AlignTop); + const char* message = (type == MfUltralightAuthTypeReader) ? "Password captured!" : + "Risky function!"; + dialog_ex_set_header(dialog_ex, message, 64, 0, AlignCenter, AlignTop); dialog_ex_set_text(dialog_ex, nfc->text_store, 64, 12, AlignCenter, AlignTop); dialog_ex_set_left_button_text(dialog_ex, "Cancel"); dialog_ex_set_right_button_text(dialog_ex, "Continue"); - if(auth_method == MfUltralightAuthMethodAuto) + if(type == MfUltralightAuthTypeReader) { notification_message(nfc->notifications, &sequence_set_green_255); + } } else { dialog_ex_set_header(dialog_ex, "Risky function!", 64, 4, AlignCenter, AlignTop); dialog_ex_set_text( @@ -52,19 +48,20 @@ void nfc_scene_mf_ultralight_unlock_warn_on_enter(void* context) { } bool nfc_scene_mf_ultralight_unlock_warn_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; - MfUltralightAuthMethod auth_method = nfc->dev->dev_data.mf_ul_data.auth_method; - if(auth_method == MfUltralightAuthMethodManual || auth_method == MfUltralightAuthMethodAuto) { + nfc->protocols_detected[0] = nfc_device_get_protocol(nfc->nfc_device); + MfUltralightAuthType type = nfc->mf_ul_auth->type; + if((type == MfUltralightAuthTypeReader) || (type == MfUltralightAuthTypeManual)) { if(event.type == SceneManagerEventTypeCustom) { if(event.event == DialogExResultRight) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightReadAuth); + scene_manager_next_scene(nfc->scene_manager, NfcSceneRead); dolphin_deed(DolphinDeedNfcRead); consumed = true; } else if(event.event == DialogExResultLeft) { - if(auth_method == MfUltralightAuthMethodAuto) { + if(type == MfUltralightAuthTypeReader) { consumed = scene_manager_search_and_switch_to_previous_scene( nfc->scene_manager, NfcSceneMfUltralightUnlockMenu); } else { @@ -78,7 +75,9 @@ bool nfc_scene_mf_ultralight_unlock_warn_on_event(void* context, SceneManagerEve } else { if(event.type == SceneManagerEventTypeCustom) { if(event.event == DialogExResultCenter) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightReadAuth); + const NfcProtocol mfu_protocol[] = {NfcProtocolMfUltralight}; + nfc_app_set_detected_protocols(nfc, mfu_protocol, COUNT_OF(mfu_protocol)); + scene_manager_next_scene(nfc->scene_manager, NfcSceneRead); dolphin_deed(DolphinDeedNfcRead); consumed = true; } @@ -89,7 +88,7 @@ bool nfc_scene_mf_ultralight_unlock_warn_on_event(void* context, SceneManagerEve } void nfc_scene_mf_ultralight_unlock_warn_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; dialog_ex_reset(nfc->dialog_ex); nfc_text_store_clear(nfc); diff --git a/applications/main/nfc/scenes/nfc_scene_mfkey_complete.c b/applications/main/nfc/scenes/nfc_scene_mfkey_complete.c deleted file mode 100644 index 04515f24f..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mfkey_complete.c +++ /dev/null @@ -1,49 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_mfkey_complete_callback(GuiButtonType result, InputType type, void* context) { - Nfc* nfc = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_mfkey_complete_on_enter(void* context) { - Nfc* nfc = context; - - widget_add_string_element(nfc->widget, 64, 0, AlignCenter, AlignTop, FontPrimary, "Complete!"); - widget_add_string_multiline_element( - nfc->widget, - 64, - 32, - AlignCenter, - AlignCenter, - FontSecondary, - "Now use Mfkey32\nto extract keys"); - widget_add_button_element( - nfc->widget, GuiButtonTypeCenter, "OK", nfc_scene_mfkey_complete_callback, nfc); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_mfkey_complete_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeCenter) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneStart); - } - } else if(event.event == SceneManagerEventTypeBack) { - consumed = - scene_manager_search_and_switch_to_previous_scene(nfc->scene_manager, NfcSceneStart); - } - - return consumed; -} - -void nfc_scene_mfkey_complete_on_exit(void* context) { - Nfc* nfc = context; - - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_mfkey_nonces_info.c b/applications/main/nfc/scenes/nfc_scene_mfkey_nonces_info.c deleted file mode 100644 index 6d9852f3e..000000000 --- a/applications/main/nfc/scenes/nfc_scene_mfkey_nonces_info.c +++ /dev/null @@ -1,55 +0,0 @@ -#include "../nfc_i.h" -#include - -void nfc_scene_mfkey_nonces_info_callback(GuiButtonType result, InputType type, void* context) { - Nfc* nfc = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_mfkey_nonces_info_on_enter(void* context) { - Nfc* nfc = context; - - FuriString* temp_str; - temp_str = furi_string_alloc(); - - uint16_t nonces_saved = mfkey32_get_auth_sectors(temp_str); - widget_add_text_scroll_element(nfc->widget, 0, 22, 128, 42, furi_string_get_cstr(temp_str)); - furi_string_printf(temp_str, "Nonce pairs saved: %d", nonces_saved); - widget_add_string_element( - nfc->widget, 0, 0, AlignLeft, AlignTop, FontPrimary, furi_string_get_cstr(temp_str)); - widget_add_string_element( - nfc->widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "Authenticated sectors:"); - - widget_add_button_element( - nfc->widget, GuiButtonTypeCenter, "OK", nfc_scene_mfkey_nonces_info_callback, nfc); - - furi_string_free(temp_str); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_mfkey_nonces_info_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeCenter) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfkeyComplete); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = - scene_manager_search_and_switch_to_previous_scene(nfc->scene_manager, NfcSceneStart); - } - - return consumed; -} - -void nfc_scene_mfkey_nonces_info_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_more_info.c b/applications/main/nfc/scenes/nfc_scene_more_info.c new file mode 100644 index 000000000..b74e30295 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_more_info.c @@ -0,0 +1,13 @@ +#include "../helpers/protocol_support/nfc_protocol_support.h" + +void nfc_scene_more_info_on_enter(void* context) { + nfc_protocol_support_on_enter(NfcProtocolSupportSceneMoreInfo, context); +} + +bool nfc_scene_more_info_on_event(void* context, SceneManagerEvent event) { + return nfc_protocol_support_on_event(NfcProtocolSupportSceneMoreInfo, context, event); +} + +void nfc_scene_more_info_on_exit(void* context) { + nfc_protocol_support_on_exit(NfcProtocolSupportSceneMoreInfo, context); +} diff --git a/applications/main/nfc/scenes/nfc_scene_nfc_data_info.c b/applications/main/nfc/scenes/nfc_scene_nfc_data_info.c deleted file mode 100644 index 66a9174df..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfc_data_info.c +++ /dev/null @@ -1,309 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_nfc_data_info_widget_callback(GuiButtonType result, InputType type, void* context) { - Nfc* nfc = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_slix_build_string( - FuriString* temp_str, - NfcVData* nfcv_data, - SlixTypeFeatures features, - const char* type) { - furi_string_cat_printf(temp_str, "Type: %s\n", type); - furi_string_cat_printf(temp_str, "Keys:\n"); - if(features & SlixFeatureRead) { - furi_string_cat_printf( - temp_str, - " Read %08llX%s\n", - nfc_util_bytes2num(nfcv_data->sub_data.slix.key_read, 4), - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsHasKeyRead) ? "" : " (unset)"); - } - if(features & SlixFeatureWrite) { - furi_string_cat_printf( - temp_str, - " Write %08llX%s\n", - nfc_util_bytes2num(nfcv_data->sub_data.slix.key_write, 4), - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsHasKeyWrite) ? "" : " (unset)"); - } - if(features & SlixFeaturePrivacy) { - furi_string_cat_printf( - temp_str, - " Privacy %08llX%s\n", - nfc_util_bytes2num(nfcv_data->sub_data.slix.key_privacy, 4), - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsHasKeyPrivacy) ? "" : " (unset)"); - furi_string_cat_printf( - temp_str, - " Privacy mode %s\n", - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsPrivacy) ? "ENABLED" : "DISABLED"); - } - if(features & SlixFeatureDestroy) { - furi_string_cat_printf( - temp_str, - " Destroy %08llX%s\n", - nfc_util_bytes2num(nfcv_data->sub_data.slix.key_destroy, 4), - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsHasKeyDestroy) ? "" : " (unset)"); - } - if(features & SlixFeatureEas) { - furi_string_cat_printf( - temp_str, - " EAS %08llX%s\n", - nfc_util_bytes2num(nfcv_data->sub_data.slix.key_eas, 4), - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsHasKeyEas) ? "" : " (unset)"); - } - if(features & SlixFeatureSignature) { - furi_string_cat_printf( - temp_str, - "Signature %08llX...\n", - nfc_util_bytes2num(nfcv_data->sub_data.slix.signature, 4)); - } - furi_string_cat_printf( - temp_str, - "DSFID: %02X %s\n", - nfcv_data->dsfid, - (nfcv_data->security_status[0] & NfcVLockBitDsfid) ? "(locked)" : ""); - furi_string_cat_printf( - temp_str, - "AFI: %02X %s\n", - nfcv_data->afi, - (nfcv_data->security_status[0] & NfcVLockBitAfi) ? "(locked)" : ""); - furi_string_cat_printf( - temp_str, - "EAS: %s\n", - (nfcv_data->security_status[0] & NfcVLockBitEas) ? "locked" : "not locked"); - - if(features & SlixFeatureProtection) { - furi_string_cat_printf( - temp_str, - "PPL: %s\n", - (nfcv_data->security_status[0] & NfcVLockBitPpl) ? "locked" : "not locked"); - furi_string_cat_printf(temp_str, "Prot.ptr %02X\n", nfcv_data->sub_data.slix.pp_pointer); - furi_string_cat_printf(temp_str, "Prot.con %02X\n", nfcv_data->sub_data.slix.pp_condition); - } -} - -void nfc_scene_nfc_data_info_on_enter(void* context) { - Nfc* nfc = context; - Widget* widget = nfc->widget; - FuriHalNfcDevData* nfc_data = &nfc->dev->dev_data.nfc_data; - NfcDeviceData* dev_data = &nfc->dev->dev_data; - NfcProtocol protocol = dev_data->protocol; - uint8_t text_scroll_height = 0; - if((protocol == NfcDeviceProtocolMifareDesfire) || (protocol == NfcDeviceProtocolMifareUl) || - (protocol == NfcDeviceProtocolMifareClassic)) { - widget_add_button_element( - widget, GuiButtonTypeRight, "More", nfc_scene_nfc_data_info_widget_callback, nfc); - text_scroll_height = 52; - } else { - text_scroll_height = 64; - } - - FuriString* temp_str; - temp_str = furi_string_alloc(); - // Set name if present - if(nfc->dev->dev_name[0] != '\0') { - furi_string_printf(temp_str, "\ec%s\n", nfc->dev->dev_name); - } - - // Set tag type - if(protocol == NfcDeviceProtocolEMV) { - furi_string_cat_printf(temp_str, "\e#EMV Bank Card\n"); - } else if(protocol == NfcDeviceProtocolMifareUl) { - furi_string_cat_printf( - temp_str, "\e#%s\n", nfc_mf_ul_type(dev_data->mf_ul_data.type, true)); - } else if(protocol == NfcDeviceProtocolMifareClassic) { - furi_string_cat_printf( - temp_str, "\e#%s\n", nfc_mf_classic_type(dev_data->mf_classic_data.type)); - } else if(protocol == NfcDeviceProtocolMifareDesfire) { - furi_string_cat_printf(temp_str, "\e#MIFARE DESFire\n"); - } else if(protocol == NfcDeviceProtocolNfcV) { - switch(dev_data->nfcv_data.sub_type) { - case NfcVTypePlain: - furi_string_cat_printf(temp_str, "\e#ISO15693\n"); - break; - case NfcVTypeSlix: - furi_string_cat_printf(temp_str, "\e#ISO15693 SLIX\n"); - break; - case NfcVTypeSlixS: - furi_string_cat_printf(temp_str, "\e#ISO15693 SLIX-S\n"); - break; - case NfcVTypeSlixL: - furi_string_cat_printf(temp_str, "\e#ISO15693 SLIX-L\n"); - break; - case NfcVTypeSlix2: - furi_string_cat_printf(temp_str, "\e#ISO15693 SLIX2\n"); - break; - default: - furi_string_cat_printf(temp_str, "\e#ISO15693 (unknown)\n"); - break; - } - } else { - furi_string_cat_printf(temp_str, "\e#Unknown ISO tag\n"); - } - - // Set tag iso data - if(protocol == NfcDeviceProtocolNfcV) { - NfcVData* nfcv_data = &nfc->dev->dev_data.nfcv_data; - - furi_string_cat_printf(temp_str, "UID:\n"); - for(size_t i = 0; i < nfc_data->uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", nfc_data->uid[i]); - } - furi_string_cat_printf(temp_str, "\n"); - - furi_string_cat_printf(temp_str, "IC Ref: %d\n", nfcv_data->ic_ref); - furi_string_cat_printf(temp_str, "Blocks: %d\n", nfcv_data->block_num); - furi_string_cat_printf(temp_str, "Blocksize: %d\n", nfcv_data->block_size); - - switch(dev_data->nfcv_data.sub_type) { - case NfcVTypePlain: - furi_string_cat_printf(temp_str, "Type: Plain\n"); - break; - case NfcVTypeSlix: - nfc_scene_slix_build_string(temp_str, nfcv_data, SlixFeatureSlix, "SLIX"); - break; - case NfcVTypeSlixS: - nfc_scene_slix_build_string(temp_str, nfcv_data, SlixFeatureSlixS, "SLIX-S"); - break; - case NfcVTypeSlixL: - nfc_scene_slix_build_string(temp_str, nfcv_data, SlixFeatureSlixL, "SLIX-L"); - break; - case NfcVTypeSlix2: - nfc_scene_slix_build_string(temp_str, nfcv_data, SlixFeatureSlix2, "SLIX2"); - break; - default: - furi_string_cat_printf(temp_str, "\e#ISO15693 (unknown)\n"); - break; - } - - furi_string_cat_printf( - temp_str, "Data (%d byte)\n", nfcv_data->block_num * nfcv_data->block_size); - - int maxBlocks = nfcv_data->block_num; - if(maxBlocks > 32) { - maxBlocks = 32; - furi_string_cat_printf(temp_str, "(truncated to %d blocks)\n", maxBlocks); - } - - for(int block = 0; block < maxBlocks; block++) { - const char* status = (nfcv_data->security_status[block] & 0x01) ? "(lck)" : ""; - for(int pos = 0; pos < nfcv_data->block_size; pos++) { - furi_string_cat_printf( - temp_str, " %02X", nfcv_data->data[block * nfcv_data->block_size + pos]); - } - furi_string_cat_printf(temp_str, " %s\n", status); - } - - } else { - char iso_type = FURI_BIT(nfc_data->sak, 5) ? '4' : '3'; - furi_string_cat_printf(temp_str, "ISO 14443-%c (NFC-A)\n", iso_type); - furi_string_cat_printf(temp_str, "UID:"); - for(size_t i = 0; i < nfc_data->uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", nfc_data->uid[i]); - } - furi_string_cat_printf( - temp_str, "\nATQA: %02X %02X ", nfc_data->atqa[1], nfc_data->atqa[0]); - furi_string_cat_printf(temp_str, " SAK: %02X", nfc_data->sak); - } - - // Set application specific data - if(protocol == NfcDeviceProtocolMifareDesfire) { - MifareDesfireData* data = &dev_data->mf_df_data; - uint32_t bytes_total = 1UL << (data->version.sw_storage >> 1); - uint32_t bytes_free = data->free_memory ? data->free_memory->bytes : 0; - furi_string_cat_printf(temp_str, "\n%lu", bytes_total); - if(data->version.sw_storage & 1) { - furi_string_push_back(temp_str, '+'); - } - furi_string_cat_printf(temp_str, " bytes, %lu bytes free\n", bytes_free); - - uint16_t n_apps = 0; - uint16_t n_files = 0; - for(MifareDesfireApplication* app = data->app_head; app; app = app->next) { - n_apps++; - for(MifareDesfireFile* file = app->file_head; file; file = file->next) { - n_files++; - } - } - furi_string_cat_printf(temp_str, "%d Application", n_apps); - if(n_apps != 1) { - furi_string_push_back(temp_str, 's'); - } - furi_string_cat_printf(temp_str, ", %d file", n_files); - if(n_files != 1) { - furi_string_push_back(temp_str, 's'); - } - } else if(protocol == NfcDeviceProtocolMifareUl) { - MfUltralightData* data = &dev_data->mf_ul_data; - furi_string_cat_printf( - temp_str, "\nPages Read %d/%d", data->data_read / 4, data->data_size / 4); - if(data->data_size > data->data_read) { - furi_string_cat_printf(temp_str, "\nPassword-protected"); - } else if(data->auth_success) { - MfUltralightConfigPages* config_pages = mf_ultralight_get_config_pages(data); - if(config_pages) { - furi_string_cat_printf( - temp_str, - "\nPassword: %02X %02X %02X %02X", - config_pages->auth_data.pwd.raw[0], - config_pages->auth_data.pwd.raw[1], - config_pages->auth_data.pwd.raw[2], - config_pages->auth_data.pwd.raw[3]); - furi_string_cat_printf( - temp_str, - "\nPACK: %02X %02X", - config_pages->auth_data.pack.raw[0], - config_pages->auth_data.pack.raw[1]); - } - } - } else if(protocol == NfcDeviceProtocolMifareClassic) { - MfClassicData* data = &dev_data->mf_classic_data; - uint8_t sectors_total = mf_classic_get_total_sectors_num(data->type); - uint8_t keys_total = sectors_total * 2; - uint8_t keys_found = 0; - uint8_t sectors_read = 0; - mf_classic_get_read_sectors_and_keys(data, §ors_read, &keys_found); - furi_string_cat_printf(temp_str, "\nKeys Found %d/%d", keys_found, keys_total); - furi_string_cat_printf(temp_str, "\nSectors Read %d/%d", sectors_read, sectors_total); - } - - // Add text scroll widget - widget_add_text_scroll_element( - widget, 0, 0, 128, text_scroll_height, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_nfc_data_info_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - NfcProtocol protocol = nfc->dev->dev_data.protocol; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeRight) { - if(protocol == NfcDeviceProtocolMifareDesfire) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfDesfireData); - consumed = true; - } else if(protocol == NfcDeviceProtocolMifareUl) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightData); - consumed = true; - } else if(protocol == NfcDeviceProtocolMifareClassic) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicData); - } else if(protocol == NfcDeviceProtocolNfcV) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVMenu); - consumed = true; - } - } - } - - return consumed; -} - -void nfc_scene_nfc_data_info_on_exit(void* context) { - Nfc* nfc = context; - - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_nfca_menu.c b/applications/main/nfc/scenes/nfc_scene_nfca_menu.c deleted file mode 100644 index 9779470a3..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfca_menu.c +++ /dev/null @@ -1,68 +0,0 @@ -#include "../nfc_i.h" -#include - -enum SubmenuIndex { - SubmenuIndexSaveUid, - SubmenuIndexEmulateUid, - SubmenuIndexInfo, -}; - -void nfc_scene_nfca_menu_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_nfca_menu_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - - submenu_add_item( - submenu, "Save UID", SubmenuIndexSaveUid, nfc_scene_nfca_menu_submenu_callback, nfc); - submenu_add_item( - submenu, "Emulate UID", SubmenuIndexEmulateUid, nfc_scene_nfca_menu_submenu_callback, nfc); - submenu_add_item(submenu, "Info", SubmenuIndexInfo, nfc_scene_nfca_menu_submenu_callback, nfc); - - submenu_set_selected_item( - nfc->submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneNfcaMenu)); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_nfca_menu_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexSaveUid) { - nfc->dev->format = NfcDeviceSaveFormatUid; - // Clear device name - nfc_device_set_name(nfc->dev, ""); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); - consumed = true; - } else if(event.event == SubmenuIndexEmulateUid) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneEmulateUid); - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSetType)) { - dolphin_deed(DolphinDeedNfcAddEmulate); - } else { - dolphin_deed(DolphinDeedNfcEmulate); - } - consumed = true; - } else if(event.event == SubmenuIndexInfo) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcDataInfo); - consumed = true; - } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneNfcaMenu, event.event); - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_previous_scene(nfc->scene_manager); - } - - return consumed; -} - -void nfc_scene_nfca_menu_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_nfca_read_success.c b/applications/main/nfc/scenes/nfc_scene_nfca_read_success.c deleted file mode 100644 index a38f31a98..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfca_read_success.c +++ /dev/null @@ -1,73 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_nfca_read_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - furi_assert(context); - Nfc* nfc = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_nfca_read_success_on_enter(void* context) { - Nfc* nfc = context; - - // Setup view - FuriHalNfcDevData* data = &nfc->dev->dev_data.nfc_data; - Widget* widget = nfc->widget; - - FuriString* temp_str; - temp_str = furi_string_alloc_set("\e#Unknown ISO tag\n"); - - notification_message_block(nfc->notifications, &sequence_set_green_255); - - char iso_type = FURI_BIT(data->sak, 5) ? '4' : '3'; - furi_string_cat_printf(temp_str, "ISO 14443-%c (NFC-A)\n", iso_type); - furi_string_cat_printf(temp_str, "UID:"); - for(size_t i = 0; i < data->uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", data->uid[i]); - } - furi_string_cat_printf(temp_str, "\nATQA: %02X %02X ", data->atqa[1], data->atqa[0]); - furi_string_cat_printf(temp_str, " SAK: %02X", data->sak); - - widget_add_text_scroll_element(widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_scene_nfca_read_success_widget_callback, nfc); - widget_add_button_element( - widget, GuiButtonTypeRight, "More", nfc_scene_nfca_read_success_widget_callback, nfc); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_nfca_read_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneRetryConfirm); - consumed = true; - } else if(event.event == GuiButtonTypeRight) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcaMenu); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneExitConfirm); - consumed = true; - } - return consumed; -} - -void nfc_scene_nfca_read_success_on_exit(void* context) { - Nfc* nfc = context; - - notification_message_block(nfc->notifications, &sequence_reset_green); - - // Clear view - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_nfcv_emulate.c b/applications/main/nfc/scenes/nfc_scene_nfcv_emulate.c deleted file mode 100644 index d812988bd..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfcv_emulate.c +++ /dev/null @@ -1,169 +0,0 @@ -#include "../nfc_i.h" - -#define NFC_SCENE_EMULATE_NFCV_LOG_SIZE_MAX (200) - -enum { - NfcSceneNfcVEmulateStateWidget, - NfcSceneNfcVEmulateStateTextBox, -}; - -bool nfc_scene_nfcv_emulate_worker_callback(NfcWorkerEvent event, void* context) { - furi_assert(context); - Nfc* nfc = context; - - switch(event) { - case NfcWorkerEventNfcVCommandExecuted: - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventUpdateLog); - } - break; - case NfcWorkerEventNfcVContentChanged: - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventSaveShadow); - break; - default: - break; - } - return true; -} - -void nfc_scene_nfcv_emulate_widget_callback(GuiButtonType result, InputType type, void* context) { - furi_assert(context); - Nfc* nfc = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_nfcv_emulate_textbox_callback(void* context) { - furi_assert(context); - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -static void nfc_scene_nfcv_emulate_widget_config(Nfc* nfc, bool data_received) { - FuriHalNfcDevData* data = &nfc->dev->dev_data.nfc_data; - Widget* widget = nfc->widget; - widget_reset(widget); - FuriString* info_str; - info_str = furi_string_alloc(); - - widget_add_icon_element(widget, 0, 3, &I_NFC_dolphin_emulation_47x61); - widget_add_string_multiline_element( - widget, 87, 13, AlignCenter, AlignTop, FontPrimary, "Emulating\nNFC V"); - if(strcmp(nfc->dev->dev_name, "") != 0) { - furi_string_printf(info_str, "%s", nfc->dev->dev_name); - } else { - for(uint8_t i = 0; i < data->uid_len; i++) { - furi_string_cat_printf(info_str, "%02X ", data->uid[i]); - } - } - furi_string_trim(info_str); - widget_add_text_box_element( - widget, 52, 40, 70, 21, AlignCenter, AlignTop, furi_string_get_cstr(info_str), true); - furi_string_free(info_str); - if(data_received) { - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - widget_add_button_element( - widget, GuiButtonTypeCenter, "Log", nfc_scene_nfcv_emulate_widget_callback, nfc); - } - } -} - -void nfc_scene_nfcv_emulate_on_enter(void* context) { - Nfc* nfc = context; - - // Setup Widget - nfc_scene_nfcv_emulate_widget_config(nfc, false); - // Setup TextBox - TextBox* text_box = nfc->text_box; - text_box_set_font(text_box, TextBoxFontHex); - text_box_set_focus(text_box, TextBoxFocusEnd); - text_box_set_text(text_box, ""); - furi_string_reset(nfc->text_box_store); - - // Set Widget state and view - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneNfcVEmulate, NfcSceneNfcVEmulateStateWidget); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - // Start worker - memset(&nfc->dev->dev_data.reader_data, 0, sizeof(NfcReaderRequestData)); - nfc_worker_start( - nfc->worker, - NfcWorkerStateNfcVEmulate, - &nfc->dev->dev_data, - nfc_scene_nfcv_emulate_worker_callback, - nfc); - - nfc_blink_emulate_start(nfc); -} - -bool nfc_scene_nfcv_emulate_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - NfcVData* nfcv_data = &nfc->dev->dev_data.nfcv_data; - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneNfcVEmulate); - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventUpdateLog) { - // Add data button to widget if data is received for the first time - if(strlen(nfcv_data->last_command) > 0) { - if(!furi_string_size(nfc->text_box_store)) { - nfc_scene_nfcv_emulate_widget_config(nfc, true); - } - /* use the last n bytes from the log so there's enough space for the new log entry */ - size_t maxSize = - NFC_SCENE_EMULATE_NFCV_LOG_SIZE_MAX - (strlen(nfcv_data->last_command) + 1); - if(furi_string_size(nfc->text_box_store) >= maxSize) { - furi_string_right(nfc->text_box_store, (strlen(nfcv_data->last_command) + 1)); - } - furi_string_cat_printf(nfc->text_box_store, "%s", nfcv_data->last_command); - furi_string_push_back(nfc->text_box_store, '\n'); - text_box_set_text(nfc->text_box, furi_string_get_cstr(nfc->text_box_store)); - - /* clear previously logged command */ - strcpy(nfcv_data->last_command, ""); - } - consumed = true; - } else if(event.event == NfcCustomEventSaveShadow) { - if(furi_string_size(nfc->dev->load_path)) { - nfc_device_save_shadow(nfc->dev, furi_string_get_cstr(nfc->dev->load_path)); - } - consumed = true; - } else if(event.event == GuiButtonTypeCenter && state == NfcSceneNfcVEmulateStateWidget) { - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewTextBox); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneNfcVEmulate, NfcSceneNfcVEmulateStateTextBox); - } - consumed = true; - } else if(event.event == NfcCustomEventViewExit && state == NfcSceneNfcVEmulateStateTextBox) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneNfcVEmulate, NfcSceneNfcVEmulateStateWidget); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - if(state == NfcSceneNfcVEmulateStateTextBox) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneNfcVEmulate, NfcSceneNfcVEmulateStateWidget); - consumed = true; - } - } - - return consumed; -} - -void nfc_scene_nfcv_emulate_on_exit(void* context) { - Nfc* nfc = context; - - // Stop worker - nfc_worker_stop(nfc->worker); - - // Clear view - widget_reset(nfc->widget); - text_box_reset(nfc->text_box); - furi_string_reset(nfc->text_box_store); - - nfc_blink_stop(nfc); -} diff --git a/applications/main/nfc/scenes/nfc_scene_nfcv_key_input.c b/applications/main/nfc/scenes/nfc_scene_nfcv_key_input.c deleted file mode 100644 index 13d903c4b..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfcv_key_input.c +++ /dev/null @@ -1,48 +0,0 @@ -#include "../nfc_i.h" -#include - -void nfc_scene_nfcv_key_input_byte_input_callback(void* context) { - Nfc* nfc = context; - NfcVSlixData* data = &nfc->dev->dev_data.nfcv_data.sub_data.slix; - - memcpy(data->key_privacy, nfc->byte_input_store, 4); - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventByteInputDone); -} - -void nfc_scene_nfcv_key_input_on_enter(void* context) { - Nfc* nfc = context; - - // Setup view - ByteInput* byte_input = nfc->byte_input; - byte_input_set_header_text(byte_input, "Enter The Password In Hex"); - byte_input_set_result_callback( - byte_input, - nfc_scene_nfcv_key_input_byte_input_callback, - NULL, - nfc, - nfc->byte_input_store, - 4); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewByteInput); -} - -bool nfc_scene_nfcv_key_input_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventByteInputDone) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVUnlock); - dolphin_deed(DolphinDeedNfcRead); - consumed = true; - } - } - return consumed; -} - -void nfc_scene_nfcv_key_input_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - byte_input_set_result_callback(nfc->byte_input, NULL, NULL, NULL, NULL, 0); - byte_input_set_header_text(nfc->byte_input, ""); -} diff --git a/applications/main/nfc/scenes/nfc_scene_nfcv_menu.c b/applications/main/nfc/scenes/nfc_scene_nfcv_menu.c deleted file mode 100644 index 60eb354e8..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfcv_menu.c +++ /dev/null @@ -1,68 +0,0 @@ -#include "../nfc_i.h" -#include - -enum SubmenuIndex { - SubmenuIndexSave, - SubmenuIndexEmulate, - SubmenuIndexInfo, -}; - -void nfc_scene_nfcv_menu_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_nfcv_menu_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - - submenu_add_item( - submenu, "Emulate", SubmenuIndexEmulate, nfc_scene_nfcv_menu_submenu_callback, nfc); - submenu_add_item(submenu, "Save", SubmenuIndexSave, nfc_scene_nfcv_menu_submenu_callback, nfc); - submenu_add_item(submenu, "Info", SubmenuIndexInfo, nfc_scene_nfcv_menu_submenu_callback, nfc); - - submenu_set_selected_item( - nfc->submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneNfcVMenu)); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_nfcv_menu_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexSave) { - nfc->dev->format = NfcDeviceSaveFormatNfcV; - // Clear device name - nfc_device_set_name(nfc->dev, ""); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); - consumed = true; - } else if(event.event == SubmenuIndexEmulate) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVEmulate); - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSetType)) { - dolphin_deed(DolphinDeedNfcAddEmulate); - } else { - dolphin_deed(DolphinDeedNfcEmulate); - } - consumed = true; - } else if(event.event == SubmenuIndexInfo) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcDataInfo); - consumed = true; - } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneNfcVMenu, event.event); - - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_previous_scene(nfc->scene_manager); - } - - return consumed; -} - -void nfc_scene_nfcv_menu_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_nfcv_read_success.c b/applications/main/nfc/scenes/nfc_scene_nfcv_read_success.c deleted file mode 100644 index 04e60611d..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfcv_read_success.c +++ /dev/null @@ -1,92 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_nfcv_read_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - furi_assert(context); - Nfc* nfc = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_nfcv_read_success_on_enter(void* context) { - Nfc* nfc = context; - NfcDeviceData* dev_data = &nfc->dev->dev_data; - FuriHalNfcDevData* nfc_data = &nfc->dev->dev_data.nfc_data; - // Setup view - Widget* widget = nfc->widget; - widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_scene_nfcv_read_success_widget_callback, nfc); - widget_add_button_element( - widget, GuiButtonTypeRight, "More", nfc_scene_nfcv_read_success_widget_callback, nfc); - - FuriString* temp_str = furi_string_alloc(); - - switch(dev_data->nfcv_data.sub_type) { - case NfcVTypePlain: - furi_string_cat_printf(temp_str, "\e#ISO15693\n"); - break; - case NfcVTypeSlix: - furi_string_cat_printf(temp_str, "\e#ISO15693 SLIX\n"); - break; - case NfcVTypeSlixS: - furi_string_cat_printf(temp_str, "\e#ISO15693 SLIX-S\n"); - break; - case NfcVTypeSlixL: - furi_string_cat_printf(temp_str, "\e#ISO15693 SLIX-L\n"); - break; - case NfcVTypeSlix2: - furi_string_cat_printf(temp_str, "\e#ISO15693 SLIX2\n"); - break; - default: - furi_string_cat_printf(temp_str, "\e#ISO15693 (unknown)\n"); - break; - } - furi_string_cat_printf(temp_str, "UID:\n"); - for(size_t i = 0; i < nfc_data->uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", nfc_data->uid[i]); - } - furi_string_cat_printf(temp_str, "\n"); - furi_string_cat_printf(temp_str, "(see More->Info for details)\n"); - - widget_add_text_scroll_element(widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); - furi_string_free(temp_str); - - notification_message_block(nfc->notifications, &sequence_set_green_255); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_nfcv_read_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneRetryConfirm); - consumed = true; - } else if(event.event == GuiButtonTypeRight) { - // Clear device name - nfc_device_set_name(nfc->dev, ""); - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVMenu); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneExitConfirm); - consumed = true; - } - - return consumed; -} - -void nfc_scene_nfcv_read_success_on_exit(void* context) { - Nfc* nfc = context; - - notification_message_block(nfc->notifications, &sequence_reset_green); - - // Clear view - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_nfcv_sniff.c b/applications/main/nfc/scenes/nfc_scene_nfcv_sniff.c deleted file mode 100644 index 2c0f17981..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfcv_sniff.c +++ /dev/null @@ -1,155 +0,0 @@ -#include "../nfc_i.h" - -#define NFC_SCENE_EMULATE_NFCV_LOG_SIZE_MAX (800) - -enum { - NfcSceneNfcVSniffStateWidget, - NfcSceneNfcVSniffStateTextBox, -}; - -bool nfc_scene_nfcv_sniff_worker_callback(NfcWorkerEvent event, void* context) { - UNUSED(event); - furi_assert(context); - Nfc* nfc = context; - - switch(event) { - case NfcWorkerEventNfcVCommandExecuted: - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventUpdateLog); - break; - case NfcWorkerEventNfcVContentChanged: - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventSaveShadow); - break; - default: - break; - } - return true; -} - -void nfc_scene_nfcv_sniff_widget_callback(GuiButtonType result, InputType type, void* context) { - furi_assert(context); - Nfc* nfc = context; - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_nfcv_sniff_textbox_callback(void* context) { - furi_assert(context); - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -static void nfc_scene_nfcv_sniff_widget_config(Nfc* nfc, bool data_received) { - Widget* widget = nfc->widget; - widget_reset(widget); - FuriString* info_str; - info_str = furi_string_alloc(); - - widget_add_icon_element(widget, 0, 3, &I_RFIDDolphinSend_97x61); - widget_add_string_element(widget, 89, 32, AlignCenter, AlignTop, FontPrimary, "Listen NfcV"); - furi_string_trim(info_str); - widget_add_text_box_element( - widget, 56, 43, 70, 21, AlignCenter, AlignTop, furi_string_get_cstr(info_str), true); - furi_string_free(info_str); - if(data_received) { - widget_add_button_element( - widget, GuiButtonTypeCenter, "Log", nfc_scene_nfcv_sniff_widget_callback, nfc); - } -} - -void nfc_scene_nfcv_sniff_on_enter(void* context) { - Nfc* nfc = context; - - // Setup Widget - nfc_scene_nfcv_sniff_widget_config(nfc, false); - // Setup TextBox - TextBox* text_box = nfc->text_box; - text_box_set_font(text_box, TextBoxFontHex); - text_box_set_focus(text_box, TextBoxFocusEnd); - text_box_set_text(text_box, ""); - furi_string_reset(nfc->text_box_store); - - // Set Widget state and view - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneNfcVSniff, NfcSceneNfcVSniffStateWidget); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - // Start worker - memset(&nfc->dev->dev_data.reader_data, 0, sizeof(NfcReaderRequestData)); - nfc_worker_start( - nfc->worker, - NfcWorkerStateNfcVSniff, - &nfc->dev->dev_data, - nfc_scene_nfcv_sniff_worker_callback, - nfc); - - nfc_blink_emulate_start(nfc); -} - -bool nfc_scene_nfcv_sniff_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - NfcVData* nfcv_data = &nfc->dev->dev_data.nfcv_data; - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneNfcVSniff); - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventUpdateLog) { - // Add data button to widget if data is received for the first time - if(strlen(nfcv_data->last_command) > 0) { - if(!furi_string_size(nfc->text_box_store)) { - nfc_scene_nfcv_sniff_widget_config(nfc, true); - } - /* use the last n bytes from the log so there's enough space for the new log entry */ - size_t maxSize = - NFC_SCENE_EMULATE_NFCV_LOG_SIZE_MAX - (strlen(nfcv_data->last_command) + 1); - if(furi_string_size(nfc->text_box_store) >= maxSize) { - furi_string_right(nfc->text_box_store, (strlen(nfcv_data->last_command) + 1)); - } - furi_string_cat_printf(nfc->text_box_store, "%s", nfcv_data->last_command); - furi_string_push_back(nfc->text_box_store, '\n'); - text_box_set_text(nfc->text_box, furi_string_get_cstr(nfc->text_box_store)); - - /* clear previously logged command */ - strcpy(nfcv_data->last_command, ""); - } - consumed = true; - } else if(event.event == NfcCustomEventSaveShadow) { - if(furi_string_size(nfc->dev->load_path)) { - nfc_device_save_shadow(nfc->dev, furi_string_get_cstr(nfc->dev->load_path)); - } - consumed = true; - } else if(event.event == GuiButtonTypeCenter && state == NfcSceneNfcVSniffStateWidget) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewTextBox); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneNfcVSniff, NfcSceneNfcVSniffStateTextBox); - consumed = true; - } else if(event.event == NfcCustomEventViewExit && state == NfcSceneNfcVSniffStateTextBox) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneNfcVSniff, NfcSceneNfcVSniffStateWidget); - consumed = true; - } - } else if(event.type == SceneManagerEventTypeBack) { - if(state == NfcSceneNfcVSniffStateTextBox) { - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneNfcVSniff, NfcSceneNfcVSniffStateWidget); - consumed = true; - } - } - - return consumed; -} - -void nfc_scene_nfcv_sniff_on_exit(void* context) { - Nfc* nfc = context; - - // Stop worker - nfc_worker_stop(nfc->worker); - - // Clear view - widget_reset(nfc->widget); - text_box_reset(nfc->text_box); - furi_string_reset(nfc->text_box_store); - - nfc_blink_stop(nfc); -} diff --git a/applications/main/nfc/scenes/nfc_scene_nfcv_unlock.c b/applications/main/nfc/scenes/nfc_scene_nfcv_unlock.c deleted file mode 100644 index 38d7ad563..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfcv_unlock.c +++ /dev/null @@ -1,154 +0,0 @@ -#include "../nfc_i.h" -#include - -typedef enum { - NfcSceneNfcVUnlockStateIdle, - NfcSceneNfcVUnlockStateDetecting, - NfcSceneNfcVUnlockStateUnlocked, - NfcSceneNfcVUnlockStateAlreadyUnlocked, - NfcSceneNfcVUnlockStateNotSupportedCard, -} NfcSceneNfcVUnlockState; - -static bool nfc_scene_nfcv_unlock_worker_callback(NfcWorkerEvent event, void* context) { - Nfc* nfc = context; - NfcVSlixData* data = &nfc->dev->dev_data.nfcv_data.sub_data.slix; - - if(event == NfcWorkerEventNfcVPassKey) { - memcpy(data->key_privacy, nfc->byte_input_store, 4); - } else { - view_dispatcher_send_custom_event(nfc->view_dispatcher, event); - } - return true; -} - -void nfc_scene_nfcv_unlock_popup_callback(void* context) { - Nfc* nfc = context; - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); -} - -void nfc_scene_nfcv_unlock_set_state(Nfc* nfc, NfcSceneNfcVUnlockState state) { - FuriHalNfcDevData* nfc_data = &(nfc->dev->dev_data.nfc_data); - NfcVData* nfcv_data = &(nfc->dev->dev_data.nfcv_data); - - uint32_t curr_state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneNfcVUnlock); - if(curr_state != state) { - Popup* popup = nfc->popup; - if(state == NfcSceneNfcVUnlockStateDetecting) { - popup_reset(popup); - popup_set_text( - popup, "Put figurine on\nFlipper's back", 97, 24, AlignCenter, AlignTop); - popup_set_icon(popup, 0, 8, &I_NFC_manual_60x50); - } else if(state == NfcSceneNfcVUnlockStateUnlocked) { - popup_reset(popup); - - if(nfc_worker_get_state(nfc->worker) == NfcWorkerStateNfcVUnlockAndSave) { - snprintf( - nfc->dev->dev_name, - sizeof(nfc->dev->dev_name), - "SLIX_%02X%02X%02X%02X%02X%02X%02X%02X", - nfc_data->uid[0], - nfc_data->uid[1], - nfc_data->uid[2], - nfc_data->uid[3], - nfc_data->uid[4], - nfc_data->uid[5], - nfc_data->uid[6], - nfc_data->uid[7]); - - nfc->dev->format = NfcDeviceSaveFormatNfcV; - - if(nfc_save_file(nfc)) { - popup_set_header(popup, "Successfully\nsaved", 94, 3, AlignCenter, AlignTop); - } else { - popup_set_header( - popup, "Unlocked but\nsave failed!", 94, 3, AlignCenter, AlignTop); - } - } else { - popup_set_header(popup, "Successfully\nunlocked", 94, 3, AlignCenter, AlignTop); - } - - notification_message(nfc->notifications, &sequence_single_vibro); - //notification_message(nfc->notifications, &sequence_success); - - popup_set_icon(popup, 0, 6, &I_RFIDDolphinSuccess_108x57); - popup_set_context(popup, nfc); - popup_set_callback(popup, nfc_scene_nfcv_unlock_popup_callback); - popup_set_timeout(popup, 1500); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - dolphin_deed(DolphinDeedNfcReadSuccess); - - } else if(state == NfcSceneNfcVUnlockStateAlreadyUnlocked) { - popup_reset(popup); - - popup_set_header(popup, "Already\nUnlocked!", 94, 3, AlignCenter, AlignTop); - popup_set_icon(popup, 0, 6, &I_RFIDDolphinSuccess_108x57); - popup_set_context(popup, nfc); - popup_set_callback(popup, nfc_scene_nfcv_unlock_popup_callback); - popup_set_timeout(popup, 1500); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - } else if(state == NfcSceneNfcVUnlockStateNotSupportedCard) { - popup_reset(popup); - popup_set_header(popup, "Wrong Type Of Card!", 64, 3, AlignCenter, AlignTop); - popup_set_text(popup, nfcv_data->error, 4, 22, AlignLeft, AlignTop); - popup_set_icon(popup, 73, 20, &I_DolphinCommon_56x48); - } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneNfcVUnlock, state); - } -} - -void nfc_scene_nfcv_unlock_on_enter(void* context) { - Nfc* nfc = context; - - nfc_device_clear(nfc->dev); - // Setup view - nfc_scene_nfcv_unlock_set_state(nfc, NfcSceneNfcVUnlockStateDetecting); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - - // Start worker - nfc_worker_start( - nfc->worker, - NfcWorkerStateNfcVUnlockAndSave, - &nfc->dev->dev_data, - nfc_scene_nfcv_unlock_worker_callback, - nfc); - - nfc_blink_read_start(nfc); -} - -bool nfc_scene_nfcv_unlock_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcWorkerEventCardDetected) { - nfc_scene_nfcv_unlock_set_state(nfc, NfcSceneNfcVUnlockStateUnlocked); - consumed = true; - } else if(event.event == NfcWorkerEventAborted) { - nfc_scene_nfcv_unlock_set_state(nfc, NfcSceneNfcVUnlockStateAlreadyUnlocked); - consumed = true; - } else if(event.event == NfcWorkerEventNoCardDetected) { - nfc_scene_nfcv_unlock_set_state(nfc, NfcSceneNfcVUnlockStateDetecting); - consumed = true; - } else if(event.event == NfcWorkerEventWrongCardDetected) { - nfc_scene_nfcv_unlock_set_state(nfc, NfcSceneNfcVUnlockStateNotSupportedCard); - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneNfcVUnlockMenu); - } - return consumed; -} - -void nfc_scene_nfcv_unlock_on_exit(void* context) { - Nfc* nfc = context; - - // Stop worker - nfc_worker_stop(nfc->worker); - // Clear view - popup_reset(nfc->popup); - nfc_blink_stop(nfc); - scene_manager_set_scene_state( - nfc->scene_manager, NfcSceneNfcVUnlock, NfcSceneNfcVUnlockStateIdle); -} diff --git a/applications/main/nfc/scenes/nfc_scene_nfcv_unlock_menu.c b/applications/main/nfc/scenes/nfc_scene_nfcv_unlock_menu.c deleted file mode 100644 index 2f7367256..000000000 --- a/applications/main/nfc/scenes/nfc_scene_nfcv_unlock_menu.c +++ /dev/null @@ -1,60 +0,0 @@ -#include "../nfc_i.h" -#include - -enum SubmenuIndex { - SubmenuIndexNfcVUnlockMenuManual, - SubmenuIndexNfcVUnlockMenuTonieBox, -}; - -void nfc_scene_nfcv_unlock_menu_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_nfcv_unlock_menu_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneNfcVUnlockMenu); - submenu_add_item( - submenu, - "Enter PWD Manually", - SubmenuIndexNfcVUnlockMenuManual, - nfc_scene_nfcv_unlock_menu_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Auth As TonieBox", - SubmenuIndexNfcVUnlockMenuTonieBox, - nfc_scene_nfcv_unlock_menu_submenu_callback, - nfc); - submenu_set_selected_item(submenu, state); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_nfcv_unlock_menu_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexNfcVUnlockMenuManual) { - nfc->dev->dev_data.nfcv_data.auth_method = NfcVAuthMethodManual; - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVKeyInput); - consumed = true; - } else if(event.event == SubmenuIndexNfcVUnlockMenuTonieBox) { - nfc->dev->dev_data.nfcv_data.auth_method = NfcVAuthMethodTonieBox; - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVUnlock); - dolphin_deed(DolphinDeedNfcRead); - consumed = true; - } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneNfcVUnlockMenu, event.event); - } - return consumed; -} - -void nfc_scene_nfcv_unlock_menu_on_exit(void* context) { - Nfc* nfc = context; - - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_read.c b/applications/main/nfc/scenes/nfc_scene_read.c index f254e08f8..e9603afd1 100644 --- a/applications/main/nfc/scenes/nfc_scene_read.c +++ b/applications/main/nfc/scenes/nfc_scene_read.c @@ -1,128 +1,13 @@ -#include "../nfc_i.h" -#include - -typedef enum { - NfcSceneReadStateIdle, - NfcSceneReadStateDetecting, - NfcSceneReadStateReading, -} NfcSceneReadState; - -bool nfc_scene_read_worker_callback(NfcWorkerEvent event, void* context) { - Nfc* nfc = context; - bool consumed = false; - if(event == NfcWorkerEventReadMfClassicLoadKeyCache) { - consumed = nfc_device_load_key_cache(nfc->dev); - } else { - view_dispatcher_send_custom_event(nfc->view_dispatcher, event); - consumed = true; - } - return consumed; -} - -void nfc_scene_read_set_state(Nfc* nfc, NfcSceneReadState state) { - uint32_t curr_state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneRead); - if(curr_state != state) { - if(state == NfcSceneReadStateDetecting) { - popup_reset(nfc->popup); - popup_set_text( - nfc->popup, "Apply card to\nFlipper's back", 97, 24, AlignCenter, AlignTop); - popup_set_icon(nfc->popup, 0, 8, &I_NFC_manual_60x50); - } else if(state == NfcSceneReadStateReading) { - popup_reset(nfc->popup); - popup_set_header( - nfc->popup, "Reading card\nDon't move...", 85, 24, AlignCenter, AlignTop); - popup_set_icon(nfc->popup, 12, 23, &A_Loading_24); - } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneRead, state); - } -} +#include "../helpers/protocol_support/nfc_protocol_support.h" void nfc_scene_read_on_enter(void* context) { - Nfc* nfc = context; - - nfc_device_clear(nfc->dev); - // Setup view - nfc_scene_read_set_state(nfc, NfcSceneReadStateDetecting); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - // Start worker - nfc_worker_start( - nfc->worker, NfcWorkerStateRead, &nfc->dev->dev_data, nfc_scene_read_worker_callback, nfc); - - nfc_blink_read_start(nfc); + nfc_protocol_support_on_enter(NfcProtocolSupportSceneRead, context); } bool nfc_scene_read_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if((event.event == NfcWorkerEventReadUidNfcB) || - (event.event == NfcWorkerEventReadUidNfcF) || - (event.event == NfcWorkerEventReadUidNfcV)) { - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneReadCardSuccess); - dolphin_deed(DolphinDeedNfcReadSuccess); - consumed = true; - } else if(event.event == NfcWorkerEventReadUidNfcA) { - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcaReadSuccess); - dolphin_deed(DolphinDeedNfcReadSuccess); - consumed = true; - } else if(event.event == NfcWorkerEventReadNfcV) { - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVReadSuccess); - dolphin_deed(DolphinDeedNfcReadSuccess); - consumed = true; - } else if(event.event == NfcWorkerEventReadMfUltralight) { - notification_message(nfc->notifications, &sequence_success); - // Set unlock password input to 0xFFFFFFFF only on fresh read - memset(nfc->byte_input_store, 0xFF, sizeof(nfc->byte_input_store)); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightReadSuccess); - dolphin_deed(DolphinDeedNfcReadSuccess); - consumed = true; - } else if(event.event == NfcWorkerEventReadMfClassicDone) { - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicReadSuccess); - dolphin_deed(DolphinDeedNfcReadSuccess); - consumed = true; - } else if(event.event == NfcWorkerEventReadMfDesfire) { - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfDesfireReadSuccess); - dolphin_deed(DolphinDeedNfcReadSuccess); - consumed = true; - } else if(event.event == NfcWorkerEventReadBankCard) { - notification_message(nfc->notifications, &sequence_success); - scene_manager_next_scene(nfc->scene_manager, NfcSceneEmvReadSuccess); - dolphin_deed(DolphinDeedNfcReadSuccess); - consumed = true; - } else if(event.event == NfcWorkerEventReadMfClassicDictAttackRequired) { - if(mf_classic_dict_check_presence(MfClassicDictTypeSystem)) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicDictAttack); - } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDictNotFound); - } - consumed = true; - } else if(event.event == NfcWorkerEventCardDetected) { - nfc_scene_read_set_state(nfc, NfcSceneReadStateReading); - nfc_blink_detect_start(nfc); - consumed = true; - } else if(event.event == NfcWorkerEventNoCardDetected) { - nfc_scene_read_set_state(nfc, NfcSceneReadStateDetecting); - nfc_blink_read_start(nfc); - consumed = true; - } - } - return consumed; + return nfc_protocol_support_on_event(NfcProtocolSupportSceneRead, context, event); } void nfc_scene_read_on_exit(void* context) { - Nfc* nfc = context; - - // Stop worker - nfc_worker_stop(nfc->worker); - // Clear view - popup_reset(nfc->popup); - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneRead, NfcSceneReadStateIdle); - - nfc_blink_stop(nfc); + nfc_protocol_support_on_exit(NfcProtocolSupportSceneRead, context); } diff --git a/applications/main/nfc/scenes/nfc_scene_read_card_success.c b/applications/main/nfc/scenes/nfc_scene_read_card_success.c deleted file mode 100644 index ee80ee768..000000000 --- a/applications/main/nfc/scenes/nfc_scene_read_card_success.c +++ /dev/null @@ -1,61 +0,0 @@ -#include "../nfc_i.h" - -void nfc_scene_read_card_success_widget_callback( - GuiButtonType result, - InputType type, - void* context) { - furi_assert(context); - Nfc* nfc = context; - - if(type == InputTypeShort) { - view_dispatcher_send_custom_event(nfc->view_dispatcher, result); - } -} - -void nfc_scene_read_card_success_on_enter(void* context) { - Nfc* nfc = context; - - FuriString* temp_str; - temp_str = furi_string_alloc(); - - // Setup view - FuriHalNfcDevData* data = &nfc->dev->dev_data.nfc_data; - Widget* widget = nfc->widget; - furi_string_set(temp_str, nfc_get_dev_type(data->type)); - widget_add_string_element( - widget, 64, 12, AlignCenter, AlignBottom, FontPrimary, furi_string_get_cstr(temp_str)); - furi_string_set(temp_str, "UID:"); - for(uint8_t i = 0; i < data->uid_len; i++) { - furi_string_cat_printf(temp_str, " %02X", data->uid[i]); - } - widget_add_string_element( - widget, 64, 32, AlignCenter, AlignCenter, FontSecondary, furi_string_get_cstr(temp_str)); - widget_add_button_element( - widget, GuiButtonTypeLeft, "Retry", nfc_scene_read_card_success_widget_callback, nfc); - - furi_string_free(temp_str); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewWidget); -} - -bool nfc_scene_read_card_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == GuiButtonTypeLeft) { - consumed = scene_manager_previous_scene(nfc->scene_manager); - } - } else if(event.type == SceneManagerEventTypeBack) { - consumed = - scene_manager_search_and_switch_to_previous_scene(nfc->scene_manager, NfcSceneStart); - } - return consumed; -} - -void nfc_scene_read_card_success_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - widget_reset(nfc->widget); -} diff --git a/applications/main/nfc/scenes/nfc_scene_read_card_type.c b/applications/main/nfc/scenes/nfc_scene_read_card_type.c deleted file mode 100644 index 94262aa1e..000000000 --- a/applications/main/nfc/scenes/nfc_scene_read_card_type.c +++ /dev/null @@ -1,97 +0,0 @@ -#include "../nfc_i.h" -#include "nfc_worker_i.h" - -enum SubmenuIndex { - SubmenuIndexReadMifareClassic, - SubmenuIndexReadMifareDesfire, - SubmenuIndexReadMfUltralight, - SubmenuIndexReadEMV, - SubmenuIndexReadNFCA, -}; - -void nfc_scene_read_card_type_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_read_card_type_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - - submenu_add_item( - submenu, - "Read Mifare Classic", - SubmenuIndexReadMifareClassic, - nfc_scene_read_card_type_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Read Mifare DESFire", - SubmenuIndexReadMifareDesfire, - nfc_scene_read_card_type_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Read NTAG/Ultralight", - SubmenuIndexReadMfUltralight, - nfc_scene_read_card_type_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Read EMV card", - SubmenuIndexReadEMV, - nfc_scene_read_card_type_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Read NFC-A data", - SubmenuIndexReadNFCA, - nfc_scene_read_card_type_submenu_callback, - nfc); - uint32_t state = scene_manager_get_scene_state(nfc->scene_manager, NfcSceneReadCardType); - submenu_set_selected_item(submenu, state); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_read_card_type_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexReadMifareClassic) { - nfc->dev->dev_data.read_mode = NfcReadModeMfClassic; - scene_manager_next_scene(nfc->scene_manager, NfcSceneRead); - consumed = true; - } - if(event.event == SubmenuIndexReadMifareDesfire) { - nfc->dev->dev_data.read_mode = NfcReadModeMfDesfire; - scene_manager_next_scene(nfc->scene_manager, NfcSceneRead); - consumed = true; - } - if(event.event == SubmenuIndexReadMfUltralight) { - nfc->dev->dev_data.read_mode = NfcReadModeMfUltralight; - scene_manager_next_scene(nfc->scene_manager, NfcSceneRead); - consumed = true; - } - if(event.event == SubmenuIndexReadEMV) { - nfc->dev->dev_data.read_mode = NfcReadModeEMV; - scene_manager_next_scene(nfc->scene_manager, NfcSceneRead); - consumed = true; - } - if(event.event == SubmenuIndexReadNFCA) { - nfc->dev->dev_data.read_mode = NfcReadModeNFCA; - scene_manager_next_scene(nfc->scene_manager, NfcSceneRead); - consumed = true; - } - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneReadCardType, event.event); - } - return consumed; -} - -void nfc_scene_read_card_type_on_exit(void* context) { - Nfc* nfc = context; - - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_read_menu.c b/applications/main/nfc/scenes/nfc_scene_read_menu.c new file mode 100644 index 000000000..cba07a485 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_read_menu.c @@ -0,0 +1,13 @@ +#include "../helpers/protocol_support/nfc_protocol_support.h" + +void nfc_scene_read_menu_on_enter(void* context) { + nfc_protocol_support_on_enter(NfcProtocolSupportSceneReadMenu, context); +} + +bool nfc_scene_read_menu_on_event(void* context, SceneManagerEvent event) { + return nfc_protocol_support_on_event(NfcProtocolSupportSceneReadMenu, context, event); +} + +void nfc_scene_read_menu_on_exit(void* context) { + nfc_protocol_support_on_exit(NfcProtocolSupportSceneReadMenu, context); +} diff --git a/applications/main/nfc/scenes/nfc_scene_read_success.c b/applications/main/nfc/scenes/nfc_scene_read_success.c new file mode 100644 index 000000000..5ceada48b --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_read_success.c @@ -0,0 +1,13 @@ +#include "../helpers/protocol_support/nfc_protocol_support.h" + +void nfc_scene_read_success_on_enter(void* context) { + nfc_protocol_support_on_enter(NfcProtocolSupportSceneReadSuccess, context); +} + +bool nfc_scene_read_success_on_event(void* context, SceneManagerEvent event) { + return nfc_protocol_support_on_event(NfcProtocolSupportSceneReadSuccess, context, event); +} + +void nfc_scene_read_success_on_exit(void* context) { + nfc_protocol_support_on_exit(NfcProtocolSupportSceneReadSuccess, context); +} diff --git a/applications/main/nfc/scenes/nfc_scene_restore_original.c b/applications/main/nfc/scenes/nfc_scene_restore_original.c index 3ecf5c048..612e6041e 100644 --- a/applications/main/nfc/scenes/nfc_scene_restore_original.c +++ b/applications/main/nfc/scenes/nfc_scene_restore_original.c @@ -1,12 +1,12 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_restore_original_popup_callback(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); } void nfc_scene_restore_original_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Setup view Popup* popup = nfc->popup; @@ -20,17 +20,17 @@ void nfc_scene_restore_original_on_enter(void* context) { } bool nfc_scene_restore_original_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == NfcCustomEventViewExit) { - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSavedMenu)) { + if(nfc_load_file(nfc, nfc->file_path, false)) { consumed = scene_manager_search_and_switch_to_previous_scene( nfc->scene_manager, NfcSceneSavedMenu); } else { consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneStart); + nfc->scene_manager, NfcSceneFileSelect); } } } @@ -38,7 +38,7 @@ bool nfc_scene_restore_original_on_event(void* context, SceneManagerEvent event) } void nfc_scene_restore_original_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Clear view popup_reset(nfc->popup); diff --git a/applications/main/nfc/scenes/nfc_scene_restore_original_confirm.c b/applications/main/nfc/scenes/nfc_scene_restore_original_confirm.c index 16b0953f8..6e260da2a 100644 --- a/applications/main/nfc/scenes/nfc_scene_restore_original_confirm.c +++ b/applications/main/nfc/scenes/nfc_scene_restore_original_confirm.c @@ -1,13 +1,13 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_restore_original_confirm_dialog_callback(DialogExResult result, void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, result); } void nfc_scene_restore_original_confirm_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; DialogEx* dialog_ex = nfc->dialog_ex; dialog_ex_set_header(dialog_ex, "Restore Card Data?", 64, 0, AlignCenter, AlignTop); @@ -23,16 +23,16 @@ void nfc_scene_restore_original_confirm_on_enter(void* context) { } bool nfc_scene_restore_original_confirm_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == DialogExResultRight) { - if(!nfc_device_restore(nfc->dev, true)) { + if(nfc_delete_shadow_file(nfc)) { + scene_manager_next_scene(nfc->scene_manager, NfcSceneRestoreOriginal); + } else { scene_manager_search_and_switch_to_previous_scene( nfc->scene_manager, NfcSceneStart); - } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneRestoreOriginal); } consumed = true; } else if(event.event == DialogExResultLeft) { @@ -46,7 +46,7 @@ bool nfc_scene_restore_original_confirm_on_event(void* context, SceneManagerEven } void nfc_scene_restore_original_confirm_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Clean view dialog_ex_reset(nfc->dialog_ex); diff --git a/applications/main/nfc/scenes/nfc_scene_retry_confirm.c b/applications/main/nfc/scenes/nfc_scene_retry_confirm.c index 5f4f7985e..b80f1bdcc 100644 --- a/applications/main/nfc/scenes/nfc_scene_retry_confirm.c +++ b/applications/main/nfc/scenes/nfc_scene_retry_confirm.c @@ -1,13 +1,13 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_retry_confirm_dialog_callback(DialogExResult result, void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, result); } void nfc_scene_retry_confirm_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; DialogEx* dialog_ex = nfc->dialog_ex; dialog_ex_set_left_button_text(dialog_ex, "Retry"); @@ -22,15 +22,20 @@ void nfc_scene_retry_confirm_on_enter(void* context) { } bool nfc_scene_retry_confirm_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == DialogExResultRight) { consumed = scene_manager_previous_scene(nfc->scene_manager); } else if(event.event == DialogExResultLeft) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneRead); + if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneDetect)) { + consumed = scene_manager_search_and_switch_to_previous_scene( + nfc->scene_manager, NfcSceneDetect); + } else if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneRead)) { + consumed = scene_manager_search_and_switch_to_previous_scene( + nfc->scene_manager, NfcSceneRead); + } } } else if(event.type == SceneManagerEventTypeBack) { consumed = true; @@ -40,7 +45,7 @@ bool nfc_scene_retry_confirm_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_retry_confirm_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Clean view dialog_ex_reset(nfc->dialog_ex); diff --git a/applications/main/nfc/scenes/nfc_scene_rpc.c b/applications/main/nfc/scenes/nfc_scene_rpc.c index d06ee7564..e12e84605 100644 --- a/applications/main/nfc/scenes/nfc_scene_rpc.c +++ b/applications/main/nfc/scenes/nfc_scene_rpc.c @@ -1,93 +1,13 @@ -#include "../nfc_i.h" +#include "../helpers/protocol_support/nfc_protocol_support.h" void nfc_scene_rpc_on_enter(void* context) { - Nfc* nfc = context; - Popup* popup = nfc->popup; - - popup_set_header(popup, "NFC", 89, 42, AlignCenter, AlignBottom); - popup_set_text(popup, "RPC mode", 89, 44, AlignCenter, AlignTop); - - popup_set_icon(popup, 0, 12, &I_NFC_dolphin_emulation_47x61); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewPopup); - - notification_message(nfc->notifications, &sequence_display_backlight_on); -} - -static bool nfc_scene_rpc_emulate_callback(NfcWorkerEvent event, void* context) { - UNUSED(event); - Nfc* nfc = context; - - nfc->rpc_state = NfcRpcStateEmulated; - return true; + nfc_protocol_support_on_enter(NfcProtocolSupportSceneRpc, context); } bool nfc_scene_rpc_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - Popup* popup = nfc->popup; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - consumed = true; - if(event.event == NfcCustomEventViewExit) { - rpc_system_app_confirm(nfc->rpc_ctx, RpcAppEventAppExit, true); - scene_manager_stop(nfc->scene_manager); - view_dispatcher_stop(nfc->view_dispatcher); - } else if(event.event == NfcCustomEventRpcSessionClose) { - scene_manager_stop(nfc->scene_manager); - view_dispatcher_stop(nfc->view_dispatcher); - } else if(event.event == NfcCustomEventRpcLoad) { - bool result = false; - const char* arg = rpc_system_app_get_data(nfc->rpc_ctx); - if((arg) && (nfc->rpc_state == NfcRpcStateIdle)) { - if(nfc_device_load(nfc->dev, arg, false)) { - if(nfc->dev->format == NfcDeviceSaveFormatMifareUl) { - nfc_worker_start( - nfc->worker, - NfcWorkerStateMfUltralightEmulate, - &nfc->dev->dev_data, - nfc_scene_rpc_emulate_callback, - nfc); - } else if(nfc->dev->format == NfcDeviceSaveFormatMifareClassic) { - nfc_worker_start( - nfc->worker, - NfcWorkerStateMfClassicEmulate, - &nfc->dev->dev_data, - nfc_scene_rpc_emulate_callback, - nfc); - } else if(nfc->dev->format == NfcDeviceSaveFormatNfcV) { - nfc_worker_start( - nfc->worker, - NfcWorkerStateNfcVEmulate, - &nfc->dev->dev_data, - nfc_scene_rpc_emulate_callback, - nfc); - } else { - nfc_worker_start( - nfc->worker, NfcWorkerStateUidEmulate, &nfc->dev->dev_data, NULL, nfc); - } - nfc->rpc_state = NfcRpcStateEmulating; - result = true; - - nfc_blink_emulate_start(nfc); - nfc_text_store_set(nfc, "emulating\n%s", nfc->dev->dev_name); - popup_set_text(popup, nfc->text_store, 89, 44, AlignCenter, AlignTop); - } - } - - rpc_system_app_confirm(nfc->rpc_ctx, RpcAppEventLoadFile, result); - } - } - return consumed; + return nfc_protocol_support_on_event(NfcProtocolSupportSceneRpc, context, event); } void nfc_scene_rpc_on_exit(void* context) { - Nfc* nfc = context; - Popup* popup = nfc->popup; - - nfc_blink_stop(nfc); - - popup_set_header(popup, NULL, 0, 0, AlignCenter, AlignBottom); - popup_set_text(popup, NULL, 0, 0, AlignCenter, AlignTop); - popup_set_icon(popup, 0, 0, NULL); + nfc_protocol_support_on_exit(NfcProtocolSupportSceneRpc, context); } diff --git a/applications/main/nfc/scenes/nfc_scene_save_name.c b/applications/main/nfc/scenes/nfc_scene_save_name.c index eed0a58dc..c23f097e1 100644 --- a/applications/main/nfc/scenes/nfc_scene_save_name.c +++ b/applications/main/nfc/scenes/nfc_scene_save_name.c @@ -1,94 +1,13 @@ -#include "../nfc_i.h" -#include -#include -#include -#include - -void nfc_scene_save_name_text_input_callback(void* context) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventTextInputDone); -} +#include "../helpers/protocol_support/nfc_protocol_support.h" void nfc_scene_save_name_on_enter(void* context) { - Nfc* nfc = context; - - // Setup view - TextInput* text_input = nfc->text_input; - bool dev_name_empty = false; - if(!strcmp(nfc->dev->dev_name, "")) { - name_generator_make_auto(nfc->text_store, NFC_DEV_NAME_MAX_LEN, NFC_APP_FILENAME_PREFIX); - dev_name_empty = true; - } else { - nfc_text_store_set(nfc, nfc->dev->dev_name); - } - text_input_set_header_text(text_input, "Name the card"); - text_input_set_result_callback( - text_input, - nfc_scene_save_name_text_input_callback, - nfc, - nfc->text_store, - NFC_DEV_NAME_MAX_LEN, - dev_name_empty); - - FuriString* folder_path; - folder_path = furi_string_alloc(); - - if(furi_string_end_with(nfc->dev->load_path, NFC_APP_FILENAME_EXTENSION)) { - path_extract_dirname(furi_string_get_cstr(nfc->dev->load_path), folder_path); - } else { - furi_string_set(folder_path, NFC_APP_FOLDER); - } - - ValidatorIsFile* validator_is_file = validator_is_file_alloc_init( - furi_string_get_cstr(folder_path), NFC_APP_FILENAME_EXTENSION, nfc->dev->dev_name); - text_input_set_validator(text_input, validator_is_file_callback, validator_is_file); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewTextInput); - - furi_string_free(folder_path); + nfc_protocol_support_on_enter(NfcProtocolSupportSceneSaveName, context); } bool nfc_scene_save_name_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == NfcCustomEventTextInputDone) { - if(strcmp(nfc->dev->dev_name, "") != 0) { - nfc_device_delete(nfc->dev, true); - } - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSetUid) && - (!scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSetTypeMfUid))) { - nfc->dev->dev_data.nfc_data = nfc->dev_edit_data; - } - strlcpy(nfc->dev->dev_name, nfc->text_store, strlen(nfc->text_store) + 1); - if(nfc_save_file(nfc)) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveSuccess); - if(!scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSavedMenu)) { - // Nothing, do not count editing as saving - } else if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSetType)) { - dolphin_deed(DolphinDeedNfcAddSave); - } else { - dolphin_deed(DolphinDeedNfcSave); - } - consumed = true; - } else { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneStart); - } - } - } - return consumed; + return nfc_protocol_support_on_event(NfcProtocolSupportSceneSaveName, context, event); } void nfc_scene_save_name_on_exit(void* context) { - Nfc* nfc = context; - - // Clear view - void* validator_context = text_input_get_validator_callback_context(nfc->text_input); - text_input_set_validator(nfc->text_input, NULL, NULL); - validator_is_file_free(validator_context); - - text_input_reset(nfc->text_input); + nfc_protocol_support_on_exit(NfcProtocolSupportSceneSaveName, context); } diff --git a/applications/main/nfc/scenes/nfc_scene_save_success.c b/applications/main/nfc/scenes/nfc_scene_save_success.c index 34919cbd8..0cb26c0d4 100644 --- a/applications/main/nfc/scenes/nfc_scene_save_success.c +++ b/applications/main/nfc/scenes/nfc_scene_save_success.c @@ -1,12 +1,12 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" void nfc_scene_save_success_popup_callback(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventViewExit); } void nfc_scene_save_success_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Setup view Popup* popup = nfc->popup; @@ -20,7 +20,7 @@ void nfc_scene_save_success_on_enter(void* context) { } bool nfc_scene_save_success_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { @@ -28,9 +28,6 @@ bool nfc_scene_save_success_on_event(void* context, SceneManagerEvent event) { if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneMfClassicKeys)) { consumed = scene_manager_search_and_switch_to_previous_scene( nfc->scene_manager, NfcSceneMfClassicKeys); - } else if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSavedMenu)) { - consumed = scene_manager_search_and_switch_to_previous_scene( - nfc->scene_manager, NfcSceneSavedMenu); } else { consumed = scene_manager_search_and_switch_to_another_scene( nfc->scene_manager, NfcSceneFileSelect); @@ -41,7 +38,7 @@ bool nfc_scene_save_success_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_save_success_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; // Clear view popup_reset(nfc->popup); diff --git a/applications/main/nfc/scenes/nfc_scene_saved_menu.c b/applications/main/nfc/scenes/nfc_scene_saved_menu.c index 9b0c633d3..d367e8ab8 100644 --- a/applications/main/nfc/scenes/nfc_scene_saved_menu.c +++ b/applications/main/nfc/scenes/nfc_scene_saved_menu.c @@ -1,187 +1,13 @@ -#include "../nfc_i.h" -#include - -enum SubmenuIndex { - SubmenuIndexEmulate, - SubmenuIndexEditUid, - SubmenuIndexDetectReader, - SubmenuIndexWrite, - SubmenuIndexUpdate, - SubmenuIndexRename, - SubmenuIndexDelete, - SubmenuIndexInfo, - SubmenuIndexRestoreOriginal, - SubmenuIndexMfUlUnlockByReader, - SubmenuIndexMfUlUnlockByPassword, -}; - -void nfc_scene_saved_menu_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} +#include "../helpers/protocol_support/nfc_protocol_support.h" void nfc_scene_saved_menu_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - - if(nfc->dev->format == NfcDeviceSaveFormatUid || - nfc->dev->format == NfcDeviceSaveFormatMifareDesfire || - nfc->dev->format == NfcDeviceSaveFormatBankCard) { - submenu_add_item( - submenu, - "Emulate UID", - SubmenuIndexEmulate, - nfc_scene_saved_menu_submenu_callback, - nfc); - if(nfc->dev->dev_data.protocol == NfcDeviceProtocolUnknown) { - submenu_add_item( - submenu, - "Edit UID", - SubmenuIndexEditUid, - nfc_scene_saved_menu_submenu_callback, - nfc); - } - } else if( - (nfc->dev->format == NfcDeviceSaveFormatMifareUl && - mf_ul_emulation_supported(&nfc->dev->dev_data.mf_ul_data)) || - nfc->dev->format == NfcDeviceSaveFormatNfcV || - nfc->dev->format == NfcDeviceSaveFormatMifareClassic) { - submenu_add_item( - submenu, "Emulate", SubmenuIndexEmulate, nfc_scene_saved_menu_submenu_callback, nfc); - } - if(nfc->dev->format == NfcDeviceSaveFormatMifareClassic) { - if(!mf_classic_is_card_read(&nfc->dev->dev_data.mf_classic_data)) { - submenu_add_item( - submenu, - "Detect Reader", - SubmenuIndexDetectReader, - nfc_scene_saved_menu_submenu_callback, - nfc); - } - submenu_add_item( - submenu, - "Write to Initial Card", - SubmenuIndexWrite, - nfc_scene_saved_menu_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Update from Initial Card", - SubmenuIndexUpdate, - nfc_scene_saved_menu_submenu_callback, - nfc); - } - submenu_add_item( - submenu, "Info", SubmenuIndexInfo, nfc_scene_saved_menu_submenu_callback, nfc); - if(nfc->dev->format == NfcDeviceSaveFormatMifareUl && - nfc->dev->dev_data.mf_ul_data.type != MfUltralightTypeULC && - !mf_ul_is_full_capture(&nfc->dev->dev_data.mf_ul_data)) { - submenu_add_item( - submenu, - "Unlock with Reader", - SubmenuIndexMfUlUnlockByReader, - nfc_scene_saved_menu_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Unlock with Password", - SubmenuIndexMfUlUnlockByPassword, - nfc_scene_saved_menu_submenu_callback, - nfc); - } - if(nfc->dev->shadow_file_exist) { - submenu_add_item( - submenu, - "Restore to original", - SubmenuIndexRestoreOriginal, - nfc_scene_saved_menu_submenu_callback, - nfc); - } - submenu_add_item( - submenu, "Rename", SubmenuIndexRename, nfc_scene_saved_menu_submenu_callback, nfc); - submenu_add_item( - submenu, "Delete", SubmenuIndexDelete, nfc_scene_saved_menu_submenu_callback, nfc); - submenu_set_selected_item( - nfc->submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneSavedMenu)); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); + nfc_protocol_support_on_enter(NfcProtocolSupportSceneSavedMenu, context); } bool nfc_scene_saved_menu_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - NfcDeviceData* dev_data = &nfc->dev->dev_data; - bool consumed = false; - - if(event.type == SceneManagerEventTypeCustom) { - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneSavedMenu, event.event); - if(event.event == SubmenuIndexEmulate) { - if(nfc->dev->format == NfcDeviceSaveFormatMifareUl) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightEmulate); - } else if(nfc->dev->format == NfcDeviceSaveFormatMifareClassic) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicEmulate); - } else if(nfc->dev->format == NfcDeviceSaveFormatNfcV) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcVEmulate); - } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneEmulateUid); - } - dolphin_deed(DolphinDeedNfcEmulate); - consumed = true; - } else if(event.event == SubmenuIndexDetectReader) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDetectReader); - dolphin_deed(DolphinDeedNfcDetectReader); - consumed = true; - } else if(event.event == SubmenuIndexWrite) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicWrite); - consumed = true; - } else if(event.event == SubmenuIndexUpdate) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicUpdate); - consumed = true; - } else if(event.event == SubmenuIndexRename) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); - consumed = true; - } else if(event.event == SubmenuIndexEditUid) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneSetUid); - consumed = true; - } else if(event.event == SubmenuIndexDelete) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDelete); - consumed = true; - } else if(event.event == SubmenuIndexInfo) { - bool application_info_present = false; - if(dev_data->protocol == NfcDeviceProtocolEMV) { - application_info_present = true; - } else if( - dev_data->protocol == NfcDeviceProtocolMifareClassic || - dev_data->protocol == NfcDeviceProtocolMifareDesfire || - dev_data->protocol == NfcDeviceProtocolMifareUl) { - application_info_present = nfc_supported_card_verify_and_parse(dev_data); - } - - FURI_LOG_I("nfc", "application_info_present: %d", application_info_present); - - if(application_info_present) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDeviceInfo); - } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneNfcDataInfo); - } - consumed = true; - } else if(event.event == SubmenuIndexRestoreOriginal) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneRestoreOriginalConfirm); - consumed = true; - } else if(event.event == SubmenuIndexMfUlUnlockByReader) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightUnlockAuto); - consumed = true; - } else if(event.event == SubmenuIndexMfUlUnlockByPassword) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneMfUltralightUnlockMenu); - consumed = true; - } - } - - return consumed; + return nfc_protocol_support_on_event(NfcProtocolSupportSceneSavedMenu, context, event); } void nfc_scene_saved_menu_on_exit(void* context) { - Nfc* nfc = context; - - submenu_reset(nfc->submenu); + nfc_protocol_support_on_exit(NfcProtocolSupportSceneSavedMenu, context); } diff --git a/applications/main/nfc/scenes/nfc_scene_select_protocol.c b/applications/main/nfc/scenes/nfc_scene_select_protocol.c new file mode 100644 index 000000000..86b9982fc --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_select_protocol.c @@ -0,0 +1,67 @@ +#include "../nfc_app_i.h" + +void nfc_scene_select_protocol_submenu_callback(void* context, uint32_t index) { + NfcApp* instance = context; + + view_dispatcher_send_custom_event(instance->view_dispatcher, index); +} + +void nfc_scene_select_protocol_on_enter(void* context) { + NfcApp* instance = context; + Submenu* submenu = instance->submenu; + + FuriString* temp_str = furi_string_alloc(); + const char* prefix; + if(scene_manager_has_previous_scene(instance->scene_manager, NfcSceneExtraActions)) { + prefix = "Read"; + instance->protocols_detected_num = NfcProtocolNum; + for(uint32_t i = 0; i < NfcProtocolNum; i++) { + instance->protocols_detected[i] = i; + } + } else { + prefix = "Read as"; + submenu_set_header(submenu, "Multi-protocol card"); + notification_message(instance->notifications, &sequence_single_vibro); + } + + for(uint32_t i = 0; i < instance->protocols_detected_num; i++) { + furi_string_printf( + temp_str, + "%s %s", + prefix, + nfc_device_get_protocol_name(instance->protocols_detected[i])); + submenu_add_item( + submenu, + furi_string_get_cstr(temp_str), + i, + nfc_scene_select_protocol_submenu_callback, + instance); + } + furi_string_free(temp_str); + + const uint32_t state = + scene_manager_get_scene_state(instance->scene_manager, NfcSceneSelectProtocol); + submenu_set_selected_item(submenu, state); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewMenu); +} + +bool nfc_scene_select_protocol_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + instance->protocols_detected_selected_idx = event.event; + scene_manager_next_scene(instance->scene_manager, NfcSceneRead); + scene_manager_set_scene_state( + instance->scene_manager, NfcSceneSelectProtocol, event.event); + consumed = true; + } + return consumed; +} + +void nfc_scene_select_protocol_on_exit(void* context) { + NfcApp* nfc = context; + + submenu_reset(nfc->submenu); +} diff --git a/applications/main/nfc/scenes/nfc_scene_set_atqa.c b/applications/main/nfc/scenes/nfc_scene_set_atqa.c index d079b3804..17a07b8b5 100644 --- a/applications/main/nfc/scenes/nfc_scene_set_atqa.c +++ b/applications/main/nfc/scenes/nfc_scene_set_atqa.c @@ -1,34 +1,39 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" -void nfc_scene_set_atqa_byte_input_callback(void* context) { - Nfc* nfc = context; +#include "../helpers/protocol_support/nfc_protocol_support_gui_common.h" - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventByteInputDone); +static void nfc_scene_set_atqa_byte_input_changed_callback(void* context) { + NfcApp* instance = context; + iso14443_3a_set_atqa(instance->iso14443_3a_edit_data, instance->byte_input_store); } void nfc_scene_set_atqa_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; + + iso14443_3a_get_atqa(instance->iso14443_3a_edit_data, instance->byte_input_store); // Setup view - ByteInput* byte_input = nfc->byte_input; + ByteInput* byte_input = instance->byte_input; byte_input_set_header_text(byte_input, "Enter ATQA in hex"); byte_input_set_result_callback( byte_input, - nfc_scene_set_atqa_byte_input_callback, - NULL, - nfc, - nfc->dev->dev_data.nfc_data.atqa, + nfc_protocol_support_common_byte_input_done_callback, + nfc_scene_set_atqa_byte_input_changed_callback, + instance, + instance->byte_input_store, 2); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewByteInput); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewByteInput); } bool nfc_scene_set_atqa_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == NfcCustomEventByteInputDone) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneSetUid); + nfc_device_set_data( + instance->nfc_device, NfcProtocolIso14443_3a, instance->iso14443_3a_edit_data); + scene_manager_next_scene(instance->scene_manager, NfcSceneSetUid); consumed = true; } } @@ -36,9 +41,9 @@ bool nfc_scene_set_atqa_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_set_atqa_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; // Clear view - byte_input_set_result_callback(nfc->byte_input, NULL, NULL, NULL, NULL, 0); - byte_input_set_header_text(nfc->byte_input, ""); + byte_input_set_result_callback(instance->byte_input, NULL, NULL, NULL, NULL, 0); + byte_input_set_header_text(instance->byte_input, ""); } diff --git a/applications/main/nfc/scenes/nfc_scene_set_sak.c b/applications/main/nfc/scenes/nfc_scene_set_sak.c index 60a1e1494..c55cee1c2 100644 --- a/applications/main/nfc/scenes/nfc_scene_set_sak.c +++ b/applications/main/nfc/scenes/nfc_scene_set_sak.c @@ -1,44 +1,48 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" -void nfc_scene_set_sak_byte_input_callback(void* context) { - Nfc* nfc = context; +#include "../helpers/protocol_support/nfc_protocol_support_gui_common.h" - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventByteInputDone); +static void nfc_scene_set_sak_byte_input_changed_callback(void* context) { + NfcApp* instance = context; + iso14443_3a_set_sak(instance->iso14443_3a_edit_data, instance->byte_input_store[0]); } void nfc_scene_set_sak_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; + + instance->byte_input_store[0] = iso14443_3a_get_sak(instance->iso14443_3a_edit_data); // Setup view - ByteInput* byte_input = nfc->byte_input; + ByteInput* byte_input = instance->byte_input; byte_input_set_header_text(byte_input, "Enter SAK in hex"); byte_input_set_result_callback( byte_input, - nfc_scene_set_sak_byte_input_callback, - NULL, - nfc, - &nfc->dev->dev_data.nfc_data.sak, + nfc_protocol_support_common_byte_input_done_callback, + nfc_scene_set_sak_byte_input_changed_callback, + instance, + instance->byte_input_store, 1); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewByteInput); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewByteInput); } bool nfc_scene_set_sak_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == NfcCustomEventByteInputDone) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneSetAtqa); + scene_manager_next_scene(instance->scene_manager, NfcSceneSetAtqa); consumed = true; } } + return consumed; } void nfc_scene_set_sak_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; // Clear view - byte_input_set_result_callback(nfc->byte_input, NULL, NULL, NULL, NULL, 0); - byte_input_set_header_text(nfc->byte_input, ""); + byte_input_set_result_callback(instance->byte_input, NULL, NULL, NULL, NULL, 0); + byte_input_set_header_text(instance->byte_input, ""); } diff --git a/applications/main/nfc/scenes/nfc_scene_set_type.c b/applications/main/nfc/scenes/nfc_scene_set_type.c index 0da633c63..e33660080 100644 --- a/applications/main/nfc/scenes/nfc_scene_set_type.c +++ b/applications/main/nfc/scenes/nfc_scene_set_type.c @@ -1,79 +1,72 @@ -#include "../nfc_i.h" -#include "lib/nfc/helpers/nfc_generators.h" +#include "../nfc_app_i.h" + +#include "../helpers/protocol_support/nfc_protocol_support_gui_common.h" enum SubmenuIndex { - SubmenuIndexNFCA4, - SubmenuIndexNFCA7, - SubmenuIndexMFClassicCustomUID, SubmenuIndexGeneratorsStart, + SubmenuIndexNFCA4 = NfcDataGeneratorTypeNum, + SubmenuIndexNFCA7, }; -void nfc_scene_set_type_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); +static void nfc_scene_set_type_init_edit_data(Iso14443_3aData* data, size_t uid_len) { + // Easiest way to create a zero'd buffer of given length + uint8_t* uid = malloc(uid_len); + iso14443_3a_set_uid(data, uid, uid_len); + free(uid); } void nfc_scene_set_type_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - // Clear device name - nfc_device_set_name(nfc->dev, ""); - furi_string_set(nfc->dev->load_path, ""); - submenu_add_item( - submenu, "NFC-A 7-bytes UID", SubmenuIndexNFCA7, nfc_scene_set_type_submenu_callback, nfc); - submenu_add_item( - submenu, "NFC-A 4-bytes UID", SubmenuIndexNFCA4, nfc_scene_set_type_submenu_callback, nfc); + NfcApp* instance = context; + + Submenu* submenu = instance->submenu; submenu_add_item( submenu, - "Mifare Classic Custom UID", - SubmenuIndexMFClassicCustomUID, - nfc_scene_set_type_submenu_callback, - nfc); + "NFC-A 7-bytes UID", + SubmenuIndexNFCA7, + nfc_protocol_support_common_submenu_callback, + instance); + submenu_add_item( + submenu, + "NFC-A 4-bytes UID", + SubmenuIndexNFCA4, + nfc_protocol_support_common_submenu_callback, + instance); - // Generators - int i = SubmenuIndexGeneratorsStart; - for(const NfcGenerator* const* generator = nfc_generators; *generator != NULL; - ++generator, ++i) { - submenu_add_item(submenu, (*generator)->name, i, nfc_scene_set_type_submenu_callback, nfc); + for(size_t i = 0; i < NfcDataGeneratorTypeNum; i++) { + const char* name = nfc_data_generator_get_name(i); + submenu_add_item(submenu, name, i, nfc_protocol_support_common_submenu_callback, instance); } - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewMenu); } bool nfc_scene_set_type_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == SubmenuIndexNFCA7) { - nfc->dev->dev_data.nfc_data.uid_len = 7; - nfc->dev->format = NfcDeviceSaveFormatUid; - scene_manager_next_scene(nfc->scene_manager, NfcSceneSetSak); + nfc_scene_set_type_init_edit_data(instance->iso14443_3a_edit_data, 7); + scene_manager_next_scene(instance->scene_manager, NfcSceneSetSak); consumed = true; } else if(event.event == SubmenuIndexNFCA4) { - nfc->dev->dev_data.nfc_data.uid_len = 4; - nfc->dev->format = NfcDeviceSaveFormatUid; - scene_manager_next_scene(nfc->scene_manager, NfcSceneSetSak); - consumed = true; - } else if(event.event == SubmenuIndexMFClassicCustomUID) { - nfc_device_clear(nfc->dev); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSetTypeMfUid); + nfc_scene_set_type_init_edit_data(instance->iso14443_3a_edit_data, 4); + scene_manager_next_scene(instance->scene_manager, NfcSceneSetSak); consumed = true; } else { - nfc_device_clear(nfc->dev); - nfc->generator = nfc_generators[event.event - SubmenuIndexGeneratorsStart]; - nfc->generator->generator_func(&nfc->dev->dev_data); - - scene_manager_next_scene(nfc->scene_manager, NfcSceneGenerateInfo); + nfc_data_generator_fill_data(event.event, instance->nfc_device); + scene_manager_set_scene_state( + instance->scene_manager, NfcSceneGenerateInfo, event.event); + scene_manager_next_scene(instance->scene_manager, NfcSceneGenerateInfo); consumed = true; } } + return consumed; } void nfc_scene_set_type_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; - submenu_reset(nfc->submenu); + submenu_reset(instance->submenu); } diff --git a/applications/main/nfc/scenes/nfc_scene_set_type_mf_uid.c b/applications/main/nfc/scenes/nfc_scene_set_type_mf_uid.c deleted file mode 100644 index 55919500a..000000000 --- a/applications/main/nfc/scenes/nfc_scene_set_type_mf_uid.c +++ /dev/null @@ -1,103 +0,0 @@ -#include "../nfc_i.h" -#include "lib/nfc/helpers/nfc_generators.h" - -enum SubmenuIndex { - SubmenuIndexMFC1k4b, - SubmenuIndexMFC4k4b, - SubmenuIndexMFC1k7b, - SubmenuIndexMFC4k7b, - SubmenuIndexMFCMini, -}; - -static const NfcGenerator ganeator_gag = { - .name = "Mifare Classic Custom UID", - .generator_func = NULL, -}; - -void nfc_scene_set_type_mf_uid_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; - - view_dispatcher_send_custom_event(nfc->view_dispatcher, index); -} - -void nfc_scene_set_type_mf_uid_on_enter(void* context) { - Nfc* nfc = context; - Submenu* submenu = nfc->submenu; - - submenu_add_item( - submenu, - "Mifare Classic 1k 4byte UID", - SubmenuIndexMFC1k4b, - nfc_scene_set_type_mf_uid_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Mifare Classic 4k 4byte UID", - SubmenuIndexMFC4k4b, - nfc_scene_set_type_mf_uid_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Mifare Classic 1k 7byte UID", - SubmenuIndexMFC1k7b, - nfc_scene_set_type_mf_uid_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Mifare Classic 4k 7byte UID", - SubmenuIndexMFC4k7b, - nfc_scene_set_type_mf_uid_submenu_callback, - nfc); - submenu_add_item( - submenu, - "Mifare Classic Mini", - SubmenuIndexMFCMini, - nfc_scene_set_type_mf_uid_submenu_callback, - nfc); - - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); -} - -bool nfc_scene_set_type_mf_uid_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; - bool consumed = false; - bool correct_index = false; - MfClassicType mf_type = MfClassicType1k; - - if(event.type == SceneManagerEventTypeCustom) { - if(event.event == SubmenuIndexMFC1k4b) { - nfc->dev->dev_data.nfc_data.uid_len = 4; - mf_type = MfClassicType1k; - correct_index = true; - } else if(event.event == SubmenuIndexMFC1k7b) { - nfc->dev->dev_data.nfc_data.uid_len = 7; - mf_type = MfClassicType1k; - correct_index = true; - } else if(event.event == SubmenuIndexMFC4k4b) { - nfc->dev->dev_data.nfc_data.uid_len = 4; - mf_type = MfClassicType4k; - correct_index = true; - } else if(event.event == SubmenuIndexMFC4k7b) { - nfc->dev->dev_data.nfc_data.uid_len = 7; - mf_type = MfClassicType4k; - correct_index = true; - } else if(event.event == SubmenuIndexMFCMini) { - nfc->dev->dev_data.nfc_data.uid_len = 4; - mf_type = MfClassicTypeMini; - correct_index = true; - } - if(correct_index) { - nfc->generator = &ganeator_gag; - scene_manager_set_scene_state(nfc->scene_manager, NfcSceneSetTypeMfUid, mf_type); - scene_manager_next_scene(nfc->scene_manager, NfcSceneSetUid); - consumed = true; - } - } - return consumed; -} - -void nfc_scene_set_type_mf_uid_on_exit(void* context) { - Nfc* nfc = context; - - submenu_reset(nfc->submenu); -} diff --git a/applications/main/nfc/scenes/nfc_scene_set_uid.c b/applications/main/nfc/scenes/nfc_scene_set_uid.c index 80ea5f6d0..df8a4dc72 100644 --- a/applications/main/nfc/scenes/nfc_scene_set_uid.c +++ b/applications/main/nfc/scenes/nfc_scene_set_uid.c @@ -1,57 +1,51 @@ -#include "../nfc_i.h" +#include "../nfc_app_i.h" -void nfc_scene_set_uid_byte_input_callback(void* context) { - Nfc* nfc = context; +#include "../helpers/protocol_support/nfc_protocol_support_gui_common.h" - view_dispatcher_send_custom_event(nfc->view_dispatcher, NfcCustomEventByteInputDone); +static void nfc_scene_set_uid_byte_input_changed_callback(void* context) { + NfcApp* instance = context; + // Retrieve previously saved UID length + const size_t uid_len = scene_manager_get_scene_state(instance->scene_manager, NfcSceneSetUid); + nfc_device_set_uid(instance->nfc_device, instance->byte_input_store, uid_len); } void nfc_scene_set_uid_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; + + size_t uid_len; + const uint8_t* uid = nfc_device_get_uid(instance->nfc_device, &uid_len); + + memcpy(instance->byte_input_store, uid, uid_len); + // Save UID length for use in callback + scene_manager_set_scene_state(instance->scene_manager, NfcSceneSetUid, uid_len); // Setup view - ByteInput* byte_input = nfc->byte_input; + ByteInput* byte_input = instance->byte_input; byte_input_set_header_text(byte_input, "Enter UID in hex"); - nfc->dev_edit_data = nfc->dev->dev_data.nfc_data; byte_input_set_result_callback( byte_input, - nfc_scene_set_uid_byte_input_callback, - NULL, - nfc, - nfc->dev_edit_data.uid, - nfc->dev_edit_data.uid_len); - view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewByteInput); + nfc_protocol_support_common_byte_input_done_callback, + nfc_scene_set_uid_byte_input_changed_callback, + instance, + instance->byte_input_store, + uid_len); + + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewByteInput); } bool nfc_scene_set_uid_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = (Nfc*)context; + NfcApp* instance = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == NfcCustomEventByteInputDone) { - if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSavedMenu)) { - nfc->dev->dev_data.nfc_data = nfc->dev_edit_data; - if(nfc_save_file(nfc)) { - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveSuccess); + if(scene_manager_has_previous_scene(instance->scene_manager, NfcSceneSavedMenu)) { + if(nfc_save(instance)) { + scene_manager_next_scene(instance->scene_manager, NfcSceneSaveSuccess); consumed = true; } - } else if(scene_manager_has_previous_scene(nfc->scene_manager, NfcSceneSetTypeMfUid)) { - MfClassicType mf_type = - scene_manager_get_scene_state(nfc->scene_manager, NfcSceneSetTypeMfUid); - if(mf_type > MfClassicTypeMini) { - furi_crash("Nfc unknown type"); - } - nfc_generate_mf_classic_ext( - &nfc->dev->dev_data, - nfc->dev_edit_data.uid_len, - mf_type, - false, - nfc->dev_edit_data.uid); - scene_manager_next_scene(nfc->scene_manager, NfcSceneGenerateInfo); - consumed = true; - } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneSaveName); + scene_manager_next_scene(instance->scene_manager, NfcSceneSaveName); consumed = true; } } @@ -61,9 +55,9 @@ bool nfc_scene_set_uid_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_set_uid_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* instance = context; // Clear view - byte_input_set_result_callback(nfc->byte_input, NULL, NULL, NULL, NULL, 0); - byte_input_set_header_text(nfc->byte_input, ""); + byte_input_set_result_callback(instance->byte_input, NULL, NULL, NULL, NULL, 0); + byte_input_set_header_text(instance->byte_input, ""); } diff --git a/applications/main/nfc/scenes/nfc_scene_start.c b/applications/main/nfc/scenes/nfc_scene_start.c index c9e8bf78c..c923226fc 100644 --- a/applications/main/nfc/scenes/nfc_scene_start.c +++ b/applications/main/nfc/scenes/nfc_scene_start.c @@ -1,5 +1,4 @@ -#include "../nfc_i.h" -#include "nfc_worker_i.h" +#include "../nfc_app_i.h" #include enum SubmenuIndex { @@ -12,15 +11,20 @@ enum SubmenuIndex { }; void nfc_scene_start_submenu_callback(void* context, uint32_t index) { - Nfc* nfc = context; + NfcApp* nfc = context; view_dispatcher_send_custom_event(nfc->view_dispatcher, index); } void nfc_scene_start_on_enter(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; Submenu* submenu = nfc->submenu; + // Clear file name and device contents + furi_string_reset(nfc->file_name); + nfc_device_clear(nfc->nfc_device); + iso14443_3a_reset(nfc->iso14443_3a_edit_data); + submenu_add_item(submenu, "Read", SubmenuIndexRead, nfc_scene_start_submenu_callback, nfc); submenu_add_item( submenu, "Detect Reader", SubmenuIndexDetectReader, nfc_scene_start_submenu_callback, nfc); @@ -38,32 +42,23 @@ void nfc_scene_start_on_enter(void* context) { submenu_set_selected_item( submenu, scene_manager_get_scene_state(nfc->scene_manager, NfcSceneStart)); - nfc_device_clear(nfc->dev); view_dispatcher_switch_to_view(nfc->view_dispatcher, NfcViewMenu); } bool nfc_scene_start_on_event(void* context, SceneManagerEvent event) { - Nfc* nfc = context; + NfcApp* nfc = context; bool consumed = false; if(event.type == SceneManagerEventTypeCustom) { if(event.event == SubmenuIndexRead) { scene_manager_set_scene_state(nfc->scene_manager, NfcSceneStart, SubmenuIndexRead); - nfc->dev->dev_data.read_mode = NfcReadModeAuto; - scene_manager_next_scene(nfc->scene_manager, NfcSceneRead); + scene_manager_next_scene(nfc->scene_manager, NfcSceneDetect); dolphin_deed(DolphinDeedNfcRead); consumed = true; } else if(event.event == SubmenuIndexDetectReader) { scene_manager_set_scene_state( nfc->scene_manager, NfcSceneStart, SubmenuIndexDetectReader); - bool sd_exist = storage_sd_status(nfc->dev->storage) == FSE_OK; - if(sd_exist) { - nfc_device_data_clear(&nfc->dev->dev_data); - scene_manager_next_scene(nfc->scene_manager, NfcSceneDetectReader); - dolphin_deed(DolphinDeedNfcDetectReader); - } else { - scene_manager_next_scene(nfc->scene_manager, NfcSceneDictNotFound); - } + scene_manager_next_scene(nfc->scene_manager, NfcSceneMfClassicDetectReader); consumed = true; } else if(event.event == SubmenuIndexSaved) { // Save the scene state explicitly in each branch, so that @@ -92,7 +87,7 @@ bool nfc_scene_start_on_event(void* context, SceneManagerEvent event) { } void nfc_scene_start_on_exit(void* context) { - Nfc* nfc = context; + NfcApp* nfc = context; submenu_reset(nfc->submenu); } diff --git a/applications/main/nfc/scenes/nfc_scene_supported_card.c b/applications/main/nfc/scenes/nfc_scene_supported_card.c new file mode 100644 index 000000000..cea55b783 --- /dev/null +++ b/applications/main/nfc/scenes/nfc_scene_supported_card.c @@ -0,0 +1,50 @@ +#include "nfc/nfc_app_i.h" + +#include "nfc/helpers/nfc_supported_cards.h" +#include "nfc/helpers/protocol_support/nfc_protocol_support_gui_common.h" + +void nfc_scene_supported_card_on_enter(void* context) { + NfcApp* instance = context; + + FuriString* temp_str = furi_string_alloc(); + + if(nfc_supported_cards_parse(instance->nfc_device, temp_str)) { + widget_add_text_scroll_element( + instance->widget, 0, 0, 128, 52, furi_string_get_cstr(temp_str)); + widget_add_button_element( + instance->widget, + GuiButtonTypeRight, + "More", + nfc_protocol_support_common_widget_callback, + instance); + + scene_manager_set_scene_state(instance->scene_manager, NfcSceneSupportedCard, true); + view_dispatcher_switch_to_view(instance->view_dispatcher, NfcViewWidget); + + } else { + scene_manager_set_scene_state(instance->scene_manager, NfcSceneSupportedCard, false); + scene_manager_next_scene(instance->scene_manager, NfcSceneInfo); + } + + furi_string_free(temp_str); +} + +bool nfc_scene_supported_card_on_event(void* context, SceneManagerEvent event) { + NfcApp* instance = context; + + bool consumed = false; + + if(event.type == SceneManagerEventTypeCustom) { + if(event.event == GuiButtonTypeRight) { + scene_manager_next_scene(instance->scene_manager, NfcSceneInfo); + consumed = true; + } + } + + return consumed; +} + +void nfc_scene_supported_card_on_exit(void* context) { + NfcApp* instance = context; + widget_reset(instance->widget); +} diff --git a/applications/main/nfc/views/detect_reader.c b/applications/main/nfc/views/detect_reader.c index e5951beb2..ebcda7caf 100644 --- a/applications/main/nfc/views/detect_reader.c +++ b/applications/main/nfc/views/detect_reader.c @@ -163,7 +163,10 @@ void detect_reader_set_nonces_collected(DetectReader* detect_reader, uint16_t no with_view_model( detect_reader->view, DetectReaderViewModel * model, - { model->nonces = nonces_collected; }, + { + model->nonces = nonces_collected; + model->state = DetectReaderStateReaderDetected; + }, false); } diff --git a/applications/main/nfc/views/dict_attack.c b/applications/main/nfc/views/dict_attack.c index 8f4bd063e..b656c2dc5 100644 --- a/applications/main/nfc/views/dict_attack.c +++ b/applications/main/nfc/views/dict_attack.c @@ -2,42 +2,36 @@ #include -typedef enum { - DictAttackStateRead, - DictAttackStateCardRemoved, -} DictAttackState; +#define NFC_CLASSIC_KEYS_PER_SECTOR 2 struct DictAttack { View* view; DictAttackCallback callback; void* context; - bool card_present; }; typedef struct { - DictAttackState state; - MfClassicType type; FuriString* header; + bool card_detected; uint8_t sectors_total; uint8_t sectors_read; - uint8_t sector_current; - uint8_t keys_total; + uint8_t current_sector; uint8_t keys_found; - uint16_t dict_keys_total; - uint16_t dict_keys_current; + size_t dict_keys_total; + size_t dict_keys_current; bool is_key_attack; uint8_t key_attack_current_sector; } DictAttackViewModel; static void dict_attack_draw_callback(Canvas* canvas, void* model) { DictAttackViewModel* m = model; - if(m->state == DictAttackStateCardRemoved) { + if(!m->card_detected) { canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Lost the tag!"); canvas_set_font(canvas, FontSecondary); elements_multiline_text_aligned( canvas, 64, 23, AlignCenter, AlignTop, "Make sure the tag is\npositioned correctly."); - } else if(m->state == DictAttackStateRead) { + } else { char draw_str[32] = {}; canvas_set_font(canvas, FontSecondary); canvas_draw_str_aligned( @@ -49,28 +43,33 @@ static void dict_attack_draw_callback(Canvas* canvas, void* model) { "Reuse key check for sector: %d", m->key_attack_current_sector); } else { - snprintf(draw_str, sizeof(draw_str), "Unlocking sector: %d", m->sector_current); + snprintf(draw_str, sizeof(draw_str), "Unlocking sector: %d", m->current_sector); } canvas_draw_str_aligned(canvas, 0, 10, AlignLeft, AlignTop, draw_str); float dict_progress = m->dict_keys_total == 0 ? 0 : (float)(m->dict_keys_current) / (float)(m->dict_keys_total); float progress = m->sectors_total == 0 ? 0 : - ((float)(m->sector_current) + dict_progress) / + ((float)(m->current_sector) + dict_progress) / (float)(m->sectors_total); - if(progress > 1.0) { - progress = 1.0; + if(progress > 1.0f) { + progress = 1.0f; } if(m->dict_keys_current == 0) { // Cause when people see 0 they think it's broken - snprintf(draw_str, sizeof(draw_str), "%d/%d", 1, m->dict_keys_total); + snprintf(draw_str, sizeof(draw_str), "%d/%zu", 1, m->dict_keys_total); } else { snprintf( - draw_str, sizeof(draw_str), "%d/%d", m->dict_keys_current, m->dict_keys_total); + draw_str, sizeof(draw_str), "%zu/%zu", m->dict_keys_current, m->dict_keys_total); } elements_progress_bar_with_text(canvas, 0, 20, 128, dict_progress, draw_str); canvas_set_font(canvas, FontSecondary); - snprintf(draw_str, sizeof(draw_str), "Keys found: %d/%d", m->keys_found, m->keys_total); + snprintf( + draw_str, + sizeof(draw_str), + "Keys found: %d/%d", + m->keys_found, + m->sectors_total * NFC_CLASSIC_KEYS_PER_SECTOR); canvas_draw_str_aligned(canvas, 0, 33, AlignLeft, AlignTop, draw_str); snprintf( draw_str, sizeof(draw_str), "Sectors Read: %d/%d", m->sectors_read, m->sectors_total); @@ -80,55 +79,56 @@ static void dict_attack_draw_callback(Canvas* canvas, void* model) { } static bool dict_attack_input_callback(InputEvent* event, void* context) { - DictAttack* dict_attack = context; + DictAttack* instance = context; bool consumed = false; + if(event->type == InputTypeShort && event->key == InputKeyOk) { - if(dict_attack->callback) { - dict_attack->callback(dict_attack->context); + if(instance->callback) { + instance->callback(DictAttackEventSkipPressed, instance->context); } consumed = true; } + return consumed; } DictAttack* dict_attack_alloc() { - DictAttack* dict_attack = malloc(sizeof(DictAttack)); - dict_attack->view = view_alloc(); - view_allocate_model(dict_attack->view, ViewModelTypeLocking, sizeof(DictAttackViewModel)); - view_set_draw_callback(dict_attack->view, dict_attack_draw_callback); - view_set_input_callback(dict_attack->view, dict_attack_input_callback); - view_set_context(dict_attack->view, dict_attack); + DictAttack* instance = malloc(sizeof(DictAttack)); + instance->view = view_alloc(); + view_allocate_model(instance->view, ViewModelTypeLocking, sizeof(DictAttackViewModel)); + view_set_draw_callback(instance->view, dict_attack_draw_callback); + view_set_input_callback(instance->view, dict_attack_input_callback); + view_set_context(instance->view, instance); with_view_model( - dict_attack->view, + instance->view, DictAttackViewModel * model, { model->header = furi_string_alloc(); }, false); - return dict_attack; + + return instance; } -void dict_attack_free(DictAttack* dict_attack) { - furi_assert(dict_attack); +void dict_attack_free(DictAttack* instance) { + furi_assert(instance); + with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { furi_string_free(model->header); }, - false); - view_free(dict_attack->view); - free(dict_attack); + instance->view, DictAttackViewModel * model, { furi_string_free(model->header); }, false); + + view_free(instance->view); + free(instance); } -void dict_attack_reset(DictAttack* dict_attack) { - furi_assert(dict_attack); +void dict_attack_reset(DictAttack* instance) { + furi_assert(instance); + with_view_model( - dict_attack->view, + instance->view, DictAttackViewModel * model, { - model->state = DictAttackStateRead; - model->type = MfClassicType1k; + model->card_detected = false; model->sectors_total = 0; model->sectors_read = 0; - model->sector_current = 0; - model->keys_total = 0; + model->current_sector = 0; model->keys_found = 0; model->dict_keys_total = 0; model->dict_keys_current = 0; @@ -138,152 +138,108 @@ void dict_attack_reset(DictAttack* dict_attack) { false); } -View* dict_attack_get_view(DictAttack* dict_attack) { - furi_assert(dict_attack); - return dict_attack->view; +View* dict_attack_get_view(DictAttack* instance) { + furi_assert(instance); + + return instance->view; } -void dict_attack_set_callback(DictAttack* dict_attack, DictAttackCallback callback, void* context) { - furi_assert(dict_attack); +void dict_attack_set_callback(DictAttack* instance, DictAttackCallback callback, void* context) { + furi_assert(instance); furi_assert(callback); - dict_attack->callback = callback; - dict_attack->context = context; + + instance->callback = callback; + instance->context = context; } -void dict_attack_set_header(DictAttack* dict_attack, const char* header) { - furi_assert(dict_attack); +void dict_attack_set_header(DictAttack* instance, const char* header) { + furi_assert(instance); furi_assert(header); with_view_model( - dict_attack->view, + instance->view, DictAttackViewModel * model, { furi_string_set(model->header, header); }, true); } -void dict_attack_set_card_detected(DictAttack* dict_attack, MfClassicType type) { - furi_assert(dict_attack); - dict_attack->card_present = true; +void dict_attack_set_card_state(DictAttack* instance, bool detected) { + furi_assert(instance); + with_view_model( - dict_attack->view, + instance->view, DictAttackViewModel * model, { model->card_detected = detected; }, true); +} + +void dict_attack_set_sectors_total(DictAttack* instance, uint8_t sectors_total) { + furi_assert(instance); + + with_view_model( + instance->view, DictAttackViewModel * model, - { - model->state = DictAttackStateRead; - model->sectors_total = mf_classic_get_total_sectors_num(type); - model->keys_total = model->sectors_total * 2; - }, + { model->sectors_total = sectors_total; }, true); } -void dict_attack_set_card_removed(DictAttack* dict_attack) { - furi_assert(dict_attack); - dict_attack->card_present = false; +void dict_attack_set_sectors_read(DictAttack* instance, uint8_t sectors_read) { + furi_assert(instance); + with_view_model( - dict_attack->view, + instance->view, DictAttackViewModel * model, { model->sectors_read = sectors_read; }, true); +} + +void dict_attack_set_keys_found(DictAttack* instance, uint8_t keys_found) { + furi_assert(instance); + + with_view_model( + instance->view, DictAttackViewModel * model, { model->keys_found = keys_found; }, true); +} + +void dict_attack_set_current_sector(DictAttack* instance, uint8_t current_sector) { + furi_assert(instance); + + with_view_model( + instance->view, DictAttackViewModel * model, - { model->state = DictAttackStateCardRemoved; }, + { model->current_sector = current_sector; }, true); } -bool dict_attack_get_card_state(DictAttack* dict_attack) { - furi_assert(dict_attack); - return dict_attack->card_present; -} +void dict_attack_set_total_dict_keys(DictAttack* instance, size_t dict_keys_total) { + furi_assert(instance); -void dict_attack_set_sector_read(DictAttack* dict_attack, uint8_t sec_read) { - furi_assert(dict_attack); with_view_model( - dict_attack->view, DictAttackViewModel * model, { model->sectors_read = sec_read; }, true); -} - -void dict_attack_set_keys_found(DictAttack* dict_attack, uint8_t keys_found) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, DictAttackViewModel * model, { model->keys_found = keys_found; }, true); -} - -void dict_attack_set_current_sector(DictAttack* dict_attack, uint8_t curr_sec) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - model->sector_current = curr_sec; - model->dict_keys_current = 0; - }, - true); -} - -void dict_attack_inc_current_sector(DictAttack* dict_attack) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - if(model->sector_current < model->sectors_total) { - model->sector_current++; - model->dict_keys_current = 0; - } - }, - true); -} - -void dict_attack_inc_keys_found(DictAttack* dict_attack) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - if(model->keys_found < model->keys_total) { - model->keys_found++; - } - }, - true); -} - -void dict_attack_set_total_dict_keys(DictAttack* dict_attack, uint16_t dict_keys_total) { - furi_assert(dict_attack); - with_view_model( - dict_attack->view, + instance->view, DictAttackViewModel * model, { model->dict_keys_total = dict_keys_total; }, true); } -void dict_attack_inc_current_dict_key(DictAttack* dict_attack, uint16_t keys_tried) { - furi_assert(dict_attack); +void dict_attack_set_current_dict_key(DictAttack* instance, size_t cur_key_num) { + furi_assert(instance); + with_view_model( - dict_attack->view, + instance->view, DictAttackViewModel * model, - { - if(model->dict_keys_current + keys_tried < model->dict_keys_total) { - model->dict_keys_current += keys_tried; - } - }, + { model->dict_keys_current = cur_key_num; }, true); } -void dict_attack_set_key_attack(DictAttack* dict_attack, bool is_key_attack, uint8_t sector) { - furi_assert(dict_attack); +void dict_attack_set_key_attack(DictAttack* instance, uint8_t sector) { + furi_assert(instance); + with_view_model( - dict_attack->view, + instance->view, DictAttackViewModel * model, { - model->is_key_attack = is_key_attack; + model->is_key_attack = true; model->key_attack_current_sector = sector; }, true); } -void dict_attack_inc_key_attack_current_sector(DictAttack* dict_attack) { - furi_assert(dict_attack); +void dict_attack_reset_key_attack(DictAttack* instance) { + furi_assert(instance); + with_view_model( - dict_attack->view, - DictAttackViewModel * model, - { - if(model->key_attack_current_sector < model->sectors_total) { - model->key_attack_current_sector++; - } - }, - true); + instance->view, DictAttackViewModel * model, { model->is_key_attack = false; }, true); } diff --git a/applications/main/nfc/views/dict_attack.h b/applications/main/nfc/views/dict_attack.h index 73b98a1b8..54a0220fe 100644 --- a/applications/main/nfc/views/dict_attack.h +++ b/applications/main/nfc/views/dict_attack.h @@ -1,46 +1,50 @@ #pragma once + #include #include -#include -#include +#ifdef __cplusplus +extern "C" { +#endif typedef struct DictAttack DictAttack; -typedef void (*DictAttackCallback)(void* context); +typedef enum { + DictAttackEventSkipPressed, +} DictAttackEvent; + +typedef void (*DictAttackCallback)(DictAttackEvent event, void* context); DictAttack* dict_attack_alloc(); -void dict_attack_free(DictAttack* dict_attack); +void dict_attack_free(DictAttack* instance); -void dict_attack_reset(DictAttack* dict_attack); +void dict_attack_reset(DictAttack* instance); -View* dict_attack_get_view(DictAttack* dict_attack); +View* dict_attack_get_view(DictAttack* instance); -void dict_attack_set_callback(DictAttack* dict_attack, DictAttackCallback callback, void* context); +void dict_attack_set_callback(DictAttack* instance, DictAttackCallback callback, void* context); -void dict_attack_set_header(DictAttack* dict_attack, const char* header); +void dict_attack_set_header(DictAttack* instance, const char* header); -void dict_attack_set_card_detected(DictAttack* dict_attack, MfClassicType type); +void dict_attack_set_card_state(DictAttack* instance, bool detected); -void dict_attack_set_card_removed(DictAttack* dict_attack); +void dict_attack_set_sectors_total(DictAttack* instance, uint8_t sectors_total); -bool dict_attack_get_card_state(DictAttack* dict_attack); +void dict_attack_set_sectors_read(DictAttack* instance, uint8_t sectors_read); -void dict_attack_set_sector_read(DictAttack* dict_attack, uint8_t sec_read); +void dict_attack_set_keys_found(DictAttack* instance, uint8_t keys_found); -void dict_attack_set_keys_found(DictAttack* dict_attack, uint8_t keys_found); +void dict_attack_set_current_sector(DictAttack* instance, uint8_t curr_sec); -void dict_attack_set_current_sector(DictAttack* dict_attack, uint8_t curr_sec); +void dict_attack_set_total_dict_keys(DictAttack* instance, size_t dict_keys_total); -void dict_attack_inc_current_sector(DictAttack* dict_attack); +void dict_attack_set_current_dict_key(DictAttack* instance, size_t cur_key_num); -void dict_attack_inc_keys_found(DictAttack* dict_attack); +void dict_attack_set_key_attack(DictAttack* instance, uint8_t sector); -void dict_attack_set_total_dict_keys(DictAttack* dict_attack, uint16_t dict_keys_total); +void dict_attack_reset_key_attack(DictAttack* instance); -void dict_attack_inc_current_dict_key(DictAttack* dict_attack, uint16_t keys_tried); - -void dict_attack_set_key_attack(DictAttack* dict_attack, bool is_key_attack, uint8_t sector); - -void dict_attack_inc_key_attack_current_sector(DictAttack* dict_attack); \ No newline at end of file +#ifdef __cplusplus +} +#endif diff --git a/applications/main/subghz/application.fam b/applications/main/subghz/application.fam index 7494e6fba..6ec301247 100644 --- a/applications/main/subghz/application.fam +++ b/applications/main/subghz/application.fam @@ -17,6 +17,7 @@ App( icon="A_Sub1ghz_14", stack_size=3 * 1024, order=1, + resources="resources", fap_libs=["assets", "hwdrivers"], fap_icon="icon.png", fap_category="Sub-GHz", diff --git a/assets/resources/subghz/assets/alutech_at_4n b/applications/main/subghz/resources/subghz/assets/alutech_at_4n similarity index 100% rename from assets/resources/subghz/assets/alutech_at_4n rename to applications/main/subghz/resources/subghz/assets/alutech_at_4n diff --git a/assets/resources/subghz/assets/dangerous_settings b/applications/main/subghz/resources/subghz/assets/dangerous_settings similarity index 100% rename from assets/resources/subghz/assets/dangerous_settings rename to applications/main/subghz/resources/subghz/assets/dangerous_settings diff --git a/assets/resources/subghz/assets/keeloq_mfcodes b/applications/main/subghz/resources/subghz/assets/keeloq_mfcodes similarity index 100% rename from assets/resources/subghz/assets/keeloq_mfcodes rename to applications/main/subghz/resources/subghz/assets/keeloq_mfcodes diff --git a/assets/resources/subghz/assets/keeloq_mfcodes_user.example b/applications/main/subghz/resources/subghz/assets/keeloq_mfcodes_user.example similarity index 100% rename from assets/resources/subghz/assets/keeloq_mfcodes_user.example rename to applications/main/subghz/resources/subghz/assets/keeloq_mfcodes_user.example diff --git a/assets/resources/subghz/assets/nice_flor_s b/applications/main/subghz/resources/subghz/assets/nice_flor_s similarity index 100% rename from assets/resources/subghz/assets/nice_flor_s rename to applications/main/subghz/resources/subghz/assets/nice_flor_s diff --git a/assets/resources/subghz/assets/setting_user.example b/applications/main/subghz/resources/subghz/assets/setting_user.example similarity index 100% rename from assets/resources/subghz/assets/setting_user.example rename to applications/main/subghz/resources/subghz/assets/setting_user.example diff --git a/applications/main/subghz/scenes/subghz_scene_rpc.c b/applications/main/subghz/scenes/subghz_scene_rpc.c index 724abaf3e..2f8a1f03f 100644 --- a/applications/main/subghz/scenes/subghz_scene_rpc.c +++ b/applications/main/subghz/scenes/subghz_scene_rpc.c @@ -35,13 +35,13 @@ bool subghz_scene_rpc_on_event(void* context, SceneManagerEvent event) { if(event.event == SubGhzCustomEventSceneExit) { scene_manager_stop(subghz->scene_manager); view_dispatcher_stop(subghz->view_dispatcher); - rpc_system_app_confirm(subghz->rpc_ctx, RpcAppEventAppExit, true); + rpc_system_app_confirm(subghz->rpc_ctx, true); } else if(event.event == SubGhzCustomEventSceneRpcSessionClose) { scene_manager_stop(subghz->scene_manager); view_dispatcher_stop(subghz->view_dispatcher); } else if(event.event == SubGhzCustomEventSceneRpcButtonPress) { bool result = false; - if((state == SubGhzRpcStateLoaded)) { + if(state == SubGhzRpcStateLoaded) { switch( subghz_txrx_tx_start(subghz->txrx, subghz_txrx_get_fff_data(subghz->txrx))) { case SubGhzTxRxStartTxStateErrorOnlyRx: @@ -63,7 +63,7 @@ bool subghz_scene_rpc_on_event(void* context, SceneManagerEvent event) { break; } } - rpc_system_app_confirm(subghz->rpc_ctx, RpcAppEventButtonPress, result); + rpc_system_app_confirm(subghz->rpc_ctx, result); } else if(event.event == SubGhzCustomEventSceneRpcButtonRelease) { bool result = false; if(state == SubGhzRpcStateTx) { @@ -72,15 +72,13 @@ bool subghz_scene_rpc_on_event(void* context, SceneManagerEvent event) { result = true; } state = SubGhzRpcStateIdle; - rpc_system_app_confirm(subghz->rpc_ctx, RpcAppEventButtonRelease, result); + rpc_system_app_confirm(subghz->rpc_ctx, result); } else if(event.event == SubGhzCustomEventSceneRpcLoad) { bool result = false; - const char* arg = rpc_system_app_get_data(subghz->rpc_ctx); - if(arg && (state == SubGhzRpcStateIdle)) { - if(subghz_key_load(subghz, arg, false)) { + if(state == SubGhzRpcStateIdle) { + if(subghz_key_load(subghz, furi_string_get_cstr(subghz->file_path), false)) { scene_manager_set_scene_state( subghz->scene_manager, SubGhzSceneRpc, SubGhzRpcStateLoaded); - furi_string_set(subghz->file_path, arg); result = true; FuriString* file_name = furi_string_alloc(); path_extract_filename(subghz->file_path, file_name, true); @@ -98,7 +96,7 @@ bool subghz_scene_rpc_on_event(void* context, SceneManagerEvent event) { rpc_system_app_set_error_text(subghz->rpc_ctx, "Cannot parse file"); } } - rpc_system_app_confirm(subghz->rpc_ctx, RpcAppEventLoadFile, result); + rpc_system_app_confirm(subghz->rpc_ctx, result); } } return consumed; diff --git a/applications/main/subghz/subghz.c b/applications/main/subghz/subghz.c index b5e6371e9..8eb7eec99 100644 --- a/applications/main/subghz/subghz.c +++ b/applications/main/subghz/subghz.c @@ -26,29 +26,31 @@ void subghz_tick_event_callback(void* context) { scene_manager_handle_tick_event(subghz->scene_manager); } -static void subghz_rpc_command_callback(RpcAppSystemEvent event, void* context) { +static void subghz_rpc_command_callback(const RpcAppSystemEvent* event, void* context) { furi_assert(context); SubGhz* subghz = context; furi_assert(subghz->rpc_ctx); - if(event == RpcAppEventSessionClose) { + if(event->type == RpcAppEventTypeSessionClose) { view_dispatcher_send_custom_event( subghz->view_dispatcher, SubGhzCustomEventSceneRpcSessionClose); rpc_system_app_set_callback(subghz->rpc_ctx, NULL, NULL); subghz->rpc_ctx = NULL; - } else if(event == RpcAppEventAppExit) { + } else if(event->type == RpcAppEventTypeAppExit) { view_dispatcher_send_custom_event(subghz->view_dispatcher, SubGhzCustomEventSceneExit); - } else if(event == RpcAppEventLoadFile) { + } else if(event->type == RpcAppEventTypeLoadFile) { + furi_assert(event->data.type == RpcAppSystemEventDataTypeString); + furi_string_set(subghz->file_path, event->data.string); view_dispatcher_send_custom_event(subghz->view_dispatcher, SubGhzCustomEventSceneRpcLoad); - } else if(event == RpcAppEventButtonPress) { + } else if(event->type == RpcAppEventTypeButtonPress) { view_dispatcher_send_custom_event( subghz->view_dispatcher, SubGhzCustomEventSceneRpcButtonPress); - } else if(event == RpcAppEventButtonRelease) { + } else if(event->type == RpcAppEventTypeButtonRelease) { view_dispatcher_send_custom_event( subghz->view_dispatcher, SubGhzCustomEventSceneRpcButtonRelease); } else { - rpc_system_app_confirm(subghz->rpc_ctx, event, false); + rpc_system_app_confirm(subghz->rpc_ctx, false); } } diff --git a/applications/main/subghz/subghz_dangerous_freq.c b/applications/main/subghz/subghz_dangerous_freq.c index 8552c5f16..9722d28b6 100644 --- a/applications/main/subghz/subghz_dangerous_freq.c +++ b/applications/main/subghz/subghz_dangerous_freq.c @@ -1,7 +1,7 @@ #include #include -#include +#include #include diff --git a/applications/main/subghz/views/receiver.c b/applications/main/subghz/views/receiver.c index 010e47062..f1d0324fc 100644 --- a/applications/main/subghz/views/receiver.c +++ b/applications/main/subghz/views/receiver.c @@ -111,7 +111,7 @@ void subghz_view_receiver_set_lock(SubGhzViewReceiver* subghz_receiver, bool loc SubGhzViewReceiverModel * model, { model->bar_show = SubGhzViewReceiverBarShowLock; }, true); - furi_timer_start(subghz_receiver->timer, pdMS_TO_TICKS(1000)); + furi_timer_start(subghz_receiver->timer, 1000); } else { with_view_model( subghz_receiver->view, @@ -453,7 +453,7 @@ bool subghz_view_receiver_input(InputEvent* event, void* context) { { model->bar_show = SubGhzViewReceiverBarShowToUnlockPress; }, true); if(subghz_receiver->lock_count == 0) { - furi_timer_start(subghz_receiver->timer, pdMS_TO_TICKS(1000)); + furi_timer_start(subghz_receiver->timer, 1000); } if(event->key == InputKeyBack && event->type == InputTypeShort) { subghz_receiver->lock_count++; @@ -467,7 +467,7 @@ bool subghz_view_receiver_input(InputEvent* event, void* context) { { model->bar_show = SubGhzViewReceiverBarShowUnlock; }, true); //subghz_receiver->lock = false; - furi_timer_start(subghz_receiver->timer, pdMS_TO_TICKS(650)); + furi_timer_start(subghz_receiver->timer, 650); } return true; diff --git a/applications/main/u2f/application.fam b/applications/main/u2f/application.fam index 8167e6277..bf41eb0f7 100644 --- a/applications/main/u2f/application.fam +++ b/applications/main/u2f/application.fam @@ -6,6 +6,7 @@ App( stack_size=2 * 1024, icon="A_U2F_14", order=80, + resources="resources", fap_libs=["assets"], fap_category="USB", fap_icon="icon.png", diff --git a/assets/resources/u2f/assets/cert.der b/applications/main/u2f/resources/u2f/assets/cert.der similarity index 100% rename from assets/resources/u2f/assets/cert.der rename to applications/main/u2f/resources/u2f/assets/cert.der diff --git a/assets/resources/u2f/assets/cert_key.u2f b/applications/main/u2f/resources/u2f/assets/cert_key.u2f similarity index 100% rename from assets/resources/u2f/assets/cert_key.u2f rename to applications/main/u2f/resources/u2f/assets/cert_key.u2f diff --git a/applications/services/desktop/animations/animation_manager.c b/applications/services/desktop/animations/animation_manager.c index f4c8f17a3..44c0c228c 100644 --- a/applications/services/desktop/animations/animation_manager.c +++ b/applications/services/desktop/animations/animation_manager.c @@ -2,7 +2,6 @@ #include #include #include -#include #include #include #include @@ -450,13 +449,13 @@ void animation_manager_unload_and_stall_animation(AnimationManager* animation_ma animation_manager->state = AnimationManagerStateFreezedIdle; animation_manager->freezed_animation_time_left = - xTimerGetExpiryTime(animation_manager->idle_animation_timer) - xTaskGetTickCount(); + furi_timer_get_expire_time(animation_manager->idle_animation_timer) - furi_get_tick(); if(animation_manager->freezed_animation_time_left < 0) { animation_manager->freezed_animation_time_left = 0; } furi_timer_stop(animation_manager->idle_animation_timer); } else { - furi_assert(0); + furi_crash(); } FURI_LOG_I( @@ -528,7 +527,7 @@ void animation_manager_load_and_continue_animation(AnimationManager* animation_m } } else { /* Unknown state is an error. But not in release version.*/ - furi_assert(0); + furi_crash(); } /* if can't restore previous animation - select new */ @@ -564,7 +563,7 @@ static void animation_manager_switch_to_one_shot_view(AnimationManager* animatio } else if(stats.level == 2) { one_shot_view_start_animation(animation_manager->one_shot_view, &A_Levelup2_128x64); } else { - furi_assert(0); + furi_crash(); } } diff --git a/applications/services/desktop/animations/animation_storage.c b/applications/services/desktop/animations/animation_storage.c index 2c16cf726..c99cc7b5d 100644 --- a/applications/services/desktop/animations/animation_storage.c +++ b/applications/services/desktop/animations/animation_storage.c @@ -304,7 +304,7 @@ static bool animation_storage_load_frames( if(file_info.size > max_filesize) { FURI_LOG_E( TAG, - "Filesize %lld, max: %d (width %d, height %d)", + "Filesize %llu, max: %zu (width %u, height %u)", file_info.size, max_filesize, width, @@ -329,7 +329,7 @@ static bool animation_storage_load_frames( if(!frames_ok) { FURI_LOG_E( TAG, - "Load \'%s\' failed, %dx%d, size: %lld", + "Load \'%s\' failed, %ux%u, size: %llu", furi_string_get_cstr(filename), width, height, diff --git a/applications/services/desktop/animations/views/bubble_animation_view.c b/applications/services/desktop/animations/views/bubble_animation_view.c index bd13bd34a..ca48bfdc7 100644 --- a/applications/services/desktop/animations/views/bubble_animation_view.c +++ b/applications/services/desktop/animations/views/bubble_animation_view.c @@ -23,7 +23,7 @@ typedef struct { uint8_t active_bubbles; uint8_t passive_bubbles; uint8_t active_shift; - TickType_t active_ended_at; + uint32_t active_ended_at; Icon* freeze_frame; } BubbleAnimationViewModel; @@ -152,7 +152,7 @@ static void bubble_animation_activate(BubbleAnimationView* view, bool force) { if(model->current != NULL) { if(!force) { if((model->active_ended_at + model->current->active_cooldown * 1000) > - xTaskGetTickCount()) { + furi_get_tick()) { activate = false; } else if(model->active_shift) { activate = false; @@ -213,7 +213,7 @@ static void bubble_animation_next_frame(BubbleAnimationViewModel* model) { model->active_cycle = 0; model->current_frame = 0; model->current_bubble = bubble_animation_pick_bubble(model, false); - model->active_ended_at = xTaskGetTickCount(); + model->active_ended_at = furi_get_tick(); } if(model->current_bubble) { @@ -353,7 +353,7 @@ void bubble_animation_view_set_animation( furi_assert(model); model->current = new_animation; - model->active_ended_at = xTaskGetTickCount() - (model->current->active_cooldown * 1000); + model->active_ended_at = furi_get_tick() - (model->current->active_cooldown * 1000); model->active_bubbles = 0; model->passive_bubbles = 0; for(int i = 0; i < new_animation->frame_bubble_sequences_count; ++i) { diff --git a/applications/services/desktop/animations/views/one_shot_animation_view.c b/applications/services/desktop/animations/views/one_shot_animation_view.c index 077f82d09..004fcde7b 100644 --- a/applications/services/desktop/animations/views/one_shot_animation_view.c +++ b/applications/services/desktop/animations/views/one_shot_animation_view.c @@ -1,7 +1,6 @@ #include "one_shot_animation_view.h" #include -#include #include #include #include @@ -11,7 +10,7 @@ typedef void (*OneShotInteractCallback)(void*); struct OneShotView { View* view; - TimerHandle_t update_timer; + FuriTimer* update_timer; OneShotInteractCallback interact_callback; void* interact_callback_context; }; @@ -22,8 +21,8 @@ typedef struct { bool block_input; } OneShotViewModel; -static void one_shot_view_update_timer_callback(TimerHandle_t xTimer) { - OneShotView* view = (void*)pvTimerGetTimerID(xTimer); +static void one_shot_view_update_timer_callback(void* context) { + OneShotView* view = context; OneShotViewModel* model = view_get_model(view->view); if((model->index + 1) < model->icon->frame_count) { @@ -81,7 +80,7 @@ OneShotView* one_shot_view_alloc(void) { OneShotView* view = malloc(sizeof(OneShotView)); view->view = view_alloc(); view->update_timer = - xTimerCreate(NULL, 1000, pdTRUE, view, one_shot_view_update_timer_callback); + furi_timer_alloc(one_shot_view_update_timer_callback, FuriTimerTypePeriodic, view); view_allocate_model(view->view, ViewModelTypeLocking, sizeof(OneShotViewModel)); view_set_context(view->view, view); @@ -94,7 +93,7 @@ OneShotView* one_shot_view_alloc(void) { void one_shot_view_free(OneShotView* view) { furi_assert(view); - xTimerDelete(view->update_timer, portMAX_DELAY); + furi_timer_free(view->update_timer); view_free(view->view); view->view = NULL; free(view); @@ -120,7 +119,7 @@ void one_shot_view_start_animation(OneShotView* view, const Icon* icon) { model->icon = icon; model->block_input = true; view_commit_model(view->view, true); - xTimerChangePeriod(view->update_timer, 1000 / model->icon->frame_rate, portMAX_DELAY); + furi_timer_start(view->update_timer, 1000 / model->icon->frame_rate); } View* one_shot_view_get_view(OneShotView* view) { diff --git a/applications/services/desktop/scenes/desktop_scene_locked.c b/applications/services/desktop/scenes/desktop_scene_locked.c index bbed56001..034eedb8a 100644 --- a/applications/services/desktop/scenes/desktop_scene_locked.c +++ b/applications/services/desktop/scenes/desktop_scene_locked.c @@ -3,7 +3,6 @@ #include #include #include -#include #include "../desktop.h" #include "../desktop_i.h" diff --git a/applications/services/desktop/scenes/desktop_scene_pin_input.c b/applications/services/desktop/scenes/desktop_scene_pin_input.c index e062c1b97..0e248def6 100644 --- a/applications/services/desktop/scenes/desktop_scene_pin_input.c +++ b/applications/services/desktop/scenes/desktop_scene_pin_input.c @@ -3,7 +3,6 @@ #include #include #include -#include #include #include @@ -20,7 +19,7 @@ #define INPUT_PIN_VIEW_TIMEOUT 15000 typedef struct { - TimerHandle_t timer; + FuriTimer* timer; } DesktopScenePinInputState; static void desktop_scene_locked_light_red(bool value) { @@ -33,17 +32,16 @@ static void desktop_scene_locked_light_red(bool value) { furi_record_close(RECORD_NOTIFICATION); } -static void - desktop_scene_pin_input_set_timer(Desktop* desktop, bool enable, TickType_t new_period) { +static void desktop_scene_pin_input_set_timer(Desktop* desktop, bool enable, uint32_t new_period) { furi_assert(desktop); DesktopScenePinInputState* state = (DesktopScenePinInputState*)scene_manager_get_scene_state( desktop->scene_manager, DesktopScenePinInput); furi_assert(state); if(enable) { - xTimerChangePeriod(state->timer, new_period, portMAX_DELAY); + furi_timer_start(state->timer, new_period); } else { - xTimerStop(state->timer, portMAX_DELAY); + furi_timer_stop(state->timer); } } @@ -64,8 +62,8 @@ static void desktop_scene_pin_input_done_callback(const PinCode* pin_code, void* } } -static void desktop_scene_pin_input_timer_callback(TimerHandle_t timer) { - Desktop* desktop = pvTimerGetTimerID(timer); +static void desktop_scene_pin_input_timer_callback(void* context) { + Desktop* desktop = context; view_dispatcher_send_custom_event( desktop->view_dispatcher, DesktopPinInputEventResetWrongPinLabel); @@ -84,7 +82,7 @@ void desktop_scene_pin_input_on_enter(void* context) { DesktopScenePinInputState* state = malloc(sizeof(DesktopScenePinInputState)); state->timer = - xTimerCreate(NULL, 10000, pdFALSE, desktop, desktop_scene_pin_input_timer_callback); + furi_timer_alloc(desktop_scene_pin_input_timer_callback, FuriTimerTypeOnce, desktop); scene_manager_set_scene_state(desktop->scene_manager, DesktopScenePinInput, (uint32_t)state); desktop_view_pin_input_hide_pin(desktop->pin_input_view, true); @@ -149,10 +147,7 @@ void desktop_scene_pin_input_on_exit(void* context) { DesktopScenePinInputState* state = (DesktopScenePinInputState*)scene_manager_get_scene_state( desktop->scene_manager, DesktopScenePinInput); - xTimerStop(state->timer, portMAX_DELAY); - while(xTimerIsTimerActive(state->timer)) { - furi_delay_tick(1); - } - xTimerDelete(state->timer, portMAX_DELAY); + + furi_timer_free(state->timer); free(state); } diff --git a/applications/services/desktop/scenes/desktop_scene_pin_timeout.c b/applications/services/desktop/scenes/desktop_scene_pin_timeout.c index ebe825e6a..e3336ad76 100644 --- a/applications/services/desktop/scenes/desktop_scene_pin_timeout.c +++ b/applications/services/desktop/scenes/desktop_scene_pin_timeout.c @@ -1,7 +1,5 @@ #include #include -#include -#include #include #include "../desktop_i.h" diff --git a/applications/services/desktop/views/desktop_view_lock_menu.c b/applications/services/desktop/views/desktop_view_lock_menu.c index 8b0eb3760..4665e5e15 100644 --- a/applications/services/desktop/views/desktop_view_lock_menu.c +++ b/applications/services/desktop/views/desktop_view_lock_menu.c @@ -60,13 +60,13 @@ void desktop_lock_menu_draw_callback(Canvas* canvas, void* model) { str = "Lock"; } else if(i == DesktopLockMenuIndexStealth) { if(m->stealth_mode) { - str = "Sound Mode"; + str = "Unmute"; } else { - str = "Stealth Mode"; + str = "Mute"; } } else if(i == DesktopLockMenuIndexDummy) { //-V547 if(m->dummy_mode) { - str = "Brainiac Mode"; + str = "Default Mode"; } else { str = "Dummy Mode"; } diff --git a/applications/services/desktop/views/desktop_view_locked.c b/applications/services/desktop/views/desktop_view_locked.c index 67cebfaab..97feb3c12 100644 --- a/applications/services/desktop/views/desktop_view_locked.c +++ b/applications/services/desktop/views/desktop_view_locked.c @@ -5,7 +5,6 @@ #include #include #include -#include #include #include "../desktop_i.h" @@ -29,7 +28,7 @@ struct DesktopViewLocked { DesktopViewLockedCallback callback; void* context; - TimerHandle_t timer; + FuriTimer* timer; uint8_t lock_count; uint32_t lock_lastpress; }; @@ -58,8 +57,8 @@ void desktop_view_locked_set_callback( locked_view->context = context; } -static void locked_view_timer_callback(TimerHandle_t timer) { - DesktopViewLocked* locked_view = pvTimerGetTimerID(timer); +static void locked_view_timer_callback(void* context) { + DesktopViewLocked* locked_view = context; locked_view->callback(DesktopLockedEventUpdate, locked_view->context); } @@ -90,7 +89,7 @@ static void desktop_view_locked_update_hint_icon_timeout(DesktopViewLocked* lock model->view_state = DesktopViewLockedStateLockedHintShown; } view_commit_model(locked_view->view, change_state); - xTimerChangePeriod(locked_view->timer, pdMS_TO_TICKS(LOCKED_HINT_TIMEOUT_MS), portMAX_DELAY); + furi_timer_start(locked_view->timer, LOCKED_HINT_TIMEOUT_MS); } void desktop_view_locked_update(DesktopViewLocked* locked_view) { @@ -110,7 +109,7 @@ void desktop_view_locked_update(DesktopViewLocked* locked_view) { view_commit_model(locked_view->view, true); if(view_state != DesktopViewLockedStateDoorsClosing) { - xTimerStop(locked_view->timer, portMAX_DELAY); + furi_timer_stop(locked_view->timer); } } @@ -148,7 +147,7 @@ static bool desktop_view_locked_input(InputEvent* event, void* context) { furi_assert(context); bool is_changed = false; - const uint32_t press_time = xTaskGetTickCount(); + const uint32_t press_time = furi_get_tick(); DesktopViewLocked* locked_view = context; DesktopViewLockedModel* model = view_get_model(locked_view->view); if(model->view_state == DesktopViewLockedStateUnlockedHintShown && @@ -196,7 +195,7 @@ DesktopViewLocked* desktop_view_locked_alloc() { DesktopViewLocked* locked_view = malloc(sizeof(DesktopViewLocked)); locked_view->view = view_alloc(); locked_view->timer = - xTimerCreate(NULL, 1000 / 16, pdTRUE, locked_view, locked_view_timer_callback); + furi_timer_alloc(locked_view_timer_callback, FuriTimerTypePeriodic, locked_view); view_allocate_model(locked_view->view, ViewModelTypeLocking, sizeof(DesktopViewLockedModel)); view_set_context(locked_view->view, locked_view); @@ -219,7 +218,7 @@ void desktop_view_locked_close_doors(DesktopViewLocked* locked_view) { model->view_state = DesktopViewLockedStateDoorsClosing; model->door_offset = DOOR_OFFSET_START; view_commit_model(locked_view->view, true); - xTimerChangePeriod(locked_view->timer, pdMS_TO_TICKS(DOOR_MOVING_INTERVAL_MS), portMAX_DELAY); + furi_timer_start(locked_view->timer, DOOR_MOVING_INTERVAL_MS); } void desktop_view_locked_lock(DesktopViewLocked* locked_view, bool pin_locked) { @@ -236,7 +235,7 @@ void desktop_view_locked_unlock(DesktopViewLocked* locked_view) { model->view_state = DesktopViewLockedStateUnlockedHintShown; model->pin_locked = false; view_commit_model(locked_view->view, true); - xTimerChangePeriod(locked_view->timer, pdMS_TO_TICKS(UNLOCKED_HINT_TIMEOUT_MS), portMAX_DELAY); + furi_timer_start(locked_view->timer, UNLOCKED_HINT_TIMEOUT_MS); } bool desktop_view_locked_is_locked_hint_visible(DesktopViewLocked* locked_view) { diff --git a/applications/services/desktop/views/desktop_view_main.c b/applications/services/desktop/views/desktop_view_main.c index c274dd540..ace0674e1 100644 --- a/applications/services/desktop/views/desktop_view_main.c +++ b/applications/services/desktop/views/desktop_view_main.c @@ -13,14 +13,14 @@ struct DesktopMainView { View* view; DesktopMainViewCallback callback; void* context; - TimerHandle_t poweroff_timer; + FuriTimer* poweroff_timer; bool dummy_mode; }; #define DESKTOP_MAIN_VIEW_POWEROFF_TIMEOUT 1300 -static void desktop_main_poweroff_timer_callback(TimerHandle_t timer) { - DesktopMainView* main_view = pvTimerGetTimerID(timer); +static void desktop_main_poweroff_timer_callback(void* context) { + DesktopMainView* main_view = context; main_view->callback(DesktopMainEventOpenPowerOff, main_view->context); } @@ -110,12 +110,9 @@ bool desktop_main_input_callback(InputEvent* event, void* context) { if(event->key == InputKeyBack) { if(event->type == InputTypePress) { - xTimerChangePeriod( - main_view->poweroff_timer, - pdMS_TO_TICKS(DESKTOP_MAIN_VIEW_POWEROFF_TIMEOUT), - portMAX_DELAY); + furi_timer_start(main_view->poweroff_timer, DESKTOP_MAIN_VIEW_POWEROFF_TIMEOUT); } else if(event->type == InputTypeRelease) { - xTimerStop(main_view->poweroff_timer, portMAX_DELAY); + furi_timer_stop(main_view->poweroff_timer); } } @@ -129,12 +126,8 @@ DesktopMainView* desktop_main_alloc() { view_set_context(main_view->view, main_view); view_set_input_callback(main_view->view, desktop_main_input_callback); - main_view->poweroff_timer = xTimerCreate( - NULL, - pdMS_TO_TICKS(DESKTOP_MAIN_VIEW_POWEROFF_TIMEOUT), - pdFALSE, - main_view, - desktop_main_poweroff_timer_callback); + main_view->poweroff_timer = + furi_timer_alloc(desktop_main_poweroff_timer_callback, FuriTimerTypeOnce, main_view); return main_view; } diff --git a/applications/services/desktop/views/desktop_view_pin_input.c b/applications/services/desktop/views/desktop_view_pin_input.c index d3dadd7d7..0894bb776 100644 --- a/applications/services/desktop/views/desktop_view_pin_input.c +++ b/applications/services/desktop/views/desktop_view_pin_input.c @@ -4,7 +4,6 @@ #include #include #include -#include #include "desktop_view_pin_input.h" #include @@ -21,7 +20,7 @@ struct DesktopViewPinInput { DesktopViewPinInputCallback timeout_callback; DesktopViewPinInputDoneCallback done_callback; void* context; - TimerHandle_t timer; + FuriTimer* timer; }; typedef struct { @@ -78,7 +77,7 @@ static bool desktop_view_pin_input_input(InputEvent* event, void* context) { } break; default: - furi_assert(0); + furi_crash(); break; } } @@ -90,7 +89,7 @@ static bool desktop_view_pin_input_input(InputEvent* event, void* context) { pin_input->back_callback(pin_input->context); } - xTimerStart(pin_input->timer, 0); + furi_timer_start(pin_input->timer, NO_ACTIVITY_TIMEOUT); return true; } @@ -129,7 +128,7 @@ static void desktop_view_pin_input_draw_cells(Canvas* canvas, DesktopViewPinInpu canvas_draw_icon_ex(canvas, x + 2, y + 3, &I_Pin_arrow_up_7x9, IconRotation90); break; default: - furi_assert(0); + furi_crash(); break; } } @@ -170,8 +169,8 @@ static void desktop_view_pin_input_draw(Canvas* canvas, void* context) { } } -void desktop_view_pin_input_timer_callback(TimerHandle_t timer) { - DesktopViewPinInput* pin_input = pvTimerGetTimerID(timer); +void desktop_view_pin_input_timer_callback(void* context) { + DesktopViewPinInput* pin_input = context; if(pin_input->timeout_callback) { pin_input->timeout_callback(pin_input->context); @@ -180,12 +179,12 @@ void desktop_view_pin_input_timer_callback(TimerHandle_t timer) { static void desktop_view_pin_input_enter(void* context) { DesktopViewPinInput* pin_input = context; - xTimerStart(pin_input->timer, portMAX_DELAY); + furi_timer_start(pin_input->timer, NO_ACTIVITY_TIMEOUT); } static void desktop_view_pin_input_exit(void* context) { DesktopViewPinInput* pin_input = context; - xTimerStop(pin_input->timer, portMAX_DELAY); + furi_timer_stop(pin_input->timer); } DesktopViewPinInput* desktop_view_pin_input_alloc(void) { @@ -195,12 +194,8 @@ DesktopViewPinInput* desktop_view_pin_input_alloc(void) { view_set_context(pin_input->view, pin_input); view_set_draw_callback(pin_input->view, desktop_view_pin_input_draw); view_set_input_callback(pin_input->view, desktop_view_pin_input_input); - pin_input->timer = xTimerCreate( - NULL, - pdMS_TO_TICKS(NO_ACTIVITY_TIMEOUT), - pdFALSE, - pin_input, - desktop_view_pin_input_timer_callback); + pin_input->timer = + furi_timer_alloc(desktop_view_pin_input_timer_callback, FuriTimerTypeOnce, pin_input); view_set_enter_callback(pin_input->view, desktop_view_pin_input_enter); view_set_exit_callback(pin_input->view, desktop_view_pin_input_exit); @@ -216,11 +211,7 @@ DesktopViewPinInput* desktop_view_pin_input_alloc(void) { void desktop_view_pin_input_free(DesktopViewPinInput* pin_input) { furi_assert(pin_input); - xTimerStop(pin_input->timer, portMAX_DELAY); - while(xTimerIsTimerActive(pin_input->timer)) { - furi_delay_tick(1); - } - xTimerDelete(pin_input->timer, portMAX_DELAY); + furi_timer_free(pin_input->timer); view_free(pin_input->view); free(pin_input); diff --git a/applications/services/desktop/views/desktop_view_pin_timeout.c b/applications/services/desktop/views/desktop_view_pin_timeout.c index e64c264ff..f24ecc8ea 100644 --- a/applications/services/desktop/views/desktop_view_pin_timeout.c +++ b/applications/services/desktop/views/desktop_view_pin_timeout.c @@ -3,7 +3,6 @@ #include #include #include -#include #include #include #include @@ -13,7 +12,7 @@ struct DesktopViewPinTimeout { View* view; - TimerHandle_t timer; + FuriTimer* timer; DesktopViewPinTimeoutDoneCallback callback; void* context; }; @@ -32,8 +31,8 @@ void desktop_view_pin_timeout_set_callback( instance->context = context; } -static void desktop_view_pin_timeout_timer_callback(TimerHandle_t timer) { - DesktopViewPinTimeout* instance = pvTimerGetTimerID(timer); +static void desktop_view_pin_timeout_timer_callback(void* context) { + DesktopViewPinTimeout* instance = context; bool stop = false; DesktopViewPinTimeoutModel* model = view_get_model(instance->view); @@ -45,7 +44,7 @@ static void desktop_view_pin_timeout_timer_callback(TimerHandle_t timer) { view_commit_model(instance->view, true); if(stop) { - xTimerStop(instance->timer, portMAX_DELAY); + furi_timer_stop(instance->timer); instance->callback(instance->context); } } @@ -73,15 +72,15 @@ static void desktop_view_pin_timeout_draw(Canvas* canvas, void* _model) { void desktop_view_pin_timeout_free(DesktopViewPinTimeout* instance) { view_free(instance->view); - xTimerDelete(instance->timer, portMAX_DELAY); + furi_timer_free(instance->timer); free(instance); } DesktopViewPinTimeout* desktop_view_pin_timeout_alloc(void) { DesktopViewPinTimeout* instance = malloc(sizeof(DesktopViewPinTimeout)); - instance->timer = xTimerCreate( - NULL, pdMS_TO_TICKS(1000), pdTRUE, instance, desktop_view_pin_timeout_timer_callback); + instance->timer = + furi_timer_alloc(desktop_view_pin_timeout_timer_callback, FuriTimerTypePeriodic, instance); instance->view = view_alloc(); view_allocate_model(instance->view, ViewModelTypeLockFree, sizeof(DesktopViewPinTimeoutModel)); @@ -101,7 +100,7 @@ void desktop_view_pin_timeout_start(DesktopViewPinTimeout* instance, uint32_t ti model->time_left = time_left; view_commit_model(instance->view, true); - xTimerStart(instance->timer, portMAX_DELAY); + furi_timer_start(instance->timer, 1000); } View* desktop_view_pin_timeout_get_view(DesktopViewPinTimeout* instance) { diff --git a/applications/services/dolphin/dolphin.c b/applications/services/dolphin/dolphin.c index b4f777db2..bef7c4a28 100644 --- a/applications/services/dolphin/dolphin.c +++ b/applications/services/dolphin/dolphin.c @@ -1,7 +1,6 @@ #include "dolphin/dolphin.h" #include "dolphin/helpers/dolphin_state.h" #include "dolphin_i.h" -#include "portmacro.h" #include "projdefs.h" #include #include @@ -45,8 +44,8 @@ void dolphin_flush(Dolphin* dolphin) { dolphin_event_send_wait(dolphin, &event); } -void dolphin_butthurt_timer_callback(TimerHandle_t xTimer) { - Dolphin* dolphin = pvTimerGetTimerID(xTimer); +void dolphin_butthurt_timer_callback(void* context) { + Dolphin* dolphin = context; furi_assert(dolphin); DolphinEvent event; @@ -54,8 +53,8 @@ void dolphin_butthurt_timer_callback(TimerHandle_t xTimer) { dolphin_event_send_async(dolphin, &event); } -void dolphin_flush_timer_callback(TimerHandle_t xTimer) { - Dolphin* dolphin = pvTimerGetTimerID(xTimer); +void dolphin_flush_timer_callback(void* context) { + Dolphin* dolphin = context; furi_assert(dolphin); DolphinEvent event; @@ -63,11 +62,11 @@ void dolphin_flush_timer_callback(TimerHandle_t xTimer) { dolphin_event_send_async(dolphin, &event); } -void dolphin_clear_limits_timer_callback(TimerHandle_t xTimer) { - Dolphin* dolphin = pvTimerGetTimerID(xTimer); +void dolphin_clear_limits_timer_callback(void* context) { + Dolphin* dolphin = context; furi_assert(dolphin); - xTimerChangePeriod(dolphin->clear_limits_timer, HOURS_IN_TICKS(24), portMAX_DELAY); + furi_timer_start(dolphin->clear_limits_timer, HOURS_IN_TICKS(24)); DolphinEvent event; event.type = DolphinEventTypeClearLimits; @@ -81,11 +80,11 @@ Dolphin* dolphin_alloc() { dolphin->event_queue = furi_message_queue_alloc(8, sizeof(DolphinEvent)); dolphin->pubsub = furi_pubsub_alloc(); dolphin->butthurt_timer = - xTimerCreate(NULL, HOURS_IN_TICKS(24), pdTRUE, dolphin, dolphin_butthurt_timer_callback); + furi_timer_alloc(dolphin_butthurt_timer_callback, FuriTimerTypePeriodic, dolphin); dolphin->flush_timer = - xTimerCreate(NULL, 30 * 1000, pdFALSE, dolphin, dolphin_flush_timer_callback); - dolphin->clear_limits_timer = xTimerCreate( - NULL, HOURS_IN_TICKS(24), pdTRUE, dolphin, dolphin_clear_limits_timer_callback); + furi_timer_alloc(dolphin_flush_timer_callback, FuriTimerTypeOnce, dolphin); + dolphin->clear_limits_timer = + furi_timer_alloc(dolphin_clear_limits_timer_callback, FuriTimerTypePeriodic, dolphin); return dolphin; } @@ -125,14 +124,14 @@ FuriPubSub* dolphin_get_pubsub(Dolphin* dolphin) { static void dolphin_update_clear_limits_timer_period(Dolphin* dolphin) { furi_assert(dolphin); - TickType_t now_ticks = xTaskGetTickCount(); - TickType_t timer_expires_at = xTimerGetExpiryTime(dolphin->clear_limits_timer); + uint32_t now_ticks = furi_get_tick(); + uint32_t timer_expires_at = furi_timer_get_expire_time(dolphin->clear_limits_timer); if((timer_expires_at - now_ticks) > HOURS_IN_TICKS(0.1)) { FuriHalRtcDateTime date; furi_hal_rtc_get_datetime(&date); - TickType_t now_time_in_ms = ((date.hour * 60 + date.minute) * 60 + date.second) * 1000; - TickType_t time_to_clear_limits = 0; + uint32_t now_time_in_ms = ((date.hour * 60 + date.minute) * 60 + date.second) * 1000; + uint32_t time_to_clear_limits = 0; if(date.hour < 5) { time_to_clear_limits = HOURS_IN_TICKS(5) - now_time_in_ms; @@ -140,7 +139,7 @@ static void dolphin_update_clear_limits_timer_period(Dolphin* dolphin) { time_to_clear_limits = HOURS_IN_TICKS(24 + 5) - now_time_in_ms; } - xTimerChangePeriod(dolphin->clear_limits_timer, time_to_clear_limits, portMAX_DELAY); + furi_timer_start(dolphin->clear_limits_timer, time_to_clear_limits); } } @@ -156,9 +155,9 @@ int32_t dolphin_srv(void* p) { furi_record_create(RECORD_DOLPHIN, dolphin); dolphin_state_load(dolphin->state); - xTimerReset(dolphin->butthurt_timer, portMAX_DELAY); + furi_timer_restart(dolphin->butthurt_timer, HOURS_IN_TICKS(2 * 24)); dolphin_update_clear_limits_timer_period(dolphin); - xTimerReset(dolphin->clear_limits_timer, portMAX_DELAY); + furi_timer_restart(dolphin->clear_limits_timer, HOURS_IN_TICKS(24)); DolphinEvent event; while(1) { @@ -168,8 +167,8 @@ int32_t dolphin_srv(void* p) { dolphin_state_on_deed(dolphin->state, event.deed); DolphinPubsubEvent event = DolphinPubsubEventUpdate; furi_pubsub_publish(dolphin->pubsub, &event); - xTimerReset(dolphin->butthurt_timer, portMAX_DELAY); - xTimerReset(dolphin->flush_timer, portMAX_DELAY); + furi_timer_restart(dolphin->butthurt_timer, HOURS_IN_TICKS(2 * 24)); + furi_timer_restart(dolphin->flush_timer, 30 * 1000); } else if(event.type == DolphinEventTypeStats) { event.stats->icounter = dolphin->state->data.icounter; event.stats->butthurt = dolphin->state->data.butthurt; diff --git a/applications/services/dolphin/dolphin_i.h b/applications/services/dolphin/dolphin_i.h index ceeff1e1a..2d716c181 100644 --- a/applications/services/dolphin/dolphin_i.h +++ b/applications/services/dolphin/dolphin_i.h @@ -30,9 +30,9 @@ struct Dolphin { // Queue FuriMessageQueue* event_queue; FuriPubSub* pubsub; - TimerHandle_t butthurt_timer; - TimerHandle_t flush_timer; - TimerHandle_t clear_limits_timer; + FuriTimer* butthurt_timer; + FuriTimer* flush_timer; + FuriTimer* clear_limits_timer; }; Dolphin* dolphin_alloc(); diff --git a/applications/services/gui/canvas.c b/applications/services/gui/canvas.c index caede740d..9aa5dd054 100644 --- a/applications/services/gui/canvas.c +++ b/applications/services/gui/canvas.c @@ -143,7 +143,7 @@ void canvas_set_font(Canvas* canvas, Font font) { } else if(font == FontBatteryPercent) { u8g2_SetFont(&canvas->fb, u8g2_font_5x7_tf); //u8g2_font_micro_tr); } else { - furi_crash(NULL); + furi_crash(); } } @@ -183,7 +183,7 @@ void canvas_draw_str_aligned( x -= (u8g2_GetStrWidth(&canvas->fb, str) / 2); break; default: - furi_crash(NULL); + furi_crash(); break; } @@ -197,7 +197,7 @@ void canvas_draw_str_aligned( y += (u8g2_GetAscent(&canvas->fb) / 2); break; default: - furi_crash(NULL); + furi_crash(); break; } @@ -555,7 +555,7 @@ void canvas_set_orientation(Canvas* canvas, CanvasOrientation orientation) { rotate_cb = U8G2_R1; break; default: - furi_assert(0); + furi_crash(); } if(need_swap) FURI_SWAP(canvas->width, canvas->height); diff --git a/applications/services/gui/elements.c b/applications/services/gui/elements.c index bce72551b..f35c36aed 100644 --- a/applications/services/gui/elements.c +++ b/applications/services/gui/elements.c @@ -232,7 +232,7 @@ static size_t } else if(horizontal == AlignRight) { px_left = x; } else { - furi_assert(0); + furi_crash(); } if(len_px > px_left) { diff --git a/applications/services/gui/icon_animation.c b/applications/services/gui/icon_animation.c index b63d233f3..a39ef2e25 100644 --- a/applications/services/gui/icon_animation.c +++ b/applications/services/gui/icon_animation.c @@ -15,7 +15,6 @@ IconAnimation* icon_animation_alloc(const Icon* icon) { void icon_animation_free(IconAnimation* instance) { furi_assert(instance); icon_animation_stop(instance); - while(xTimerIsTimerActive(instance->timer) == pdTRUE) furi_delay_tick(1); furi_timer_free(instance->timer); free(instance); } @@ -67,10 +66,9 @@ void icon_animation_start(IconAnimation* instance) { instance->animating = true; furi_assert(instance->icon->frame_rate); furi_check( - xTimerChangePeriod( + furi_timer_start( instance->timer, - (furi_kernel_get_tick_frequency() / instance->icon->frame_rate), - portMAX_DELAY) == pdPASS); + (furi_kernel_get_tick_frequency() / instance->icon->frame_rate)) == FuriStatusOk); } } @@ -78,7 +76,7 @@ void icon_animation_stop(IconAnimation* instance) { furi_assert(instance); if(instance->animating) { instance->animating = false; - furi_check(xTimerStop(instance->timer, portMAX_DELAY) == pdPASS); + furi_timer_stop(instance->timer); instance->frame = 0; } } diff --git a/applications/services/gui/modules/byte_input.c b/applications/services/gui/modules/byte_input.c index 5bf387b26..dd13e3aad 100644 --- a/applications/services/gui/modules/byte_input.c +++ b/applications/services/gui/modules/byte_input.c @@ -79,7 +79,7 @@ static uint8_t byte_input_get_row_size(uint8_t row_index) { row_size = COUNT_OF(keyboard_keys_row_2); break; default: - furi_crash(NULL); + furi_crash(); } return row_size; @@ -102,7 +102,7 @@ static const ByteInputKey* byte_input_get_row(uint8_t row_index) { row = keyboard_keys_row_2; break; default: - furi_crash(NULL); + furi_crash(); } return row; diff --git a/applications/services/gui/modules/popup.c b/applications/services/gui/modules/popup.c index d75abb95f..520efceef 100644 --- a/applications/services/gui/modules/popup.c +++ b/applications/services/gui/modules/popup.c @@ -98,7 +98,7 @@ void popup_start_timer(void* context) { if(timer_period == 0) timer_period = 1; if(furi_timer_start(popup->timer, timer_period) != FuriStatusOk) { - furi_assert(0); + furi_crash(); }; } } diff --git a/applications/services/gui/modules/text_input.c b/applications/services/gui/modules/text_input.c index ab5bc5b41..926a74910 100644 --- a/applications/services/gui/modules/text_input.c +++ b/applications/services/gui/modules/text_input.c @@ -105,7 +105,7 @@ static uint8_t get_row_size(uint8_t row_index) { row_size = COUNT_OF(keyboard_keys_row_3); break; default: - furi_crash(NULL); + furi_crash(); } return row_size; @@ -125,7 +125,7 @@ static const TextInputKey* get_row(uint8_t row_index) { row = keyboard_keys_row_3; break; default: - furi_crash(NULL); + furi_crash(); } return row; diff --git a/applications/services/gui/view.c b/applications/services/gui/view.c index 07ae072a1..316f5c612 100644 --- a/applications/services/gui/view.c +++ b/applications/services/gui/view.c @@ -82,7 +82,7 @@ void view_allocate_model(View* view, ViewModelType type, size_t size) { model->data = malloc(size); view->model = model; } else { - furi_crash(NULL); + furi_crash(); } } @@ -99,7 +99,7 @@ void view_free_model(View* view) { free(model); view->model = NULL; } else { - furi_crash(NULL); + furi_crash(); } } diff --git a/applications/services/gui/view_dispatcher.c b/applications/services/gui/view_dispatcher.c index 0119abc20..87b07a87c 100644 --- a/applications/services/gui/view_dispatcher.c +++ b/applications/services/gui/view_dispatcher.c @@ -207,7 +207,7 @@ void view_dispatcher_attach_to_gui( } else if(type == ViewDispatcherTypeFullscreen) { gui_add_view_port(gui, view_dispatcher->view_port, GuiLayerFullscreen); } else { - furi_check(NULL); + furi_crash(); } view_dispatcher->gui = gui; } diff --git a/applications/services/input/input.c b/applications/services/input/input.c index 8da0a3400..216aa39b2 100644 --- a/applications/services/input/input.c +++ b/applications/services/input/input.c @@ -6,20 +6,6 @@ static Input* input = NULL; -inline static void input_timer_start(FuriTimer* timer_id, uint32_t ticks) { - TimerHandle_t hTimer = (TimerHandle_t)timer_id; - furi_check(xTimerChangePeriod(hTimer, ticks, portMAX_DELAY) == pdPASS); -} - -inline static void input_timer_stop(FuriTimer* timer_id) { - TimerHandle_t hTimer = (TimerHandle_t)timer_id; - furi_check(xTimerStop(hTimer, portMAX_DELAY) == pdPASS); - // xTimerStop is not actually stopping timer, - // Instead it places stop event into timer queue - // This code ensures that timer is stopped - while(xTimerIsTimerActive(hTimer) == pdTRUE) furi_delay_tick(1); -} - void input_press_timer_callback(void* arg) { InputPinState* input_pin = arg; InputEvent event; @@ -123,10 +109,12 @@ int32_t input_srv(void* p) { input->counter++; input->pin_states[i].counter = input->counter; event.sequence_counter = input->pin_states[i].counter; - input_timer_start(input->pin_states[i].press_timer, INPUT_PRESS_TICKS); + furi_timer_start(input->pin_states[i].press_timer, INPUT_PRESS_TICKS); } else { event.sequence_counter = input->pin_states[i].counter; - input_timer_stop(input->pin_states[i].press_timer); + furi_timer_stop(input->pin_states[i].press_timer); + while(furi_timer_is_running(input->pin_states[i].press_timer)) + furi_delay_tick(1); if(input->pin_states[i].press_counter < INPUT_LONG_PRESS_COUNTS) { event.type = InputTypeShort; furi_pubsub_publish(input->event_pubsub, &event); diff --git a/applications/services/loader/loader.c b/applications/services/loader/loader.c index a08272731..99d2b60d5 100644 --- a/applications/services/loader/loader.c +++ b/applications/services/loader/loader.c @@ -179,7 +179,7 @@ static FlipperInternalApplication const* loader_find_application_by_name_in_list const FlipperInternalApplication* list, const uint32_t n_apps) { for(size_t i = 0; i < n_apps; i++) { - if(strcmp(name, list[i].name) == 0) { + if((strcmp(name, list[i].name) == 0) || (strcmp(name, list[i].appid) == 0)) { return &list[i]; } } diff --git a/applications/services/loader/loader.h b/applications/services/loader/loader.h index ded0fea86..63da7d3ca 100644 --- a/applications/services/loader/loader.h +++ b/applications/services/loader/loader.h @@ -31,7 +31,7 @@ typedef struct { /** * @brief Start application * @param[in] instance loader instance - * @param[in] name application name + * @param[in] name application name or id * @param[in] args application arguments * @param[out] error_message detailed error message, can be NULL * @return LoaderStatus @@ -42,7 +42,7 @@ LoaderStatus /** * @brief Start application with GUI error message * @param[in] instance loader instance - * @param[in] name application name + * @param[in] name application name or id * @param[in] args application arguments * @return LoaderStatus */ diff --git a/applications/services/rpc/rpc.c b/applications/services/rpc/rpc.c index 43ebd2a56..50c4b3608 100644 --- a/applications/services/rpc/rpc.c +++ b/applications/services/rpc/rpc.c @@ -6,7 +6,6 @@ #include #include -#include #include @@ -162,7 +161,7 @@ void rpc_session_set_terminated_callback( * odd: client sends close request and sends command after. */ size_t - rpc_session_feed(RpcSession* session, uint8_t* encoded_bytes, size_t size, TickType_t timeout) { + rpc_session_feed(RpcSession* session, uint8_t* encoded_bytes, size_t size, uint32_t timeout) { furi_assert(session); furi_assert(encoded_bytes); @@ -478,12 +477,15 @@ void rpc_send_and_release(RpcSession* session, PB_Main* message) { } void rpc_send_and_release_empty(RpcSession* session, uint32_t command_id, PB_CommandStatus status) { + furi_assert(session); + PB_Main message = { .command_id = command_id, .command_status = status, .has_next = false, .which_content = PB_Main_empty_tag, }; + rpc_send_and_release(session, &message); pb_release(&PB_Main_msg, &message); } diff --git a/applications/services/rpc/rpc.h b/applications/services/rpc/rpc.h index d11fdc162..863bca355 100644 --- a/applications/services/rpc/rpc.h +++ b/applications/services/rpc/rpc.h @@ -124,7 +124,7 @@ void rpc_session_set_terminated_callback( * * @return actually consumed bytes */ -size_t rpc_session_feed(RpcSession* session, uint8_t* buffer, size_t size, TickType_t timeout); +size_t rpc_session_feed(RpcSession* session, uint8_t* buffer, size_t size, uint32_t timeout); /** Get available size of RPC buffer * diff --git a/applications/services/rpc/rpc_app.c b/applications/services/rpc/rpc_app.c index bf44ed2de..9af652dae 100644 --- a/applications/services/rpc/rpc_app.c +++ b/applications/services/rpc/rpc_app.c @@ -10,49 +10,85 @@ struct RpcAppSystem { RpcSession* session; - RpcAppSystemCallback app_callback; - void* app_context; + RpcAppSystemCallback callback; + void* callback_context; - RpcAppSystemDataExchangeCallback data_exchange_callback; - void* data_exchange_context; + uint32_t error_code; + char* error_text; - PB_Main* state_msg; - PB_Main* error_msg; - - uint32_t last_id; - char* last_data; + uint32_t last_command_id; + RpcAppSystemEventType last_event_type; }; #define RPC_SYSTEM_APP_TEMP_ARGS_SIZE 16 +static void rpc_system_app_send_state_response( + RpcAppSystem* rpc_app, + PB_App_AppState state, + const char* name) { + PB_Main* response = malloc(sizeof(PB_Main)); + + response->which_content = PB_Main_app_state_response_tag; + response->content.app_state_response.state = state; + + FURI_LOG_D(TAG, "%s", name); + rpc_send(rpc_app->session, response); + + free(response); +} + +static void rpc_system_app_send_error_response( + RpcAppSystem* rpc_app, + uint32_t command_id, + PB_CommandStatus status, + const char* name) { + // Not describing all possible errors as only APP_NOT_RUNNING is used + const char* status_str = status == PB_CommandStatus_ERROR_APP_NOT_RUNNING ? "APP_NOT_RUNNING" : + "UNKNOWN"; + FURI_LOG_E(TAG, "%s: %s, id %lu, status: %d", name, status_str, command_id, status); + rpc_send_and_release_empty(rpc_app->session, command_id, status); +} + +static void rpc_system_app_set_last_command( + RpcAppSystem* rpc_app, + uint32_t command_id, + const RpcAppSystemEvent* event) { + furi_assert(rpc_app->last_command_id == 0); + furi_assert(rpc_app->last_event_type == RpcAppEventTypeInvalid); + + rpc_app->last_command_id = command_id; + rpc_app->last_event_type = event->type; +} + static void rpc_system_app_start_process(const PB_Main* request, void* context) { furi_assert(request); - furi_assert(context); - furi_assert(request->which_content == PB_Main_app_start_request_tag); - RpcAppSystem* rpc_app = context; - RpcSession* session = rpc_app->session; - rpc_system_app_error_reset(rpc_app); - furi_assert(session); - char args_temp[RPC_SYSTEM_APP_TEMP_ARGS_SIZE]; - furi_assert(!rpc_app->last_id); - furi_assert(!rpc_app->last_data); + RpcAppSystem* rpc_app = context; + furi_assert(rpc_app); + furi_assert(rpc_app->last_command_id == 0); + furi_assert(rpc_app->last_event_type == RpcAppEventTypeInvalid); FURI_LOG_D(TAG, "StartProcess: id %lu", request->command_id); - PB_CommandStatus result; - Loader* loader = furi_record_open(RECORD_LOADER); const char* app_name = request->content.app_start_request.name; + + PB_CommandStatus result; + if(app_name) { + rpc_system_app_error_reset(rpc_app); + + char app_args_temp[RPC_SYSTEM_APP_TEMP_ARGS_SIZE]; const char* app_args = request->content.app_start_request.args; + if(app_args && strcmp(app_args, "RPC") == 0) { // If app is being started in RPC mode - pass RPC context via args string - snprintf(args_temp, RPC_SYSTEM_APP_TEMP_ARGS_SIZE, "RPC %08lX", (uint32_t)rpc_app); - app_args = args_temp; + snprintf(app_args_temp, RPC_SYSTEM_APP_TEMP_ARGS_SIZE, "RPC %08lX", (uint32_t)rpc_app); + app_args = app_args_temp; } - LoaderStatus status = loader_start(loader, app_name, app_args, NULL); + + const LoaderStatus status = loader_start(loader, app_name, app_args, NULL); if(status == LoaderStatusErrorAppStarted) { result = PB_CommandStatus_ERROR_APP_SYSTEM_LOCKED; } else if(status == LoaderStatusErrorInternal) { @@ -62,7 +98,7 @@ static void rpc_system_app_start_process(const PB_Main* request, void* context) } else if(status == LoaderStatusOk) { result = PB_CommandStatus_OK; } else { - furi_crash(NULL); + furi_crash(); } } else { result = PB_CommandStatus_ERROR_INVALID_PARAMETERS; @@ -71,266 +107,271 @@ static void rpc_system_app_start_process(const PB_Main* request, void* context) furi_record_close(RECORD_LOADER); FURI_LOG_D(TAG, "StartProcess: response id %lu, result %d", request->command_id, result); - rpc_send_and_release_empty(session, request->command_id, result); + rpc_send_and_release_empty(rpc_app->session, request->command_id, result); } static void rpc_system_app_lock_status_process(const PB_Main* request, void* context) { furi_assert(request); - furi_assert(context); - furi_assert(request->which_content == PB_Main_app_lock_status_request_tag); + RpcAppSystem* rpc_app = context; + furi_assert(rpc_app); + rpc_system_app_error_reset(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); FURI_LOG_D(TAG, "LockStatus"); + PB_Main* response = malloc(sizeof(PB_Main)); + + response->command_id = request->command_id; + response->which_content = PB_Main_app_lock_status_response_tag; + Loader* loader = furi_record_open(RECORD_LOADER); - - PB_Main response = { - .has_next = false, - .command_status = PB_CommandStatus_OK, - .command_id = request->command_id, - .which_content = PB_Main_app_lock_status_response_tag, - }; - - response.content.app_lock_status_response.locked = loader_is_locked(loader); - + response->content.app_lock_status_response.locked = loader_is_locked(loader); furi_record_close(RECORD_LOADER); FURI_LOG_D(TAG, "LockStatus: response"); - rpc_send_and_release(session, &response); - pb_release(&PB_Main_msg, &response); + rpc_send_and_release(rpc_app->session, response); + + free(response); } static void rpc_system_app_exit_request(const PB_Main* request, void* context) { furi_assert(request); - furi_assert(context); - furi_assert(request->which_content == PB_Main_app_exit_request_tag); + RpcAppSystem* rpc_app = context; - rpc_system_app_error_reset(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); + furi_assert(rpc_app); - PB_CommandStatus status; - - if(rpc_app->app_callback) { + if(rpc_app->callback) { FURI_LOG_D(TAG, "ExitRequest: id %lu", request->command_id); - furi_assert(!rpc_app->last_id); - furi_assert(!rpc_app->last_data); - rpc_app->last_id = request->command_id; - rpc_app->app_callback(RpcAppEventAppExit, rpc_app->app_context); + + const RpcAppSystemEvent event = { + .type = RpcAppEventTypeAppExit, + .data = + { + .type = RpcAppSystemEventDataTypeNone, + {0}, + }, + }; + + rpc_system_app_error_reset(rpc_app); + rpc_system_app_set_last_command(rpc_app, request->command_id, &event); + + rpc_app->callback(&event, rpc_app->callback_context); + } else { - status = PB_CommandStatus_ERROR_APP_NOT_RUNNING; - FURI_LOG_E( - TAG, "ExitRequest: APP_NOT_RUNNING, id %lu, status: %d", request->command_id, status); - rpc_send_and_release_empty(session, request->command_id, status); + rpc_system_app_send_error_response( + rpc_app, request->command_id, PB_CommandStatus_ERROR_APP_NOT_RUNNING, "ExitRequest"); } } static void rpc_system_app_load_file(const PB_Main* request, void* context) { furi_assert(request); - furi_assert(context); - furi_assert(request->which_content == PB_Main_app_load_file_request_tag); - RpcAppSystem* rpc_app = context; - rpc_system_app_error_reset(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); - PB_CommandStatus status; - if(rpc_app->app_callback) { + RpcAppSystem* rpc_app = context; + furi_assert(rpc_app); + + if(rpc_app->callback) { FURI_LOG_D(TAG, "LoadFile: id %lu", request->command_id); - furi_assert(!rpc_app->last_id); - furi_assert(!rpc_app->last_data); - rpc_app->last_id = request->command_id; - rpc_app->last_data = strdup(request->content.app_load_file_request.path); - rpc_app->app_callback(RpcAppEventLoadFile, rpc_app->app_context); + + const RpcAppSystemEvent event = { + .type = RpcAppEventTypeLoadFile, + .data = + { + .type = RpcAppSystemEventDataTypeString, + .string = request->content.app_load_file_request.path, + }, + }; + + rpc_system_app_error_reset(rpc_app); + rpc_system_app_set_last_command(rpc_app, request->command_id, &event); + + rpc_app->callback(&event, rpc_app->callback_context); + } else { - status = PB_CommandStatus_ERROR_APP_NOT_RUNNING; - FURI_LOG_E( - TAG, "LoadFile: APP_NOT_RUNNING, id %lu, status: %d", request->command_id, status); - rpc_send_and_release_empty(session, request->command_id, status); + rpc_system_app_send_error_response( + rpc_app, request->command_id, PB_CommandStatus_ERROR_APP_NOT_RUNNING, "LoadFile"); } } static void rpc_system_app_button_press(const PB_Main* request, void* context) { furi_assert(request); - furi_assert(context); - furi_assert(request->which_content == PB_Main_app_button_press_request_tag); - RpcAppSystem* rpc_app = context; - rpc_system_app_error_reset(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); - PB_CommandStatus status; - if(rpc_app->app_callback) { + RpcAppSystem* rpc_app = context; + furi_assert(rpc_app); + + if(rpc_app->callback) { FURI_LOG_D(TAG, "ButtonPress"); - furi_assert(!rpc_app->last_id); - furi_assert(!rpc_app->last_data); - rpc_app->last_id = request->command_id; - rpc_app->last_data = strdup(request->content.app_button_press_request.args); - rpc_app->app_callback(RpcAppEventButtonPress, rpc_app->app_context); + + RpcAppSystemEvent event; + event.type = RpcAppEventTypeButtonPress; + + if(strlen(request->content.app_button_press_request.args) != 0) { + event.data.type = RpcAppSystemEventDataTypeString; + event.data.string = request->content.app_button_press_request.args; + } else { + event.data.type = RpcAppSystemEventDataTypeInt32; + event.data.i32 = request->content.app_button_press_request.index; + } + + rpc_system_app_error_reset(rpc_app); + rpc_system_app_set_last_command(rpc_app, request->command_id, &event); + + rpc_app->callback(&event, rpc_app->callback_context); + } else { - status = PB_CommandStatus_ERROR_APP_NOT_RUNNING; - FURI_LOG_E( - TAG, "ButtonPress: APP_NOT_RUNNING, id %lu, status: %d", request->command_id, status); - rpc_send_and_release_empty(session, request->command_id, status); + rpc_system_app_send_error_response( + rpc_app, request->command_id, PB_CommandStatus_ERROR_APP_NOT_RUNNING, "ButtonPress"); } } static void rpc_system_app_button_release(const PB_Main* request, void* context) { furi_assert(request); furi_assert(request->which_content == PB_Main_app_button_release_request_tag); - furi_assert(context); RpcAppSystem* rpc_app = context; - rpc_system_app_error_reset(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); + furi_assert(rpc_app); - PB_CommandStatus status; - if(rpc_app->app_callback) { + if(rpc_app->callback) { FURI_LOG_D(TAG, "ButtonRelease"); - furi_assert(!rpc_app->last_id); - furi_assert(!rpc_app->last_data); - rpc_app->last_id = request->command_id; - rpc_app->app_callback(RpcAppEventButtonRelease, rpc_app->app_context); + + const RpcAppSystemEvent event = { + .type = RpcAppEventTypeButtonRelease, + .data = + { + .type = RpcAppSystemEventDataTypeNone, + {0}, + }, + }; + + rpc_system_app_error_reset(rpc_app); + rpc_system_app_set_last_command(rpc_app, request->command_id, &event); + + rpc_app->callback(&event, rpc_app->callback_context); + } else { - status = PB_CommandStatus_ERROR_APP_NOT_RUNNING; - FURI_LOG_E( - TAG, "ButtonRelease: APP_NOT_RUNNING, id %lu, status: %d", request->command_id, status); - rpc_send_and_release_empty(session, request->command_id, status); + rpc_system_app_send_error_response( + rpc_app, request->command_id, PB_CommandStatus_ERROR_APP_NOT_RUNNING, "ButtonRelease"); } } static void rpc_system_app_get_error_process(const PB_Main* request, void* context) { furi_assert(request); furi_assert(request->which_content == PB_Main_app_get_error_request_tag); - furi_assert(context); RpcAppSystem* rpc_app = context; - RpcSession* session = rpc_app->session; - furi_assert(session); + furi_assert(rpc_app); - rpc_app->error_msg->command_id = request->command_id; + PB_Main* response = malloc(sizeof(PB_Main)); + + response->command_id = request->command_id; + response->which_content = PB_Main_app_get_error_response_tag; + response->content.app_get_error_response.code = rpc_app->error_code; + response->content.app_get_error_response.text = rpc_app->error_text; FURI_LOG_D(TAG, "GetError"); - rpc_send(session, rpc_app->error_msg); + rpc_send(rpc_app->session, response); + + free(response); } static void rpc_system_app_data_exchange_process(const PB_Main* request, void* context) { furi_assert(request); furi_assert(request->which_content == PB_Main_app_data_exchange_request_tag); - furi_assert(context); RpcAppSystem* rpc_app = context; - rpc_system_app_error_reset(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); + furi_assert(rpc_app); - PB_CommandStatus command_status; - pb_bytes_array_t* data = request->content.app_data_exchange_request.data; + if(rpc_app->callback) { + FURI_LOG_D(TAG, "DataExchange"); - if(rpc_app->data_exchange_callback) { - uint8_t* data_bytes = NULL; - size_t data_size = 0; - if(data) { - data_bytes = data->bytes; - data_size = data->size; - } - rpc_app->data_exchange_callback(data_bytes, data_size, rpc_app->data_exchange_context); - command_status = PB_CommandStatus_OK; + const pb_bytes_array_t* data = request->content.app_data_exchange_request.data; + + const RpcAppSystemEvent event = { + .type = RpcAppEventTypeDataExchange, + .data = + { + .type = RpcAppSystemEventDataTypeBytes, + .bytes = + { + .ptr = data ? data->bytes : NULL, + .size = data ? data->size : 0, + }, + }, + }; + + rpc_system_app_error_reset(rpc_app); + rpc_system_app_set_last_command(rpc_app, request->command_id, &event); + + rpc_app->callback(&event, rpc_app->callback_context); } else { - command_status = PB_CommandStatus_ERROR_APP_CMD_ERROR; + rpc_system_app_send_error_response( + rpc_app, request->command_id, PB_CommandStatus_ERROR_APP_NOT_RUNNING, "DataExchange"); } - - FURI_LOG_D(TAG, "DataExchange"); - rpc_send_and_release_empty(session, request->command_id, command_status); } void rpc_system_app_send_started(RpcAppSystem* rpc_app) { furi_assert(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); - - rpc_app->state_msg->content.app_state_response.state = PB_App_AppState_APP_STARTED; - - FURI_LOG_D(TAG, "SendStarted"); - rpc_send(session, rpc_app->state_msg); + rpc_system_app_send_state_response(rpc_app, PB_App_AppState_APP_STARTED, "SendStarted"); } void rpc_system_app_send_exited(RpcAppSystem* rpc_app) { furi_assert(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); - - rpc_app->state_msg->content.app_state_response.state = PB_App_AppState_APP_CLOSED; - - FURI_LOG_D(TAG, "SendExit"); - rpc_send(session, rpc_app->state_msg); + rpc_system_app_send_state_response(rpc_app, PB_App_AppState_APP_CLOSED, "SendExit"); } -const char* rpc_system_app_get_data(RpcAppSystem* rpc_app) { +void rpc_system_app_confirm(RpcAppSystem* rpc_app, bool result) { furi_assert(rpc_app); - furi_assert(rpc_app->last_data); - return rpc_app->last_data; -} + furi_assert(rpc_app->last_command_id != 0); + /* Ensure that only commands of these types can be confirmed */ + furi_assert( + rpc_app->last_event_type == RpcAppEventTypeAppExit || + rpc_app->last_event_type == RpcAppEventTypeLoadFile || + rpc_app->last_event_type == RpcAppEventTypeButtonPress || + rpc_app->last_event_type == RpcAppEventTypeButtonRelease || + rpc_app->last_event_type == RpcAppEventTypeDataExchange); -void rpc_system_app_confirm(RpcAppSystem* rpc_app, RpcAppSystemEvent event, bool result) { - furi_assert(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); - furi_assert(rpc_app->last_id); + const uint32_t last_command_id = rpc_app->last_command_id; + const RpcAppSystemEventType last_event_type = rpc_app->last_event_type; - PB_CommandStatus status = result ? PB_CommandStatus_OK : PB_CommandStatus_ERROR_APP_CMD_ERROR; + rpc_app->last_command_id = 0; + rpc_app->last_event_type = RpcAppEventTypeInvalid; - uint32_t last_id = 0; - switch(event) { - case RpcAppEventAppExit: - case RpcAppEventLoadFile: - case RpcAppEventButtonPress: - case RpcAppEventButtonRelease: - last_id = rpc_app->last_id; - rpc_app->last_id = 0; - if(rpc_app->last_data) { - free(rpc_app->last_data); - rpc_app->last_data = NULL; - } - FURI_LOG_D(TAG, "AppConfirm: event %d last_id %lu status %d", event, last_id, status); - rpc_send_and_release_empty(session, last_id, status); - break; - default: - furi_crash("RPC App state programming Error"); - break; - } + const PB_CommandStatus status = result ? PB_CommandStatus_OK : + PB_CommandStatus_ERROR_APP_CMD_ERROR; + FURI_LOG_D( + TAG, + "AppConfirm: event %d last_id %lu status %d", + last_event_type, + last_command_id, + status); + + rpc_send_and_release_empty(rpc_app->session, last_command_id, status); } void rpc_system_app_set_callback(RpcAppSystem* rpc_app, RpcAppSystemCallback callback, void* ctx) { furi_assert(rpc_app); - rpc_app->app_callback = callback; - rpc_app->app_context = ctx; + rpc_app->callback = callback; + rpc_app->callback_context = ctx; } void rpc_system_app_set_error_code(RpcAppSystem* rpc_app, uint32_t error_code) { furi_assert(rpc_app); - PB_App_GetErrorResponse* content = &rpc_app->error_msg->content.app_get_error_response; - content->code = error_code; + rpc_app->error_code = error_code; } void rpc_system_app_set_error_text(RpcAppSystem* rpc_app, const char* error_text) { furi_assert(rpc_app); - PB_App_GetErrorResponse* content = &rpc_app->error_msg->content.app_get_error_response; - if(content->text) { - free(content->text); + if(rpc_app->error_text) { + free(rpc_app->error_text); } - content->text = error_text ? strdup(error_text) : NULL; + rpc_app->error_text = error_text ? strdup(error_text) : NULL; } void rpc_system_app_error_reset(RpcAppSystem* rpc_app) { @@ -340,29 +381,13 @@ void rpc_system_app_error_reset(RpcAppSystem* rpc_app) { rpc_system_app_set_error_text(rpc_app, NULL); } -void rpc_system_app_set_data_exchange_callback( - RpcAppSystem* rpc_app, - RpcAppSystemDataExchangeCallback callback, - void* ctx) { - furi_assert(rpc_app); - - rpc_app->data_exchange_callback = callback; - rpc_app->data_exchange_context = ctx; -} - void rpc_system_app_exchange_data(RpcAppSystem* rpc_app, const uint8_t* data, size_t data_size) { furi_assert(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); - PB_Main message = { - .command_id = 0, - .command_status = PB_CommandStatus_OK, - .has_next = false, - .which_content = PB_Main_app_data_exchange_request_tag, - }; + PB_Main* request = malloc(sizeof(PB_Main)); - PB_App_DataExchangeRequest* content = &message.content.app_data_exchange_request; + request->which_content = PB_Main_app_data_exchange_request_tag; + PB_App_DataExchangeRequest* content = &request->content.app_data_exchange_request; if(data && data_size) { content->data = malloc(PB_BYTES_ARRAY_T_ALLOCSIZE(data_size)); @@ -372,7 +397,9 @@ void rpc_system_app_exchange_data(RpcAppSystem* rpc_app, const uint8_t* data, si content->data = NULL; } - rpc_send_and_release(session, &message); + rpc_send_and_release(rpc_app->session, request); + + free(request); } void* rpc_system_app_alloc(RpcSession* session) { @@ -381,18 +408,6 @@ void* rpc_system_app_alloc(RpcSession* session) { RpcAppSystem* rpc_app = malloc(sizeof(RpcAppSystem)); rpc_app->session = session; - // App exit message - rpc_app->state_msg = malloc(sizeof(PB_Main)); - rpc_app->state_msg->which_content = PB_Main_app_state_response_tag; - rpc_app->state_msg->command_status = PB_CommandStatus_OK; - - // App error message - rpc_app->error_msg = malloc(sizeof(PB_Main)); - rpc_app->error_msg->which_content = PB_Main_app_get_error_response_tag; - rpc_app->error_msg->command_status = PB_CommandStatus_OK; - rpc_app->error_msg->content.app_get_error_response.code = 0; - rpc_app->error_msg->content.app_get_error_response.text = NULL; - RpcHandler rpc_handler = { .message_handler = NULL, .decode_submessage = NULL, @@ -429,24 +444,24 @@ void* rpc_system_app_alloc(RpcSession* session) { void rpc_system_app_free(void* context) { RpcAppSystem* rpc_app = context; furi_assert(rpc_app); - RpcSession* session = rpc_app->session; - furi_assert(session); + furi_assert(rpc_app->session); - if(rpc_app->app_callback) { - rpc_app->app_callback(RpcAppEventSessionClose, rpc_app->app_context); + if(rpc_app->callback) { + const RpcAppSystemEvent event = { + .type = RpcAppEventTypeSessionClose, + .data = + { + .type = RpcAppSystemEventDataTypeNone, + {0}, + }, + }; + + rpc_app->callback(&event, rpc_app->callback_context); } - while(rpc_app->app_callback) { + while(rpc_app->callback) { furi_delay_tick(1); } - furi_assert(!rpc_app->data_exchange_callback); - - if(rpc_app->last_data) free(rpc_app->last_data); - - pb_release(&PB_Main_msg, rpc_app->error_msg); - - free(rpc_app->error_msg); - free(rpc_app->state_msg); free(rpc_app); } diff --git a/applications/services/rpc/rpc_app.h b/applications/services/rpc/rpc_app.h index d5c6fee96..4ee5a24d3 100644 --- a/applications/services/rpc/rpc_app.h +++ b/applications/services/rpc/rpc_app.h @@ -1,45 +1,213 @@ +/** + * @file rpc_app.h + * @brief Application RPC subsystem interface. + * + * The application RPC subsystem provides facilities for interacting with applications, + * such as starting/stopping, passing parameters, sending commands and exchanging arbitrary data. + * + * All commands are handled asynchronously via a user-settable callback. + * + * For a complete description of message types handled in this subsystem, + * see https://github.com/flipperdevices/flipperzero-protobuf/blob/dev/application.proto + */ #pragma once + #include "rpc.h" #ifdef __cplusplus extern "C" { #endif +/** + * @brief Enumeration of possible event data types. + */ typedef enum { - RpcAppEventSessionClose, - RpcAppEventAppExit, - RpcAppEventLoadFile, - RpcAppEventButtonPress, - RpcAppEventButtonRelease, + RpcAppSystemEventDataTypeNone, /**< No data is provided by the event. */ + RpcAppSystemEventDataTypeString, /**< Event data contains a zero-terminated string. */ + RpcAppSystemEventDataTypeInt32, /**< Event data contains a signed 32-bit integer. */ + RpcAppSystemEventDataTypeBytes, /**< Event data contains zero or more bytes. */ +} RpcAppSystemEventDataType; + +/** + * @brief Event data structure, containing the type and associated data. + * + * All below fields except for type are valid only if the respective type is set. + */ +typedef struct { + RpcAppSystemEventDataType + type; /**< Type of the data. The meaning of other fields depends on this one. */ + union { + const char* string; /**< Pointer to a zero-terminated character string. */ + int32_t i32; /**< Signed 32-bit integer value. */ + struct { + const uint8_t* ptr; /**< Pointer to the byte array data. */ + size_t size; /**< Size of the byte array, in bytes. */ + } bytes; /**< Byte array of arbitrary length. */ + }; +} RpcAppSystemEventData; + +/** + * @brief Enumeration of possible event types. + */ +typedef enum { + /** + * @brief Denotes an invalid state. + * + * An event of this type shall never be passed into the callback. + */ + RpcAppEventTypeInvalid, + /** + * @brief The client side has closed the session. + * + * After receiving this event, the RPC context is no more valid. + */ + RpcAppEventTypeSessionClose, + /** + * @brief The client has requested the application to exit. + * + * The application must exit after receiving this command. + */ + RpcAppEventTypeAppExit, + /** + * @brief The client has requested the application to load a file. + * + * This command's meaning is application-specific, i.e. the application might or + * might not require additional commands after loading a file to do anything useful. + */ + RpcAppEventTypeLoadFile, + /** + * @brief The client has informed the application that a button has been pressed. + * + * This command's meaning is application-specific, e.g. to select a part of the + * previously loaded file or to invoke a particular function within the application. + */ + RpcAppEventTypeButtonPress, + /** + * @brief The client has informed the application that a button has been released. + * + * This command's meaning is application-specific, e.g. to cease + * all activities to be conducted while a button is being pressed. + */ + RpcAppEventTypeButtonRelease, + /** + * @brief The client has sent a byte array of arbitrary size. + * + * This command's purpose is bi-directional exchange of arbitrary raw data. + * Useful for implementing higher-level protocols while using the RPC as a transport layer. + */ + RpcAppEventTypeDataExchange, +} RpcAppSystemEventType; + +/** + * @brief RPC application subsystem event structure. + */ +typedef struct { + RpcAppSystemEventType type; /**< Type of the event. */ + RpcAppSystemEventData data; /**< Data associated with the event. */ } RpcAppSystemEvent; -typedef void (*RpcAppSystemCallback)(RpcAppSystemEvent event, void* context); -typedef void ( - *RpcAppSystemDataExchangeCallback)(const uint8_t* data, size_t data_size, void* context); +/** + * @brief Callback function type. + * + * A function of this type must be passed to rpc_system_app_set_callback() by the user code. + * + * @warning The event pointer is valid ONLY inside the callback function. + * + * @param[in] event pointer to the event object. Valid only inside the callback function. + * @param[in,out] context pointer to the user-defined context object. + */ +typedef void (*RpcAppSystemCallback)(const RpcAppSystemEvent* event, void* context); +/** + * @brief RPC application subsystem opaque type declaration. + */ typedef struct RpcAppSystem RpcAppSystem; -void rpc_system_app_set_callback(RpcAppSystem* rpc_app, RpcAppSystemCallback callback, void* ctx); +/** + * @brief Set the callback function for use by an RpcAppSystem instance. + * + * @param[in,out] rpc_app pointer to the instance to be configured. + * @param[in] callback pointer to the function to be called upon message reception. + * @param[in,out] context pointer to the user-defined context object. Will be passed to the callback. + */ +void rpc_system_app_set_callback( + RpcAppSystem* rpc_app, + RpcAppSystemCallback callback, + void* context); +/** + * @brief Send a notification that an RpcAppSystem instance has been started and is ready. + * + * Call this function once right after acquiring an RPC context and setting the callback. + * + * @param[in,out] rpc_app pointer to the instance to be used. + */ void rpc_system_app_send_started(RpcAppSystem* rpc_app); +/** + * @brief Send a notification that the application using an RpcAppSystem instance is about to exit. + * + * Call this function when the application is about to exit (usually in the *_free() function). + * + * @param[in,out] rpc_app pointer to the instance to be used. + */ void rpc_system_app_send_exited(RpcAppSystem* rpc_app); -const char* rpc_system_app_get_data(RpcAppSystem* rpc_app); - -void rpc_system_app_confirm(RpcAppSystem* rpc_app, RpcAppSystemEvent event, bool result); +/** + * @brief Send a confirmation that the application using an RpcAppSystem instance has handled the event. + * + * An explicit confirmation is required for the following event types: + * - RpcAppEventTypeAppExit + * - RpcAppEventTypeLoadFile + * - RpcAppEventTypeButtonPress + * - RpcAppEventTypeButtonRelease + * - RpcAppEventTypeDataExchange + * + * Not confirming these events will result in a client-side timeout. + * + * @param[in,out] rpc_app pointer to the instance to be used. + * @param[in] result whether the command was successfully handled or not (true for success). + */ +void rpc_system_app_confirm(RpcAppSystem* rpc_app, bool result); +/** + * @brief Set the error code stored in an RpcAppSystem instance. + * + * The error code can be retrieved by the client at any time by using the GetError request. + * The error code value has no meaning within the subsystem, i.e. it is only passed through to the client. + * + * @param[in,out] rpc_app pointer to the instance to be modified. + * @param[in] error_code arbitrary error code to be set. + */ void rpc_system_app_set_error_code(RpcAppSystem* rpc_app, uint32_t error_code); +/** + * @brief Set the error text stored in an RpcAppSystem instance. + * + * The error text can be retrieved by the client at any time by using the GetError request. + * The text has no meaning within the subsystem, i.e. it is only passed through to the client. + * + * @param[in,out] rpc_app pointer to the instance to be modified. + * @param[in] error_text Pointer to a zero-terminated string containing the error text. + */ void rpc_system_app_set_error_text(RpcAppSystem* rpc_app, const char* error_text); +/** + * @brief Reset the error code and text stored in an RpcAppSystem instance. + * + * Resets the error code to 0 and error text to "" (empty string). + * + * @param[in,out] rpc_app pointer to the instance to be reset. + */ void rpc_system_app_error_reset(RpcAppSystem* rpc_app); -void rpc_system_app_set_data_exchange_callback( - RpcAppSystem* rpc_app, - RpcAppSystemDataExchangeCallback callback, - void* ctx); - +/** + * @brief Send a byte array of arbitrary data to the client using an RpcAppSystem instance. + * + * @param[in,out] rpc_app pointer to the instance to be used. + * @param[in] data pointer to the data buffer to be sent. + * @param[in] data_size size of the data buffer, in bytes. + */ void rpc_system_app_exchange_data(RpcAppSystem* rpc_app, const uint8_t* data, size_t data_size); #ifdef __cplusplus diff --git a/applications/services/rpc/rpc_cli.c b/applications/services/rpc/rpc_cli.c index f1c139b5f..4612752a8 100644 --- a/applications/services/rpc/rpc_cli.c +++ b/applications/services/rpc/rpc_cli.c @@ -2,7 +2,6 @@ #include #include #include -#include #define TAG "RpcCli" diff --git a/applications/services/storage/storage_cli.c b/applications/services/storage/storage_cli.c index 74bcf2d92..59489d459 100644 --- a/applications/services/storage/storage_cli.c +++ b/applications/services/storage/storage_cli.c @@ -333,11 +333,9 @@ static void storage_cli_write_chunk(Cli* cli, FuriString* path, FuriString* args if(buffer_size) { uint8_t* buffer = malloc(buffer_size); - for(uint32_t i = 0; i < buffer_size; i++) { - buffer[i] = cli_getc(cli); - } + size_t read_bytes = cli_read(cli, buffer, buffer_size); - uint16_t written_size = storage_file_write(file, buffer, buffer_size); + uint16_t written_size = storage_file_write(file, buffer, read_bytes); if(written_size != buffer_size) { storage_cli_print_error(storage_file_get_error(file)); diff --git a/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_auth.c b/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_auth.c index be2ee4825..b73fe347b 100644 --- a/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_auth.c +++ b/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_auth.c @@ -68,7 +68,7 @@ bool desktop_settings_scene_pin_auth_on_event(void* context, SceneManagerEvent e } else if(state == SCENE_STATE_PIN_AUTH_DISABLE) { scene_manager_next_scene(app->scene_manager, DesktopSettingsAppScenePinDisable); } else { - furi_assert(0); + furi_crash(); } consumed = true; break; diff --git a/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_error.c b/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_error.c index 508992cee..1ba3c1b2d 100644 --- a/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_error.c +++ b/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_error.c @@ -39,7 +39,7 @@ void desktop_settings_scene_pin_error_on_enter(void* context) { } else if(state == SCENE_STATE_PIN_ERROR_WRONG) { desktop_view_pin_input_set_label_primary(app->pin_input_view, 35, 8, "Wrong PIN!"); } else { - furi_assert(0); + furi_crash(); } desktop_view_pin_input_set_label_secondary(app->pin_input_view, 0, 8, NULL); desktop_view_pin_input_set_label_button(app->pin_input_view, "Retry"); diff --git a/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_setup_howto.c b/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_setup_howto.c index ec128246f..31eec3871 100644 --- a/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_setup_howto.c +++ b/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_setup_howto.c @@ -32,7 +32,7 @@ bool desktop_settings_scene_pin_setup_howto_on_event(void* context, SceneManager consumed = true; break; default: - furi_crash(NULL); + furi_crash(); } } return consumed; diff --git a/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_setup_howto2.c b/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_setup_howto2.c index 44b8e1bf7..0ebf85c64 100644 --- a/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_setup_howto2.c +++ b/applications/settings/desktop_settings/scenes/desktop_settings_scene_pin_setup_howto2.c @@ -52,7 +52,7 @@ bool desktop_settings_scene_pin_setup_howto2_on_event(void* context, SceneManage break; } default: - furi_crash(NULL); + furi_crash(); } } return consumed; diff --git a/applications/system/updater/updater.c b/applications/system/updater/updater.c index e749f3ce6..4c7fd29e9 100644 --- a/applications/system/updater/updater.c +++ b/applications/system/updater/updater.c @@ -5,7 +5,6 @@ #include #include #include -#include #include static bool updater_custom_event_callback(void* context, uint32_t event) { diff --git a/assets/.gitignore b/assets/.gitignore index a66a6eed4..ca338d633 100644 --- a/assets/.gitignore +++ b/assets/.gitignore @@ -1,5 +1 @@ /core2_firmware -/resources/Manifest -/resources/apps/* -/resources/dolphin/* -/resources/apps_data/**/*.fal diff --git a/assets/ReadMe.md b/assets/ReadMe.md index 2d493b4fe..84310e731 100644 --- a/assets/ReadMe.md +++ b/assets/ReadMe.md @@ -32,10 +32,7 @@ Good starting point: https://docs.unrealengine.com/4.27/en-US/ProductionPipeline Don't include assets that you are not using, compiler is not going to strip unused assets. # Structure -- `compiled` - Output folder made for compiled assets, after building project, in `build` directory. - `dolphin` - Dolphin game assets sources. Goes to `compiled` and `resources` folders in `build` directory. - `icons` - Icons sources. Goes to `compiled` folder in `build` directory. - `protobuf` - Protobuf sources. Goes to `compiled` folder in `build` directory. -- `resources` - Assets that is going to be provisioned to SD card. - `slideshow` - One-time slideshows for desktop -- `unit_tests` - Some pre-defined signals for testing purposes. diff --git a/assets/SConscript b/assets/SConscript index 9bd273626..c10de78af 100644 --- a/assets/SConscript +++ b/assets/SConscript @@ -1,16 +1,16 @@ -from fbt.version import get_git_commit_unix_timestamp - Import("env") assetsenv = env.Clone( tools=["fbt_assets"], FW_LIB_NAME="assets", - GIT_UNIX_TIMESTAMP=get_git_commit_unix_timestamp(), + ASSETS_WORK_DIR=env.Dir("compiled"), + ASSETS_SRC_DIR=env.Dir("#/assets"), ) assetsenv.ApplyLibFlags() icons = assetsenv.CompileIcons( - assetsenv.Dir("compiled"), assetsenv.Dir("#/assets/icons") + assetsenv["ASSETS_WORK_DIR"], + assetsenv["ASSETS_SRC_DIR"].Dir("icons"), ) assetsenv.Alias("icons", icons) @@ -18,7 +18,7 @@ assetsenv.Alias("icons", icons) # Protobuf .proto -> .c + .h proto_src = assetsenv.Glob("protobuf/*.proto", source=True) proto_options = assetsenv.Glob("protobuf/*.options", source=True) -proto = assetsenv.ProtoBuilder(assetsenv.Dir("compiled"), proto_src) +proto = assetsenv.ProtoBuilder(assetsenv["ASSETS_WORK_DIR"], proto_src) assetsenv.Depends(proto, proto_options) # Precious(proto) assetsenv.Alias("proto", proto) @@ -27,8 +27,8 @@ assetsenv.Alias("proto", proto) # Internal animations dolphin_internal = assetsenv.DolphinSymBuilder( - assetsenv.Dir("compiled"), - assetsenv.Dir("#/assets/dolphin"), + assetsenv["ASSETS_WORK_DIR"], + assetsenv["ASSETS_SRC_DIR"].Dir("dolphin"), DOLPHIN_RES_TYPE="internal", ) assetsenv.Alias("dolphin_internal", dolphin_internal) @@ -37,8 +37,8 @@ assetsenv.Alias("dolphin_internal", dolphin_internal) # Blocking animations dolphin_blocking = assetsenv.DolphinSymBuilder( - assetsenv.Dir("compiled"), - assetsenv.Dir("#/assets/dolphin"), + assetsenv["ASSETS_WORK_DIR"], + assetsenv["ASSETS_SRC_DIR"].Dir("dolphin"), DOLPHIN_RES_TYPE="blocking", ) assetsenv.Alias("dolphin_blocking", dolphin_blocking) @@ -46,8 +46,8 @@ assetsenv.Alias("dolphin_blocking", dolphin_blocking) # Protobuf version meta proto_ver = assetsenv.ProtoVerBuilder( - "compiled/protobuf_version.h", - "#/assets/protobuf/Changelog", + "${ASSETS_WORK_DIR}/protobuf_version.h", + assetsenv["ASSETS_SRC_DIR"].File("protobuf/Changelog"), ) assetsenv.Depends(proto_ver, proto) assetsenv.Alias("proto_ver", proto_ver) @@ -61,41 +61,19 @@ assetsenv.Install("${LIB_DIST_DIR}", assetslib) # Resources for SD card -env.SetDefault(FW_RESOURCES=None) if assetsenv["IS_BASE_FIRMWARE"]: + dolphin_external_out_dir = assetsenv["ASSETS_WORK_DIR"].Dir("dolphin") # External dolphin animations dolphin_external = assetsenv.DolphinExtBuilder( - assetsenv.Dir("#/assets/resources/dolphin"), - assetsenv.Dir("#/assets/dolphin"), + dolphin_external_out_dir, + assetsenv["ASSETS_SRC_DIR"].Dir("dolphin"), DOLPHIN_RES_TYPE="external", ) if assetsenv["FORCE"]: assetsenv.AlwaysBuild(dolphin_external) assetsenv.Alias("dolphin_ext", dolphin_external) - assetsenv.Clean(dolphin_external, assetsenv.Dir("#/assets/resources/dolphin")) + assetsenv.Clean(dolphin_external, dolphin_external_out_dir) - # Resources manifest - resources = assetsenv.Command( - "#/assets/resources/Manifest", - assetsenv.GlobRecursive( - "*", - assetsenv.Dir("resources").srcnode(), - exclude=["Manifest"], - ), - action=Action( - '${PYTHON3} "${ASSETS_COMPILER}" manifest "${TARGET.dir.posix}" --timestamp=${GIT_UNIX_TIMESTAMP}', - "${RESMANIFESTCOMSTR}", - ), - ) - assetsenv.Precious(resources) - assetsenv.AlwaysBuild(resources) - assetsenv.Clean( - resources, - assetsenv.Dir("#/assets/resources/apps"), - ) - - # Exporting resources node to external environment - env.Replace(FW_RESOURCES=resources) - assetsenv.Alias("resources", resources) + env.Replace(DOLPHIN_EXTERNAL_OUT_DIR=dolphin_external_out_dir) Return("assetslib") diff --git a/assets/protobuf b/assets/protobuf index 327163d58..23ad19a75 160000 --- a/assets/protobuf +++ b/assets/protobuf @@ -1 +1 @@ -Subproject commit 327163d5867c7aa3051334c93ced718d15bfe4da +Subproject commit 23ad19a756649ed9f6677b598e5361c5cce6847b diff --git a/documentation/AppManifests.md b/documentation/AppManifests.md index 72c15ad48..d190a798b 100644 --- a/documentation/AppManifests.md +++ b/documentation/AppManifests.md @@ -41,12 +41,13 @@ Only two parameters are mandatory: **_appid_** and **_apptype_**. Others are opt - **order**: order of an application within its group when sorting entries in it. The lower the order is, the closer to the start of the list the item is placed. _Used for ordering startup hooks and menu entries._ - **sdk_headers**: list of C header files from this app's code to include in API definitions for external applications. - **targets**: list of strings and target names with which this application is compatible. If not specified, the application is built for all targets. The default value is `["all"]`. +- **resources**: name of a folder within the application's source folder to be used for packacking SD card resources for this application. They will only be used if application is included in build configuration. The default value is `""`, meaning no resources are packaged. #### Parameters for external applications The following parameters are used only for [FAPs](./AppsOnSDCard.md): -- **sources**: list of strings, file name masks used for gathering sources within the app folder. The default value of `["*.c*"]` includes C and C++ source files. Applications cannot use the `"lib"` folder for their own source code, as it is reserved for **fap_private_libs**. +- **sources**: list of strings, file name masks used for gathering sources within the app folder. The default value of `["*.c*"]` includes C and C++ source files. Applications cannot use the `"lib"` folder for their own source code, as it is reserved for **fap_private_libs**. Paths starting with `"!"` are excluded from the list of sources. They can also include wildcard characters and directory names. For example, a value of `["*.c*", "!plugins"]` will include all C and C++ source files in the app folder except those in the `plugins` (and `lib`) folders. Paths with no wildcards (`*, ?`) are treated as full literal paths for both inclusion and exclusion. - **fap_version**: string, application version. The default value is "0.1". You can also use a tuple of 2 numbers in the form of (x,y) to specify the version. It is also possible to add more dot-separated parts to the version, like patch number, but only major and minor version numbers are stored in the built .fap. - **fap_icon**: name of a `.png` file, 1-bit color depth, 10x10px, to be embedded within `.fap` file. - **fap_libs**: list of extra libraries to link the application against. Provides access to extra functions that are not exported as a part of main firmware at the expense of increased `.fap` file size and RAM consumption. diff --git a/documentation/AppsOnSDCard.md b/documentation/AppsOnSDCard.md index f04793b4f..3f6d51acf 100644 --- a/documentation/AppsOnSDCard.md +++ b/documentation/AppsOnSDCard.md @@ -61,7 +61,7 @@ The App Loader allocates memory for the application and copies it to RAM, proces ## API versioning -Not all parts of firmware are available for external applications. A subset of available functions and variables is defined in the "api_symbols.csv" file, which is a part of the firmware target definition in the `firmware/targets/` directory. +Not all parts of firmware are available for external applications. A subset of available functions and variables is defined in the "api_symbols.csv" file, which is a part of the firmware target definition in the `targets/` directory. **`fbt`** uses semantic versioning for the API. The major version is incremented when there are breaking changes in the API. The minor version is incremented when new features are added. diff --git a/documentation/FuriCheck.md b/documentation/FuriCheck.md new file mode 100644 index 000000000..02f3fc917 --- /dev/null +++ b/documentation/FuriCheck.md @@ -0,0 +1,40 @@ +# Run time checks and forced system crash + +The best way to protect system integrity is to reduce amount cases that we must handle and crash the system as early as possible. +For that purpose we have bunch of helpers located in Furi Core check.h. + +## Couple notes before start + +- Definition of Crash - log event, save crash information in RTC and reboot the system. +- Definition of Halt - log event, stall the system. +- Debug and production builds behaves differently: debug build will never reset system in order to preserve state for debugging. +- If you have debugger connected we will stop before reboot automatically. +- All helpers accept optional MESSAGE_CSTR: it can be in RAM or Flash memory, but only messages from Flash will be shown after system reboot. +- MESSAGE_CSTR can be NULL, but macros magic already doing it for you, so just don't. + +## `furi_assert(CONDITION)` or `furi_assert(CONDITION, MESSAGE_CSTR)` + +Assert condition in development environment and crash the system if CONDITION is false. + +- Should be used at development stage in apps and services +- Keep in mind that release never contains this check +- Keep in mind that libraries never contains this check by default, use `LIB_DEBUG=1` if you need it +- Avoid putting function calls into CONDITION, since it may be omitted in some builds + +## `furi_check(CONDITION)` or `furi_check(CONDITION, MESSAGE_CSTR)` + +Always assert condition and crash the system if CONDITION is false. + +- Use it if you always need to check conditions + +## `furi_crash()` or `furi_crash(MESSAGE_CSTR)` + +Crash the system. + +- Use it to crash the system. For example: if abnormal condition detected. + +## `furi_halt()` or `furi_halt(MESSAGE_CSTR)` + +Halt the system. + +- We use it internally to shutdown flipper if poweroff is not possible. diff --git a/documentation/HardwareTargets.md b/documentation/HardwareTargets.md index 0c3474839..b3213d4f5 100644 --- a/documentation/HardwareTargets.md +++ b/documentation/HardwareTargets.md @@ -2,7 +2,7 @@ Flipper's firmware is modular and supports different hardware configurations in a common code base. It encapsulates hardware-specific differences in `furi_hal`, board initialization code, linker files, SDK data and other information in a _target definition_. -Target-specific files are placed in a single sub-folder in `firmware/targets`. It must contain a target definition file, `target.json`, and may contain other files if they are referenced by current target's definition. By default, `fbt` gathers all source files in target folder, unless they are explicitly excluded. +Target-specific files are placed in a single sub-folder in `targets`. It must contain a target definition file, `target.json`, and may contain other files if they are referenced by current target's definition. By default, `fbt` gathers all source files in target folder, unless they are explicitly excluded. Targets can inherit most code parts from other targets, to reduce common code duplication. diff --git a/documentation/UnitTests.md b/documentation/UnitTests.md index 4717daa8c..9352917cd 100644 --- a/documentation/UnitTests.md +++ b/documentation/UnitTests.md @@ -15,10 +15,9 @@ Running existing unit tests is useful to ensure that the new code doesn't introd To run the unit tests, follow these steps: -1. Compile the firmware with the tests enabled: `./fbt FIRMWARE_APP_SET=unit_tests`. -2. Flash the firmware using your preferred method. -3. Copy the [assets/unit_tests](/assets/unit_tests) folder to the root of your Flipper Zero's SD card. -4. Launch the CLI session and run the `unit_tests` command. +1. Compile the firmware with the tests enabled: `./fbt FIRMWARE_APP_SET=unit_tests updater_package`. +2. Flash the firmware using your preferred method, including SD card resources (`build/latest/resources`). +3. Launch the CLI session and run the `unit_tests` command. **NOTE:** To run a particular test (and skip all others), specify its name as the command argument. See [test_index.c](/applications/debug/unit_tests/test_index.c) for the complete list of test names. @@ -33,7 +32,7 @@ The common entry point for all tests is the [unit_tests](/applications/debug/uni #### Test assets -Some unit tests require external data in order to function. These files (commonly called assets) reside in the [assets/unit_tests](/assets/unit_tests) directory in their respective subdirectories. Asset files can be of any type (plain text, FlipperFormat (FFF), binary, etc.). +Some unit tests require external data in order to function. These files (commonly called assets) reside in the [unit_tests](/applications/debug/unit_tests/resources/unit_tests) directory in their respective subdirectories. Asset files can be of any type (plain text, FlipperFormat (FFF), binary, etc.). ### Application-specific @@ -42,10 +41,10 @@ Some unit tests require external data in order to function. These files (commonl Each infrared protocol has a corresponding set of unit tests, so it makes sense to implement one when adding support for a new protocol. To add unit tests for your protocol, follow these steps: -1. Create a file named `test_.irtest` in the [assets](/assets/unit_tests/infrared) directory. +1. Create a file named `test_.irtest` in the [assets](/applications/debug/unit_tests/resources/unit_tests/infrared) directory. 2. Fill it with the test data (more on it below). 3. Add the test code to [infrared_test.c](/applications/debug/unit_tests/infrared/infrared_test.c). -4. Update the [assets](/assets/unit_tests/infrared) on your Flipper Zero and run the tests to see if they pass. +4. Build and install firmware with resources, install it on your Flipper and run the tests to see if they pass. ##### Test data format diff --git a/documentation/file_formats/InfraredFileFormats.md b/documentation/file_formats/InfraredFileFormats.md index c9b6a9536..4d43bd5b8 100644 --- a/documentation/file_formats/InfraredFileFormats.md +++ b/documentation/file_formats/InfraredFileFormats.md @@ -72,9 +72,9 @@ Known protocols are represented in the `parsed` form, whereas non-recognized sig ### Examples -- [TV Universal Library](/assets/resources/infrared/assets/tv.ir) -- [A/C Universal Library](/assets/resources/infrared/assets/ac.ir) -- [Audio Universal Library](/assets/resources/infrared/assets/audio.ir) +- [TV Universal Library](/applications/main/infrared/resources/infrared/assets/tv.ir) +- [A/C Universal Library](/applications/main/infrared/resources/infrared/assets/ac.ir) +- [Audio Universal Library](/applications/main/infrared/resources/infrared/assets/audio.ir) ### Description @@ -92,7 +92,7 @@ See [Universal Remotes](/documentation/UniversalRemotes.md) for more information ### Examples -See [Infrared Unit Tests](/assets/unit_tests/infrared/) for various examples. +See [Infrared Unit Tests](/applications/debug/unit_tests/resources/unit_tests/infrared/) for various examples. ### Description diff --git a/documentation/file_formats/NfcFileFormats.md b/documentation/file_formats/NfcFileFormats.md index 78c6420ee..f752cdb90 100644 --- a/documentation/file_formats/NfcFileFormats.md +++ b/documentation/file_formats/NfcFileFormats.md @@ -1,44 +1,109 @@ # NFC Flipper File Formats -## NFC-A (UID) + Header +## UID + Header (General format) ### Example Filetype: Flipper NFC device - Version: 3 - # Nfc device type can be UID, Mifare Ultralight, Mifare Classic, Bank card - Device type: UID - # UID, ATQA and SAK are common for all formats - UID: 04 85 92 8A A0 61 81 - ATQA: 00 44 - SAK: 00 + Version: 4 + # Device type can be ISO14443-3A, ISO14443-3B, ISO14443-4A, NTAG/Ultralight, Mifare Classic, Mifare DESFire + Device type: ISO14443-4A + # UID is common for all formats + UID: 04 48 6A 32 33 58 80 + ------------------------- + (Device-specific data) ### Description -This file format is used to store the UID, SAK and ATQA of a NFC-A device. It does not store any internal data, so it can be used for multiple different card types. Also used as a header for other formats. +This file format is used to store the device type and the UID of an NFC device. It does not store any internal data, so it is only used as a header for other formats. Version differences: 1. Initial version, deprecated 2. LSB ATQA (e.g. 4400 instead of 0044) 3. MSB ATQA (current version) +4. Replace UID device type with ISO14443-3A -UID can be either 4 or 7 bytes long. ATQA is 2 bytes long. SAK is 1 byte long. +## ISO14443-3A -## Mifare Ultralight/NTAG + Filetype: Flipper NFC device + Version: 4 + # Device type can be ISO14443-3A, ISO14443-3B, ISO14443-4A, NTAG/Ultralight, Mifare Classic, Mifare DESFire + Device type: ISO14443-3A + # UID is common for all formats + UID: 34 19 6D 41 14 56 E6 + # ISO14443-3A specific data + ATQA: 00 44 + SAK: 00 + +### Description + +This file format is used to store the UID, SAK and ATQA of a ISO14443-3A device. +UID must be either 4 or 7 bytes long. ATQA is 2 bytes long. SAK is 1 byte long. + +Version differences: +None, there are no versions yet. + +## ISO14443-3B + + Filetype: Flipper NFC device + Version: 4 + # Device type can be ISO14443-3A, ISO14443-3B, ISO14443-4A, NTAG/Ultralight, Mifare Classic, Mifare DESFire + Device type: ISO14443-3B + # UID is common for all formats + UID: 30 1D B3 28 + # ISO14443-3B specific data + Application data: 00 12 34 FF + Protocol info: 11 81 E1 + +### Description + +This file format is used to store the UID, Application data and Protocol info of a ISO14443-3B device. +UID must be 4 bytes long. Application data is 4 bytes long. Protocol info is 3 bytes long. + +Version differences: +None, there are no versions yet. + +## ISO14443-4A ### Example Filetype: Flipper NFC device - Version: 3 - # Nfc device type can be UID, Mifare Ultralight, Mifare Classic - Device type: NTAG216 - # UID, ATQA and SAK are common for all formats + Version: 4 + # Device type can be ISO14443-3A, ISO14443-3B, ISO14443-4A, NTAG/Ultralight, Mifare Classic, Mifare DESFire + Device type: ISO14443-4A + # UID is common for all formats + UID: 04 48 6A 32 33 58 80 + # ISO14443-3A specific data + ATQA: 03 44 + SAK: 20 + # ISO14443-4A specific data + ATS: 06 75 77 81 02 80 + +### Description + +This file format is used to store the UID, SAK and ATQA of a ISO14443-4A device. It also stores the Answer to Select (ATS) data of the card. +ATS must be no less than 5 bytes long. + +Version differences: +None, there are no versions yet. + +## NTAG/Ultralight + +### Example + + Filetype: Flipper NFC device + Version: 4 + # Device type can be ISO14443-3A, ISO14443-3B, ISO14443-4A, NTAG/Ultralight, Mifare Classic, Mifare DESFire + Device type: NTAG/Ultralight + # UID is common for all formats UID: 04 85 90 54 12 98 23 + # ISO14443-3A specific data ATQA: 00 44 SAK: 00 - # Mifare Ultralight specific data - Data format version: 1 + # NTAG/Ultralight specific data + Data format version: 2 + NTAG/Ultralight type: NTAG216 Signature: 1B 84 EB 70 BD 4C BD 1B 1D E4 98 0B 18 58 BD 7C 72 85 B4 E4 7B 38 8E 96 CF 88 6B EE A3 43 AD 90 Mifare version: 00 04 04 02 01 00 13 03 Counter 0: 0 @@ -66,6 +131,8 @@ UID can be either 4 or 7 bytes long. ATQA is 2 bytes long. SAK is 1 byte long. This file format is used to store the UID, SAK and ATQA of a Mifare Ultralight/NTAG device. It also stores the internal data of the card, the signature, the version, and the counters. The data is stored in pages, just like on the card itself. +The "NTAG/Ultralight type" field contains the concrete device type. It must be one of: Mifare Ultralight, Mifare Ultralight 11, Mifare Ultralight 21, NTAG203, NTAG213, NTAG215, NTAG216, NTAG I2C 1K, NTAG I2C 2K, NTAG I2C Plus 1K, NTAG I2C Plus 2K. + The "Signature" field contains the reply of the tag to the READ_SIG command. More on that can be found here: (page 31) The "Mifare version" field is not related to the file format version but to the Mifare Ultralight version. It contains the response of the tag to the GET_VERSION command. More on that can be found here: (page 21) @@ -74,18 +141,20 @@ Other fields are the direct representation of the card's internal state. Learn m Version differences: -1. Current version +1. Mifare Ultralight type is stored directly in Device type field +2. Current version, Mifare Ultralight type is stored in the same-named field ## Mifare Classic ### Example Filetype: Flipper NFC device - Version: 3 - # Nfc device type can be UID, Mifare Ultralight, Mifare Classic + Version: 4 + # Device type can be ISO14443-3A, ISO14443-3B, ISO14443-4A, NTAG/Ultralight, Mifare Classic, Mifare DESFire Device type: Mifare Classic - # UID, ATQA and SAK are common for all formats + # UID is common for all formats UID: BA E2 7C 9D + # ISO14443-3A specific data ATQA: 00 02 SAK: 18 # Mifare Classic specific data @@ -145,13 +214,16 @@ Example: ### Example Filetype: Flipper NFC device - Version: 3 - # Nfc device type can be UID, Mifare Ultralight, Mifare Classic + Version: 4 + # Device type can be ISO14443-3A, ISO14443-3B, ISO14443-4A, NTAG/Ultralight, Mifare Classic, Mifare DESFire Device type: Mifare DESFire - # UID, ATQA and SAK are common for all formats + # UID is common for all formats UID: 04 2F 19 0A CD 66 80 + # ISO14443-3A specific data ATQA: 03 44 SAK: 20 + # ISO14443-4A specific data + ATS: 06 75 77 81 02 80 # Mifare DESFire specific data PICC Version: 04 01 01 12 00 1A 05 04 01 01 02 01 1A 05 04 2F 19 0A CD 66 80 CE ED D4 51 80 31 19 PICC Free Memory: 7520 diff --git a/firmware.scons b/firmware.scons index 82f775d71..eca6afc4c 100644 --- a/firmware.scons +++ b/firmware.scons @@ -1,15 +1,10 @@ -from SCons.Errors import UserError -from SCons.Node import FS - import itertools -from fbt_extra.util import ( - should_gen_cdb_and_link_dir, - link_elf_dir_as_latest, -) - from fbt.sdk.cache import LazySdkVersionLoader - +from fbt.version import get_git_commit_unix_timestamp +from fbt_extra.util import link_elf_dir_as_latest, should_gen_cdb_and_link_dir +from SCons.Errors import UserError +from SCons.Node import FS Import("ENV", "fw_build_meta") @@ -22,12 +17,15 @@ env = ENV.Clone( "pvsstudio", "fbt_hwtarget", "fbt_envhooks", + "fbt_resources", ], COMPILATIONDB_USE_ABSPATH=False, BUILD_DIR=fw_build_meta["build_dir"], IS_BASE_FIRMWARE=fw_build_meta["type"] == "firmware", FW_FLAVOR=fw_build_meta["flavor"], LIB_DIST_DIR=fw_build_meta["build_dir"].Dir("lib"), + RESOURCES_ROOT=fw_build_meta["build_dir"].Dir("resources"), + TARGETS_ROOT=Dir("#/targets"), LINT_SOURCES=[ Dir("applications"), ], @@ -37,7 +35,7 @@ env = ENV.Clone( CPPPATH=[ "#/furi", *(f"#/{app_dir[0]}" for app_dir in ENV["APPDIRS"] if app_dir[1]), - "#/firmware/targets/furi_hal_include", + "#/targets/furi_hal_include", ], # Specific flags for building libraries - always do optimized builds FW_LIB_OPTS={ @@ -104,7 +102,7 @@ lib_targets = env.BuildModules( [ "lib", "assets", - "firmware", + "targets", "furi", ], ) @@ -144,12 +142,22 @@ fwenv.PrepareApplicationsBuild() # Build external apps + configure SDK if env["IS_BASE_FIRMWARE"]: fwenv.SetDefault(FBT_FAP_DEBUG_ELF_ROOT=fwenv["BUILD_DIR"].Dir(".extapps")) - fwenv["FW_EXTAPPS"] = SConscript( + fw_extapps = fwenv["FW_EXTAPPS"] = SConscript( "site_scons/extapps.scons", exports={"ENV": fwenv}, ) - fw_artifacts.append(fwenv["FW_EXTAPPS"].sdk_tree) + fw_artifacts.append(fw_extapps.sdk_tree) + # Resources & manifest for SD card + manifest = fwenv.ManifestBuilder( + "${RESOURCES_ROOT}/Manifest", + GIT_UNIX_TIMESTAMP=get_git_commit_unix_timestamp(), + _EXTRA_DIST=[fwenv["DOLPHIN_EXTERNAL_OUT_DIR"]], + ) + fwenv.Replace(FW_RESOURCES_MANIFEST=manifest) + fwenv.Alias("resources", manifest) + + # API getter fwenv.Append(FBT_API_VERSION=LazySdkVersionLoader(fwenv.subst("$SDK_DEFINITION"))) fwenv.PhonyTarget( "get_apiversion", @@ -189,7 +197,7 @@ sources = [apps_c] # Gather sources only from app folders in current configuration sources.extend( itertools.chain.from_iterable( - fwenv.GlobRecursive(source_type, appdir.relpath, exclude=["lib"]) + fwenv.GatherSources([source_type, "!lib"], appdir.relpath) for appdir, source_type in fwenv["APPBUILD"].get_builtin_app_folders() ) ) diff --git a/firmware/targets/f7/furi_hal/furi_hal_nfc.c b/firmware/targets/f7/furi_hal/furi_hal_nfc.c deleted file mode 100644 index baffde1eb..000000000 --- a/firmware/targets/f7/furi_hal/furi_hal_nfc.c +++ /dev/null @@ -1,837 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#define TAG "FuriHalNfc" - -static const uint32_t clocks_in_ms = 64 * 1000; - -FuriEventFlag* event = NULL; -#define EVENT_FLAG_INTERRUPT (1UL << 0) -#define EVENT_FLAG_STATE_CHANGED (1UL << 1) -#define EVENT_FLAG_STOP (1UL << 2) -#define EVENT_FLAG_ALL (EVENT_FLAG_INTERRUPT | EVENT_FLAG_STATE_CHANGED | EVENT_FLAG_STOP) - -#define FURI_HAL_NFC_UID_INCOMPLETE (0x04) - -void furi_hal_nfc_init() { - furi_assert(!event); - event = furi_event_flag_alloc(); - - ReturnCode ret = rfalNfcInitialize(); - if(ret == ERR_NONE) { - furi_hal_nfc_start_sleep(); - FURI_LOG_I(TAG, "Init OK"); - } else { - FURI_LOG_W(TAG, "Init Failed, RFAL returned: %d", ret); - } -} - -void furi_hal_nfc_deinit() { - ReturnCode ret = rfalDeinitialize(); - if(ret == ERR_NONE) { - FURI_LOG_I(TAG, "Deinit OK"); - } else { - FURI_LOG_W(TAG, "Deinit Failed, RFAL returned: %d", ret); - } - - if(event) { - furi_event_flag_free(event); - event = NULL; - } -} - -bool furi_hal_nfc_is_busy() { - return rfalNfcGetState() != RFAL_NFC_STATE_IDLE; -} - -bool furi_hal_nfc_is_init() { - return rfalNfcGetState() != RFAL_NFC_STATE_NOTINIT; -} - -void furi_hal_nfc_field_on() { - furi_hal_nfc_exit_sleep(); - st25r3916TxRxOn(); -} - -void furi_hal_nfc_field_off() { - st25r3916TxRxOff(); - furi_hal_nfc_start_sleep(); -} - -void furi_hal_nfc_start_sleep() { - rfalLowPowerModeStart(); -} - -void furi_hal_nfc_exit_sleep() { - rfalLowPowerModeStop(); -} - -bool furi_hal_nfc_detect(FuriHalNfcDevData* nfc_data, uint32_t timeout) { - furi_assert(nfc_data); - - rfalNfcDevice* dev_list = NULL; - uint8_t dev_cnt = 0; - bool detected = false; - - rfalLowPowerModeStop(); - rfalNfcState state = rfalNfcGetState(); - rfalNfcState state_old = 0; - if(state == RFAL_NFC_STATE_NOTINIT) { - rfalNfcInitialize(); - } - rfalNfcDiscoverParam params; - params.compMode = RFAL_COMPLIANCE_MODE_EMV; - params.techs2Find = RFAL_NFC_POLL_TECH_A | RFAL_NFC_POLL_TECH_B | RFAL_NFC_POLL_TECH_F | - RFAL_NFC_POLL_TECH_V | RFAL_NFC_POLL_TECH_AP2P | RFAL_NFC_POLL_TECH_ST25TB; - params.totalDuration = 1000; - params.devLimit = 3; - params.wakeupEnabled = false; - params.wakeupConfigDefault = true; - params.nfcfBR = RFAL_BR_212; - params.ap2pBR = RFAL_BR_424; - params.maxBR = RFAL_BR_KEEP; - params.GBLen = RFAL_NFCDEP_GB_MAX_LEN; - params.notifyCb = NULL; - - uint32_t start = DWT->CYCCNT; - rfalNfcDiscover(¶ms); - while(true) { - rfalNfcWorker(); - state = rfalNfcGetState(); - if(state != state_old) { - FURI_LOG_T(TAG, "State change %d -> %d", state_old, state); - } - state_old = state; - if(state == RFAL_NFC_STATE_ACTIVATED) { - detected = true; - break; - } - if(state == RFAL_NFC_STATE_POLL_ACTIVATION) { - start = DWT->CYCCNT; - continue; - } - if(state == RFAL_NFC_STATE_POLL_SELECT) { - rfalNfcSelect(0); - } - if(DWT->CYCCNT - start > timeout * clocks_in_ms) { - rfalNfcDeactivate(true); - FURI_LOG_T(TAG, "Timeout"); - break; - } - furi_delay_tick(1); - } - rfalNfcGetDevicesFound(&dev_list, &dev_cnt); - if(detected) { - if(dev_list[0].type == RFAL_NFC_LISTEN_TYPE_NFCA) { - nfc_data->type = FuriHalNfcTypeA; - nfc_data->atqa[0] = dev_list[0].dev.nfca.sensRes.anticollisionInfo; - nfc_data->atqa[1] = dev_list[0].dev.nfca.sensRes.platformInfo; - nfc_data->sak = dev_list[0].dev.nfca.selRes.sak; - uint8_t* cuid_start = dev_list[0].nfcid; - if(dev_list[0].nfcidLen == 7) { - cuid_start = &dev_list[0].nfcid[3]; - } - nfc_data->cuid = (cuid_start[0] << 24) | (cuid_start[1] << 16) | (cuid_start[2] << 8) | - (cuid_start[3]); - } else if( - dev_list[0].type == RFAL_NFC_LISTEN_TYPE_NFCB || - dev_list[0].type == RFAL_NFC_LISTEN_TYPE_ST25TB) { - nfc_data->type = FuriHalNfcTypeB; - } else if(dev_list[0].type == RFAL_NFC_LISTEN_TYPE_NFCF) { - nfc_data->type = FuriHalNfcTypeF; - } else if(dev_list[0].type == RFAL_NFC_LISTEN_TYPE_NFCV) { - nfc_data->type = FuriHalNfcTypeV; - } - if(dev_list[0].rfInterface == RFAL_NFC_INTERFACE_RF) { - nfc_data->interface = FuriHalNfcInterfaceRf; - } else if(dev_list[0].rfInterface == RFAL_NFC_INTERFACE_ISODEP) { - nfc_data->interface = FuriHalNfcInterfaceIsoDep; - } else if(dev_list[0].rfInterface == RFAL_NFC_INTERFACE_NFCDEP) { - nfc_data->interface = FuriHalNfcInterfaceNfcDep; - } - nfc_data->uid_len = dev_list[0].nfcidLen; - memcpy(nfc_data->uid, dev_list[0].nfcid, nfc_data->uid_len); - } - - return detected; -} - -bool furi_hal_nfc_activate_nfca(uint32_t timeout, uint32_t* cuid) { - rfalNfcDevice* dev_list; - uint8_t dev_cnt = 0; - rfalLowPowerModeStop(); - rfalNfcState state = rfalNfcGetState(); - if(state == RFAL_NFC_STATE_NOTINIT) { - rfalNfcInitialize(); - } - rfalNfcDiscoverParam params = { - .compMode = RFAL_COMPLIANCE_MODE_NFC, - .techs2Find = RFAL_NFC_POLL_TECH_A, - .totalDuration = 1000, - .devLimit = 3, - .wakeupEnabled = false, - .wakeupConfigDefault = true, - .nfcfBR = RFAL_BR_212, - .ap2pBR = RFAL_BR_424, - .maxBR = RFAL_BR_KEEP, - .GBLen = RFAL_NFCDEP_GB_MAX_LEN, - .notifyCb = NULL, - }; - uint32_t start = DWT->CYCCNT; - rfalNfcDiscover(¶ms); - while(state != RFAL_NFC_STATE_ACTIVATED) { - rfalNfcWorker(); - state = rfalNfcGetState(); - FURI_LOG_T(TAG, "Current state %d", state); - if(state == RFAL_NFC_STATE_POLL_ACTIVATION) { - start = DWT->CYCCNT; - continue; - } - if(state == RFAL_NFC_STATE_POLL_SELECT) { - rfalNfcSelect(0); - } - if(DWT->CYCCNT - start > timeout * clocks_in_ms) { - rfalNfcDeactivate(true); - FURI_LOG_T(TAG, "Timeout"); - return false; - } - furi_thread_yield(); - } - rfalNfcGetDevicesFound(&dev_list, &dev_cnt); - // Take first device and set cuid - if(cuid) { - uint8_t* cuid_start = dev_list[0].nfcid; - if(dev_list[0].nfcidLen == 7) { - cuid_start = &dev_list[0].nfcid[3]; - } - *cuid = (cuid_start[0] << 24) | (cuid_start[1] << 16) | (cuid_start[2] << 8) | - (cuid_start[3]); - FURI_LOG_T(TAG, "Activated tag with cuid: %lX", *cuid); - } - return true; -} - -bool furi_hal_nfc_listen( - uint8_t* uid, - uint8_t uid_len, - uint8_t* atqa, - uint8_t sak, - bool activate_after_sak, - uint32_t timeout) { - rfalNfcState state = rfalNfcGetState(); - if(state == RFAL_NFC_STATE_NOTINIT) { - rfalNfcInitialize(); - } else if(state >= RFAL_NFC_STATE_ACTIVATED) { - rfalNfcDeactivate(false); - } - rfalLowPowerModeStop(); - rfalNfcDiscoverParam params = { - .techs2Find = RFAL_NFC_LISTEN_TECH_A, - .totalDuration = 1000, - .devLimit = 1, - .wakeupEnabled = false, - .wakeupConfigDefault = true, - .nfcfBR = RFAL_BR_212, - .ap2pBR = RFAL_BR_424, - .maxBR = RFAL_BR_KEEP, - .GBLen = RFAL_NFCDEP_GB_MAX_LEN, - .notifyCb = NULL, - .activate_after_sak = activate_after_sak, - }; - if(FURI_BIT(sak, 5)) { - params.compMode = RFAL_COMPLIANCE_MODE_EMV; - } else { - params.compMode = RFAL_COMPLIANCE_MODE_NFC; - } - params.lmConfigPA.nfcidLen = uid_len; - memcpy(params.lmConfigPA.nfcid, uid, uid_len); - params.lmConfigPA.SENS_RES[0] = atqa[0]; - params.lmConfigPA.SENS_RES[1] = atqa[1]; - params.lmConfigPA.SEL_RES = sak; - rfalNfcDiscover(¶ms); - - // Disable EMD suppression. - st25r3916ModifyRegister(ST25R3916_REG_EMD_SUP_CONF, ST25R3916_REG_EMD_SUP_CONF_emd_emv, 0); - - uint32_t start = DWT->CYCCNT; - while(state != RFAL_NFC_STATE_ACTIVATED) { - rfalNfcWorker(); - state = rfalNfcGetState(); - if(DWT->CYCCNT - start > timeout * clocks_in_ms) { - rfalNfcDeactivate(true); - return false; - } - furi_delay_tick(1); - } - return true; -} - -static void furi_hal_nfc_read_fifo(uint8_t* data, uint16_t* bits) { - uint8_t fifo_status[2]; - uint8_t rx_buff[64]; - - st25r3916ReadMultipleRegisters( - ST25R3916_REG_FIFO_STATUS1, fifo_status, ST25R3916_FIFO_STATUS_LEN); - uint16_t rx_bytes = - ((((uint16_t)fifo_status[1] & ST25R3916_REG_FIFO_STATUS2_fifo_b_mask) >> - ST25R3916_REG_FIFO_STATUS2_fifo_b_shift) - << 8); - rx_bytes |= (((uint16_t)fifo_status[0]) & 0x00FFU); - st25r3916ReadFifo(rx_buff, rx_bytes); - - memcpy(data, rx_buff, rx_bytes); - *bits = rx_bytes * 8; -} - -void furi_hal_nfc_listen_sleep() { - st25r3916ExecuteCommand(ST25R3916_CMD_GOTO_SLEEP); -} - -void furi_hal_nfc_stop_cmd() { - st25r3916ExecuteCommand(ST25R3916_CMD_STOP); -} - -bool furi_hal_nfc_listen_rx(FuriHalNfcTxRxContext* tx_rx, uint32_t timeout_ms) { - furi_assert(tx_rx); - - // Wait for interrupts - uint32_t start = furi_get_tick(); - bool data_received = false; - while(true) { - if(furi_hal_gpio_read(&gpio_nfc_irq_rfid_pull) == true) { - st25r3916CheckForReceivedInterrupts(); - if(st25r3916GetInterrupt(ST25R3916_IRQ_MASK_RXE)) { - furi_hal_nfc_read_fifo(tx_rx->rx_data, &tx_rx->rx_bits); - data_received = true; - if(tx_rx->sniff_rx) { - tx_rx->sniff_rx(tx_rx->rx_data, tx_rx->rx_bits, false, tx_rx->sniff_context); - } - break; - } - continue; - } - if(furi_get_tick() - start > timeout_ms) { - FURI_LOG_T(TAG, "Interrupt waiting timeout"); - furi_delay_tick(1); - break; - } - } - - return data_received; -} - -void furi_hal_nfc_listen_start(FuriHalNfcDevData* nfc_data) { - furi_assert(nfc_data); - - furi_hal_gpio_init(&gpio_nfc_irq_rfid_pull, GpioModeInput, GpioPullDown, GpioSpeedVeryHigh); - // Clear interrupts - st25r3916ClearInterrupts(); - // Mask all interrupts - st25r3916DisableInterrupts(ST25R3916_IRQ_MASK_ALL); - // RESET - st25r3916ExecuteCommand(ST25R3916_CMD_STOP); - // Setup registers - st25r3916WriteRegister( - ST25R3916_REG_OP_CONTROL, - ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_rx_en | - ST25R3916_REG_OP_CONTROL_en_fd_auto_efd); - st25r3916WriteRegister( - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_targ_targ | ST25R3916_REG_MODE_om3 | ST25R3916_REG_MODE_om0); - st25r3916WriteRegister( - ST25R3916_REG_PASSIVE_TARGET, - ST25R3916_REG_PASSIVE_TARGET_fdel_2 | ST25R3916_REG_PASSIVE_TARGET_fdel_0 | - ST25R3916_REG_PASSIVE_TARGET_d_ac_ap2p | ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r); - st25r3916WriteRegister(ST25R3916_REG_MASK_RX_TIMER, 0x02); - - // Mask interrupts - uint32_t clear_irq_mask = - (ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_RXE_PTA | ST25R3916_IRQ_MASK_WU_A_X | - ST25R3916_IRQ_MASK_WU_A); - st25r3916EnableInterrupts(clear_irq_mask); - - // Set 4 or 7 bytes UID - if(nfc_data->uid_len == 4) { - st25r3916ChangeRegisterBits( - ST25R3916_REG_AUX, ST25R3916_REG_AUX_nfc_id_mask, ST25R3916_REG_AUX_nfc_id_4bytes); - } else { - st25r3916ChangeRegisterBits( - ST25R3916_REG_AUX, ST25R3916_REG_AUX_nfc_id_mask, ST25R3916_REG_AUX_nfc_id_7bytes); - } - // Write PT Memory - uint8_t pt_memory[15] = {}; - memcpy(pt_memory, nfc_data->uid, nfc_data->uid_len); - pt_memory[10] = nfc_data->atqa[0]; - pt_memory[11] = nfc_data->atqa[1]; - if(nfc_data->uid_len == 4) { - pt_memory[12] = nfc_data->sak & ~FURI_HAL_NFC_UID_INCOMPLETE; - } else { - pt_memory[12] = FURI_HAL_NFC_UID_INCOMPLETE; - } - pt_memory[13] = nfc_data->sak & ~FURI_HAL_NFC_UID_INCOMPLETE; - pt_memory[14] = nfc_data->sak & ~FURI_HAL_NFC_UID_INCOMPLETE; - - st25r3916WritePTMem(pt_memory, sizeof(pt_memory)); - // Go to sense - st25r3916ExecuteCommand(ST25R3916_CMD_GOTO_SENSE); -} - -void rfal_interrupt_callback_handler() { - furi_event_flag_set(event, EVENT_FLAG_INTERRUPT); -} - -void rfal_state_changed_callback(void* context) { - UNUSED(context); - furi_event_flag_set(event, EVENT_FLAG_STATE_CHANGED); -} - -void furi_hal_nfc_stop() { - if(event) { - furi_event_flag_set(event, EVENT_FLAG_STOP); - } -} - -bool furi_hal_nfc_emulate_nfca( - uint8_t* uid, - uint8_t uid_len, - uint8_t* atqa, - uint8_t sak, - FuriHalNfcEmulateCallback callback, - void* context, - uint32_t timeout) { - rfalSetUpperLayerCallback(rfal_interrupt_callback_handler); - rfal_set_state_changed_callback(rfal_state_changed_callback); - - rfalLmConfPA config; - config.nfcidLen = uid_len; - memcpy(config.nfcid, uid, uid_len); - memcpy(config.SENS_RES, atqa, RFAL_LM_SENS_RES_LEN); - config.SEL_RES = sak; - uint8_t buff_rx[256]; - uint16_t buff_rx_size = 256; - uint16_t buff_rx_len = 0; - uint8_t buff_tx[1040]; - uint16_t buff_tx_len = 0; - uint32_t data_type = FURI_HAL_NFC_TXRX_DEFAULT; - - rfalLowPowerModeStop(); - if(rfalListenStart( - RFAL_LM_MASK_NFCA, - &config, - NULL, - NULL, - buff_rx, - rfalConvBytesToBits(buff_rx_size), - &buff_rx_len)) { - rfalListenStop(); - FURI_LOG_E(TAG, "Failed to start listen mode"); - return false; - } - while(true) { - buff_rx_len = 0; - buff_tx_len = 0; - uint32_t flag = furi_event_flag_wait(event, EVENT_FLAG_ALL, FuriFlagWaitAny, timeout); - if(flag == (unsigned)FuriFlagErrorTimeout || flag == EVENT_FLAG_STOP) { - break; - } - bool data_received = false; - buff_rx_len = 0; - rfalWorker(); - rfalLmState state = rfalListenGetState(&data_received, NULL); - if(data_received) { - rfalTransceiveBlockingRx(); - if(nfca_emulation_handler(buff_rx, buff_rx_len, buff_tx, &buff_tx_len)) { - if(rfalListenSleepStart( - RFAL_LM_STATE_SLEEP_A, - buff_rx, - rfalConvBytesToBits(buff_rx_size), - &buff_rx_len)) { - FURI_LOG_E(TAG, "Failed to enter sleep mode"); - break; - } else { - continue; - } - } - if(buff_tx_len) { - ReturnCode ret = rfalTransceiveBitsBlockingTx( - buff_tx, - buff_tx_len, - buff_rx, - rfalConvBytesToBits(buff_rx_size), - &buff_rx_len, - data_type, - RFAL_FWT_NONE); - if(ret) { - FURI_LOG_E(TAG, "Tranceive failed with status %d", ret); - break; - } - continue; - } - if((state == RFAL_LM_STATE_ACTIVE_A || state == RFAL_LM_STATE_ACTIVE_Ax)) { - if(callback) { - callback(buff_rx, buff_rx_len, buff_tx, &buff_tx_len, &data_type, context); - } - if(!rfalIsExtFieldOn()) { - break; - } - if(buff_tx_len) { - if(buff_tx_len == UINT16_MAX) buff_tx_len = 0; - - ReturnCode ret = rfalTransceiveBitsBlockingTx( - buff_tx, - buff_tx_len, - buff_rx, - rfalConvBytesToBits(buff_rx_size), - &buff_rx_len, - data_type, - RFAL_FWT_NONE); - if(ret) { - FURI_LOG_E(TAG, "Tranceive failed with status %d", ret); - continue; - } - } else { - break; - } - } - } - } - rfalListenStop(); - return true; -} - -static bool furi_hal_nfc_transparent_tx_rx(FuriHalNfcTxRxContext* tx_rx, uint16_t timeout_ms) { - furi_assert(tx_rx->nfca_signal); - - bool ret = false; - - // Start transparent mode - st25r3916ExecuteCommand(ST25R3916_CMD_TRANSPARENT_MODE); - // Reconfigure gpio for Transparent mode - furi_hal_spi_bus_handle_deinit(&furi_hal_spi_bus_handle_nfc); - - // Send signal - FURI_CRITICAL_ENTER(); - nfca_signal_encode(tx_rx->nfca_signal, tx_rx->tx_data, tx_rx->tx_bits, tx_rx->tx_parity); - digital_signal_send(tx_rx->nfca_signal->tx_signal, &gpio_spi_r_mosi); - FURI_CRITICAL_EXIT(); - furi_hal_gpio_write(&gpio_spi_r_mosi, false); - - // Configure gpio back to SPI and exit transparent - furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_nfc); - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - - // Manually wait for interrupt - furi_hal_gpio_init(&gpio_nfc_irq_rfid_pull, GpioModeInput, GpioPullDown, GpioSpeedVeryHigh); - st25r3916ClearAndEnableInterrupts(ST25R3916_IRQ_MASK_RXE); - - if(tx_rx->sniff_tx) { - tx_rx->sniff_tx(tx_rx->tx_data, tx_rx->tx_bits, false, tx_rx->sniff_context); - } - - uint32_t irq = 0; - uint8_t rxe = 0; - uint32_t start = DWT->CYCCNT; - while(true) { - if(!rfalIsExtFieldOn()) { - return false; - } - if(furi_hal_gpio_read(&gpio_nfc_irq_rfid_pull) == true) { - st25r3916ReadRegister(ST25R3916_REG_IRQ_MAIN, &rxe); - if(rxe & (1 << 4)) { - irq = 1; - break; - } - } - uint32_t timeout = DWT->CYCCNT - start; - if(timeout / furi_hal_cortex_instructions_per_microsecond() > timeout_ms * 1000) { - FURI_LOG_D(TAG, "Interrupt waiting timeout"); - break; - } - } - if(irq) { - uint8_t fifo_stat[2]; - st25r3916ReadMultipleRegisters( - ST25R3916_REG_FIFO_STATUS1, fifo_stat, ST25R3916_FIFO_STATUS_LEN); - uint16_t len = - ((((uint16_t)fifo_stat[1] & ST25R3916_REG_FIFO_STATUS2_fifo_b_mask) >> - ST25R3916_REG_FIFO_STATUS2_fifo_b_shift) - << RFAL_BITS_IN_BYTE); - len |= (((uint16_t)fifo_stat[0]) & 0x00FFU); - uint8_t rx[100]; - st25r3916ReadFifo(rx, len); - - tx_rx->rx_bits = len * 8; - memcpy(tx_rx->rx_data, rx, len); - - if(tx_rx->sniff_rx) { - tx_rx->sniff_rx(tx_rx->rx_data, tx_rx->rx_bits, false, tx_rx->sniff_context); - } - - ret = true; - } else { - FURI_LOG_E(TAG, "Timeout error"); - ret = false; - } - - st25r3916ClearInterrupts(); - - return ret; -} - -static uint32_t furi_hal_nfc_tx_rx_get_flag(FuriHalNfcTxRxType type) { - uint32_t flags = 0; - - if(type == FuriHalNfcTxRxTypeRxNoCrc) { - flags = RFAL_TXRX_FLAGS_CRC_RX_KEEP; - } else if(type == FuriHalNfcTxRxTypeRxKeepPar) { - flags = RFAL_TXRX_FLAGS_CRC_TX_MANUAL | RFAL_TXRX_FLAGS_CRC_RX_KEEP | - RFAL_TXRX_FLAGS_PAR_RX_KEEP; - } else if(type == FuriHalNfcTxRxTypeRaw) { - flags = RFAL_TXRX_FLAGS_CRC_TX_MANUAL | RFAL_TXRX_FLAGS_CRC_RX_KEEP | - RFAL_TXRX_FLAGS_PAR_RX_KEEP | RFAL_TXRX_FLAGS_PAR_TX_NONE; - } else if(type == FuriHalNfcTxRxTypeRxRaw) { - flags = RFAL_TXRX_FLAGS_CRC_TX_MANUAL | RFAL_TXRX_FLAGS_CRC_RX_KEEP | - RFAL_TXRX_FLAGS_PAR_RX_KEEP | RFAL_TXRX_FLAGS_PAR_TX_NONE; - } - - return flags; -} - -static uint16_t furi_hal_nfc_data_and_parity_to_bitstream( - uint8_t* data, - uint16_t len, - uint8_t* parity, - uint8_t* out) { - furi_assert(data); - furi_assert(out); - - uint8_t next_par_bit = 0; - uint16_t curr_bit_pos = 0; - for(uint16_t i = 0; i < len; i++) { - next_par_bit = FURI_BIT(parity[i / 8], 7 - (i % 8)); - if(curr_bit_pos % 8 == 0) { - out[curr_bit_pos / 8] = data[i]; - curr_bit_pos += 8; - out[curr_bit_pos / 8] = next_par_bit; - curr_bit_pos++; - } else { - out[curr_bit_pos / 8] |= data[i] << (curr_bit_pos % 8); - out[curr_bit_pos / 8 + 1] = data[i] >> (8 - curr_bit_pos % 8); - out[curr_bit_pos / 8 + 1] |= next_par_bit << (curr_bit_pos % 8); - curr_bit_pos += 9; - } - } - return curr_bit_pos; -} - -uint16_t furi_hal_nfc_bitstream_to_data_and_parity( - uint8_t* in_buff, - uint16_t in_buff_bits, - uint8_t* out_data, - uint8_t* out_parity) { - if(in_buff_bits < 8) { - out_data[0] = in_buff[0]; - return in_buff_bits; - } - if(in_buff_bits % 9 != 0) { - return 0; - } - - uint8_t curr_byte = 0; - uint16_t bit_processed = 0; - memset(out_parity, 0, in_buff_bits / 9); - while(bit_processed < in_buff_bits) { - out_data[curr_byte] = in_buff[bit_processed / 8] >> (bit_processed % 8); - out_data[curr_byte] |= in_buff[bit_processed / 8 + 1] << (8 - bit_processed % 8); - out_parity[curr_byte / 8] |= FURI_BIT(in_buff[bit_processed / 8 + 1], bit_processed % 8) - << (7 - curr_byte % 8); - bit_processed += 9; - curr_byte++; - } - return curr_byte * 8; -} - -bool furi_hal_nfc_tx_rx(FuriHalNfcTxRxContext* tx_rx, uint16_t timeout_ms) { - furi_assert(tx_rx); - - ReturnCode ret; - rfalNfcState state = RFAL_NFC_STATE_ACTIVATED; - uint8_t temp_tx_buff[FURI_HAL_NFC_DATA_BUFF_SIZE] = {}; - uint16_t temp_tx_bits = 0; - uint8_t* temp_rx_buff = NULL; - uint16_t* temp_rx_bits = NULL; - - if(tx_rx->tx_rx_type == FuriHalNfcTxRxTransparent) { - return furi_hal_nfc_transparent_tx_rx(tx_rx, timeout_ms); - } - - // Prepare data for FIFO if necessary - uint32_t flags = furi_hal_nfc_tx_rx_get_flag(tx_rx->tx_rx_type); - if(tx_rx->tx_rx_type == FuriHalNfcTxRxTypeRaw) { - temp_tx_bits = furi_hal_nfc_data_and_parity_to_bitstream( - tx_rx->tx_data, tx_rx->tx_bits / 8, tx_rx->tx_parity, temp_tx_buff); - ret = rfalNfcDataExchangeCustomStart( - temp_tx_buff, temp_tx_bits, &temp_rx_buff, &temp_rx_bits, RFAL_FWT_NONE, flags); - } else { - ret = rfalNfcDataExchangeCustomStart( - tx_rx->tx_data, tx_rx->tx_bits, &temp_rx_buff, &temp_rx_bits, RFAL_FWT_NONE, flags); - } - if(ret != ERR_NONE) { - FURI_LOG_E(TAG, "Failed to start data exchange"); - return false; - } - - if(tx_rx->sniff_tx) { - bool crc_dropped = !(flags & RFAL_TXRX_FLAGS_CRC_TX_MANUAL); - tx_rx->sniff_tx(tx_rx->tx_data, tx_rx->tx_bits, crc_dropped, tx_rx->sniff_context); - } - - uint32_t start = DWT->CYCCNT; - while(state != RFAL_NFC_STATE_DATAEXCHANGE_DONE) { - rfalNfcWorker(); - state = rfalNfcGetState(); - ret = rfalNfcDataExchangeGetStatus(); - if(ret == ERR_WRONG_STATE) { - return false; - } else if(ret == ERR_BUSY) { - if(DWT->CYCCNT - start > timeout_ms * clocks_in_ms) { - FURI_LOG_D(TAG, "Timeout during data exchange"); - return false; - } - continue; - } else { - start = DWT->CYCCNT; - } - furi_delay_tick(1); - } - - if(tx_rx->tx_rx_type == FuriHalNfcTxRxTypeRaw || - tx_rx->tx_rx_type == FuriHalNfcTxRxTypeRxRaw) { - tx_rx->rx_bits = furi_hal_nfc_bitstream_to_data_and_parity( - temp_rx_buff, *temp_rx_bits, tx_rx->rx_data, tx_rx->rx_parity); - } else { - memcpy(tx_rx->rx_data, temp_rx_buff, MIN(*temp_rx_bits / 8, FURI_HAL_NFC_DATA_BUFF_SIZE)); - tx_rx->rx_bits = *temp_rx_bits; - } - - if(tx_rx->sniff_rx) { - bool crc_dropped = !(flags & RFAL_TXRX_FLAGS_CRC_RX_KEEP); - tx_rx->sniff_rx(tx_rx->rx_data, tx_rx->rx_bits, crc_dropped, tx_rx->sniff_context); - } - - return true; -} - -bool furi_hal_nfc_tx_rx_full(FuriHalNfcTxRxContext* tx_rx) { - uint16_t part_len_bytes; - - if(!furi_hal_nfc_tx_rx(tx_rx, 1000)) { - return false; - } - while(tx_rx->rx_bits && tx_rx->rx_data[0] == 0xAF) { - FuriHalNfcTxRxContext tmp = *tx_rx; - tmp.tx_data[0] = 0xAF; - tmp.tx_bits = 8; - if(!furi_hal_nfc_tx_rx(&tmp, 1000)) { - return false; - } - part_len_bytes = tmp.rx_bits / 8; - if(part_len_bytes > FURI_HAL_NFC_DATA_BUFF_SIZE - tx_rx->rx_bits / 8) { - FURI_LOG_W(TAG, "Overrun rx buf"); - return false; - } - if(part_len_bytes == 0) { - FURI_LOG_W(TAG, "Empty 0xAF response"); - return false; - } - memcpy(tx_rx->rx_data + tx_rx->rx_bits / 8, tmp.rx_data + 1, part_len_bytes - 1); - tx_rx->rx_data[0] = tmp.rx_data[0]; - tx_rx->rx_bits += 8 * (part_len_bytes - 1); - } - - return true; -} - -void furi_hal_nfc_sleep() { - rfalNfcDeactivate(false); - rfalLowPowerModeStart(); -} - -FuriHalNfcReturn - furi_hal_nfc_ll_set_mode(FuriHalNfcMode mode, FuriHalNfcBitrate txBR, FuriHalNfcBitrate rxBR) { - return rfalSetMode((rfalMode)mode, (rfalBitRate)txBR, (rfalBitRate)rxBR); -} - -void furi_hal_nfc_ll_set_error_handling(FuriHalNfcErrorHandling eHandling) { - rfalSetErrorHandling((rfalEHandling)eHandling); -} - -void furi_hal_nfc_ll_set_guard_time(uint32_t cycles) { - rfalSetGT(cycles); -} - -void furi_hal_nfc_ll_set_fdt_listen(uint32_t cycles) { - rfalSetFDTListen(cycles); -} - -void furi_hal_nfc_ll_set_fdt_poll(uint32_t FDTPoll) { - rfalSetFDTPoll(FDTPoll); -} - -void furi_hal_nfc_ll_txrx_on() { - st25r3916TxRxOn(); -} - -void furi_hal_nfc_ll_txrx_off() { - st25r3916TxRxOff(); -} - -FuriHalNfcReturn furi_hal_nfc_ll_txrx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt) { - return rfalTransceiveBlockingTxRx(txBuf, txBufLen, rxBuf, rxBufLen, actLen, flags, fwt); -} - -FuriHalNfcReturn furi_hal_nfc_ll_txrx_bits( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt) { - return rfalTransceiveBitsBlockingTxRx(txBuf, txBufLen, rxBuf, rxBufLen, actLen, flags, fwt); -} - -void furi_hal_nfc_ll_poll() { - rfalWorker(); -} - -void furi_hal_nfc_field_detect_start() { - st25r3916WriteRegister( - ST25R3916_REG_OP_CONTROL, - ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_en_fd_mask); - st25r3916WriteRegister(ST25R3916_REG_MODE, ST25R3916_REG_MODE_targ | ST25R3916_REG_MODE_om0); -} - -bool furi_hal_nfc_field_is_present() { - return st25r3916CheckReg( - ST25R3916_REG_AUX_DISPLAY, - ST25R3916_REG_AUX_DISPLAY_efd_o, - ST25R3916_REG_AUX_DISPLAY_efd_o); -} \ No newline at end of file diff --git a/firmware/targets/f7/furi_hal/furi_hal_nfc.h b/firmware/targets/f7/furi_hal/furi_hal_nfc.h deleted file mode 100644 index f4051926a..000000000 --- a/firmware/targets/f7/furi_hal/furi_hal_nfc.h +++ /dev/null @@ -1,431 +0,0 @@ -/** - * @file furi_hal_nfc.h - * NFC HAL API - */ - -#pragma once - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif -#include -#include - -#define FURI_HAL_NFC_UID_MAX_LEN 10 -#define FURI_HAL_NFC_DATA_BUFF_SIZE (512) -#define FURI_HAL_NFC_PARITY_BUFF_SIZE (FURI_HAL_NFC_DATA_BUFF_SIZE / 8) - -#define FURI_HAL_NFC_TXRX_DEFAULT \ - ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_AUTO | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_REMV | \ - (uint32_t)RFAL_TXRX_FLAGS_PAR_RX_REMV | (uint32_t)RFAL_TXRX_FLAGS_PAR_TX_AUTO) - -#define FURI_HAL_NFC_TX_DEFAULT_RX_NO_CRC \ - ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_AUTO | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP | \ - (uint32_t)RFAL_TXRX_FLAGS_PAR_RX_REMV | (uint32_t)RFAL_TXRX_FLAGS_PAR_TX_AUTO) - -#define FURI_HAL_NFC_TXRX_WITH_PAR \ - ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP | \ - (uint32_t)RFAL_TXRX_FLAGS_PAR_RX_KEEP | (uint32_t)RFAL_TXRX_FLAGS_PAR_TX_AUTO) - -#define FURI_HAL_NFC_TXRX_RAW \ - ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP | \ - (uint32_t)RFAL_TXRX_FLAGS_PAR_RX_KEEP | (uint32_t)RFAL_TXRX_FLAGS_PAR_TX_NONE) - -#define FURI_HAL_NFC_TX_RAW_RX_DEFAULT \ - ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_REMV | \ - (uint32_t)RFAL_TXRX_FLAGS_PAR_RX_REMV | (uint32_t)RFAL_TXRX_FLAGS_PAR_TX_NONE) - -typedef enum { - FuriHalNfcTxRxTypeDefault, - FuriHalNfcTxRxTypeRxNoCrc, - FuriHalNfcTxRxTypeRxKeepPar, - FuriHalNfcTxRxTypeRaw, - FuriHalNfcTxRxTypeRxRaw, - FuriHalNfcTxRxTransparent, -} FuriHalNfcTxRxType; - -typedef bool (*FuriHalNfcEmulateCallback)( - uint8_t* buff_rx, - uint16_t buff_rx_len, - uint8_t* buff_tx, - uint16_t* buff_tx_len, - uint32_t* flags, - void* context); - -typedef enum { - FuriHalNfcTypeA, - FuriHalNfcTypeB, - FuriHalNfcTypeF, - FuriHalNfcTypeV, -} FuriHalNfcType; - -typedef enum { - FuriHalNfcInterfaceRf, - FuriHalNfcInterfaceIsoDep, - FuriHalNfcInterfaceNfcDep, -} FuriHalNfcInterface; - -typedef struct { - FuriHalNfcType type; - FuriHalNfcInterface interface; - uint8_t uid_len; - uint8_t uid[10]; - uint32_t cuid; - uint8_t atqa[2]; - uint8_t sak; -} FuriHalNfcDevData; - -typedef void ( - *FuriHalNfcTxRxSniffCallback)(uint8_t* data, uint16_t bits, bool crc_dropped, void* context); - -typedef struct { - uint8_t tx_data[FURI_HAL_NFC_DATA_BUFF_SIZE]; - uint8_t tx_parity[FURI_HAL_NFC_PARITY_BUFF_SIZE]; - uint16_t tx_bits; - uint8_t rx_data[FURI_HAL_NFC_DATA_BUFF_SIZE]; - uint8_t rx_parity[FURI_HAL_NFC_PARITY_BUFF_SIZE]; - uint16_t rx_bits; - FuriHalNfcTxRxType tx_rx_type; - NfcaSignal* nfca_signal; - - FuriHalNfcTxRxSniffCallback sniff_tx; - FuriHalNfcTxRxSniffCallback sniff_rx; - void* sniff_context; -} FuriHalNfcTxRxContext; - -/** Init nfc - */ -void furi_hal_nfc_init(); - -/** Deinit nfc - */ -void furi_hal_nfc_deinit(); - -/** Check if nfc worker is busy - * - * @return true if busy - */ -bool furi_hal_nfc_is_busy(); - -/** Check if nfc is initialized - * - * @return true if initialized - */ -bool furi_hal_nfc_is_init(); - -/** NFC field on - */ -void furi_hal_nfc_field_on(); - -/** NFC field off - */ -void furi_hal_nfc_field_off(); - -/** NFC start sleep - */ -void furi_hal_nfc_start_sleep(); - -void furi_hal_nfc_stop_cmd(); - -/** NFC stop sleep - */ -void furi_hal_nfc_exit_sleep(); - -/** NFC poll - * - * @param dev_list pointer to rfalNfcDevice buffer - * @param dev_cnt pointer device count - * @param timeout timeout in ms - * @param deactivate deactivate flag - * - * @return true on success - */ -bool furi_hal_nfc_detect(FuriHalNfcDevData* nfc_data, uint32_t timeout); - -/** Activate NFC-A tag - * - * @param timeout timeout in ms - * @param cuid pointer to 32bit uid - * - * @return true on succeess - */ -bool furi_hal_nfc_activate_nfca(uint32_t timeout, uint32_t* cuid); - -/** NFC listen - * - * @param uid pointer to uid buffer - * @param uid_len uid length - * @param atqa pointer to atqa - * @param sak sak - * @param activate_after_sak activate after sak flag - * @param timeout timeout in ms - * - * @return true on success - */ -bool furi_hal_nfc_listen( - uint8_t* uid, - uint8_t uid_len, - uint8_t* atqa, - uint8_t sak, - bool activate_after_sak, - uint32_t timeout); - -/** Start Target Listen mode - * @note RFAL free implementation - * - * @param nfc_data FuriHalNfcDevData instance - */ -void furi_hal_nfc_listen_start(FuriHalNfcDevData* nfc_data); - -/** Read data in Target Listen mode - * @note Must be called only after furi_hal_nfc_listen_start() - * - * @param tx_rx FuriHalNfcTxRxContext instance - * @param timeout_ms timeout im ms - * - * @return true on not empty receive - */ -bool furi_hal_nfc_listen_rx(FuriHalNfcTxRxContext* tx_rx, uint32_t timeout_ms); - -/** Set Target in Sleep state */ -void furi_hal_nfc_listen_sleep(); - -/** Emulate NFC-A Target - * @note RFAL based implementation - * - * @param uid NFC-A UID - * @param uid_len NFC-A UID length - * @param atqa NFC-A ATQA - * @param sak NFC-A SAK - * @param callback FuriHalNfcEmulateCallback instance - * @param context pointer to context for callback - * @param timeout timeout in ms - * - * @return true on success - */ -bool furi_hal_nfc_emulate_nfca( - uint8_t* uid, - uint8_t uid_len, - uint8_t* atqa, - uint8_t sak, - FuriHalNfcEmulateCallback callback, - void* context, - uint32_t timeout); - -/** NFC data exchange - * - * @param tx_rx_ctx FuriHalNfcTxRxContext instance - * - * @return true on success - */ -bool furi_hal_nfc_tx_rx(FuriHalNfcTxRxContext* tx_rx, uint16_t timeout_ms); - -/** NFC data full exhange - * - * @param tx_rx_ctx FuriHalNfcTxRxContext instance - * - * @return true on success - */ -bool furi_hal_nfc_tx_rx_full(FuriHalNfcTxRxContext* tx_rx); - -/** NFC deactivate and start sleep - */ -void furi_hal_nfc_sleep(); - -void furi_hal_nfc_stop(); - -/* Low level transport API, use it to implement your own transport layers */ - -#define furi_hal_nfc_ll_ms2fc rfalConvMsTo1fc - -#define FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_TX_MANUAL RFAL_TXRX_FLAGS_CRC_TX_MANUAL -#define FURI_HAL_NFC_LL_TXRX_FLAGS_AGC_ON RFAL_TXRX_FLAGS_AGC_ON -#define FURI_HAL_NFC_LL_TXRX_FLAGS_PAR_RX_REMV RFAL_TXRX_FLAGS_PAR_RX_REMV -#define FURI_HAL_NFC_LL_TXRX_FLAGS_CRC_RX_KEEP RFAL_TXRX_FLAGS_CRC_RX_KEEP - -typedef enum { - FuriHalNfcReturnOk = 0, /*!< no error occurred */ - FuriHalNfcReturnNomem = 1, /*!< not enough memory to perform the requested operation */ - FuriHalNfcReturnBusy = 2, /*!< device or resource busy */ - FuriHalNfcReturnIo = 3, /*!< generic IO error */ - FuriHalNfcReturnTimeout = 4, /*!< error due to timeout */ - FuriHalNfcReturnRequest = - 5, /*!< invalid request or requested function can't be executed at the moment */ - FuriHalNfcReturnNomsg = 6, /*!< No message of desired type */ - FuriHalNfcReturnParam = 7, /*!< Parameter error */ - FuriHalNfcReturnSystem = 8, /*!< System error */ - FuriHalNfcReturnFraming = 9, /*!< Framing error */ - FuriHalNfcReturnOverrun = 10, /*!< lost one or more received bytes */ - FuriHalNfcReturnProto = 11, /*!< protocol error */ - FuriHalNfcReturnInternal = 12, /*!< Internal Error */ - FuriHalNfcReturnAgain = 13, /*!< Call again */ - FuriHalNfcReturnMemCorrupt = 14, /*!< memory corruption */ - FuriHalNfcReturnNotImplemented = 15, /*!< not implemented */ - FuriHalNfcReturnPcCorrupt = - 16, /*!< Program Counter has been manipulated or spike/noise trigger illegal operation */ - FuriHalNfcReturnSend = 17, /*!< error sending*/ - FuriHalNfcReturnIgnore = 18, /*!< indicates error detected but to be ignored */ - FuriHalNfcReturnSemantic = 19, /*!< indicates error in state machine (unexpected cmd) */ - FuriHalNfcReturnSyntax = 20, /*!< indicates error in state machine (unknown cmd) */ - FuriHalNfcReturnCrc = 21, /*!< crc error */ - FuriHalNfcReturnNotfound = 22, /*!< transponder not found */ - FuriHalNfcReturnNotunique = - 23, /*!< transponder not unique - more than one transponder in field */ - FuriHalNfcReturnNotsupp = 24, /*!< requested operation not supported */ - FuriHalNfcReturnWrite = 25, /*!< write error */ - FuriHalNfcReturnFifo = 26, /*!< fifo over or underflow error */ - FuriHalNfcReturnPar = 27, /*!< parity error */ - FuriHalNfcReturnDone = 28, /*!< transfer has already finished */ - FuriHalNfcReturnRfCollision = - 29, /*!< collision error (Bit Collision or during RF Collision avoidance ) */ - FuriHalNfcReturnHwOverrun = 30, /*!< lost one or more received bytes */ - FuriHalNfcReturnReleaseReq = 31, /*!< device requested release */ - FuriHalNfcReturnSleepReq = 32, /*!< device requested sleep */ - FuriHalNfcReturnWrongState = 33, /*!< incorrent state for requested operation */ - FuriHalNfcReturnMaxReruns = 34, /*!< blocking procedure reached maximum runs */ - FuriHalNfcReturnDisabled = 35, /*!< operation aborted due to disabled configuration */ - FuriHalNfcReturnHwMismatch = 36, /*!< expected hw do not match */ - FuriHalNfcReturnLinkLoss = - 37, /*!< Other device's field didn't behave as expected: turned off by Initiator in Passive mode, or AP2P did not turn on field */ - FuriHalNfcReturnInvalidHandle = 38, /*!< invalid or not initalized device handle */ - FuriHalNfcReturnIncompleteByte = 40, /*!< Incomplete byte rcvd */ - FuriHalNfcReturnIncompleteByte01 = 41, /*!< Incomplete byte rcvd - 1 bit */ - FuriHalNfcReturnIncompleteByte02 = 42, /*!< Incomplete byte rcvd - 2 bit */ - FuriHalNfcReturnIncompleteByte03 = 43, /*!< Incomplete byte rcvd - 3 bit */ - FuriHalNfcReturnIncompleteByte04 = 44, /*!< Incomplete byte rcvd - 4 bit */ - FuriHalNfcReturnIncompleteByte05 = 45, /*!< Incomplete byte rcvd - 5 bit */ - FuriHalNfcReturnIncompleteByte06 = 46, /*!< Incomplete byte rcvd - 6 bit */ - FuriHalNfcReturnIncompleteByte07 = 47, /*!< Incomplete byte rcvd - 7 bit */ -} FuriHalNfcReturn; - -typedef enum { - FuriHalNfcModeNone = 0, /*!< No mode selected/defined */ - FuriHalNfcModePollNfca = 1, /*!< Mode to perform as NFCA (ISO14443A) Poller (PCD) */ - FuriHalNfcModePollNfcaT1t = 2, /*!< Mode to perform as NFCA T1T (Topaz) Poller (PCD) */ - FuriHalNfcModePollNfcb = 3, /*!< Mode to perform as NFCB (ISO14443B) Poller (PCD) */ - FuriHalNfcModePollBPrime = 4, /*!< Mode to perform as B' Calypso (Innovatron) (PCD) */ - FuriHalNfcModePollBCts = 5, /*!< Mode to perform as CTS Poller (PCD) */ - FuriHalNfcModePollNfcf = 6, /*!< Mode to perform as NFCF (FeliCa) Poller (PCD) */ - FuriHalNfcModePollNfcv = 7, /*!< Mode to perform as NFCV (ISO15963) Poller (PCD) */ - FuriHalNfcModePollPicopass = 8, /*!< Mode to perform as PicoPass / iClass Poller (PCD) */ - FuriHalNfcModePollActiveP2p = 9, /*!< Mode to perform as Active P2P (ISO18092) Initiator */ - FuriHalNfcModeListenNfca = 10, /*!< Mode to perform as NFCA (ISO14443A) Listener (PICC) */ - FuriHalNfcModeListenNfcb = 11, /*!< Mode to perform as NFCA (ISO14443B) Listener (PICC) */ - FuriHalNfcModeListenNfcf = 12, /*!< Mode to perform as NFCA (ISO15963) Listener (PICC) */ - FuriHalNfcModeListenActiveP2p = 13 /*!< Mode to perform as Active P2P (ISO18092) Target */ -} FuriHalNfcMode; - -typedef enum { - FuriHalNfcBitrate106 = 0, /*!< Bit Rate 106 kbit/s (fc/128) */ - FuriHalNfcBitrate212 = 1, /*!< Bit Rate 212 kbit/s (fc/64) */ - FuriHalNfcBitrate424 = 2, /*!< Bit Rate 424 kbit/s (fc/32) */ - FuriHalNfcBitrate848 = 3, /*!< Bit Rate 848 kbit/s (fc/16) */ - FuriHalNfcBitrate1695 = 4, /*!< Bit Rate 1695 kbit/s (fc/8) */ - FuriHalNfcBitrate3390 = 5, /*!< Bit Rate 3390 kbit/s (fc/4) */ - FuriHalNfcBitrate6780 = 6, /*!< Bit Rate 6780 kbit/s (fc/2) */ - FuriHalNfcBitrate13560 = 7, /*!< Bit Rate 13560 kbit/s (fc) */ - FuriHalNfcBitrate52p97 = 0xEB, /*!< Bit Rate 52.97 kbit/s (fc/256) Fast Mode VICC->VCD */ - FuriHalNfcBitrate26p48 = - 0xEC, /*!< Bit Rate 26,48 kbit/s (fc/512) NFCV VICC->VCD & VCD->VICC 1of4 */ - FuriHalNfcBitrate1p66 = 0xED, /*!< Bit Rate 1,66 kbit/s (fc/8192) NFCV VCD->VICC 1of256 */ - FuriHalNfcBitrateKeep = 0xFF /*!< Value indicating to keep the same previous bit rate */ -} FuriHalNfcBitrate; - -FuriHalNfcReturn - furi_hal_nfc_ll_set_mode(FuriHalNfcMode mode, FuriHalNfcBitrate txBR, FuriHalNfcBitrate rxBR); - -#define FURI_HAL_NFC_LL_GT_NFCA furi_hal_nfc_ll_ms2fc(5U) /*!< GTA Digital 2.0 6.10.4.1 & B.2 */ -#define FURI_HAL_NFC_LL_GT_NFCB furi_hal_nfc_ll_ms2fc(5U) /*!< GTB Digital 2.0 7.9.4.1 & B.3 */ -#define FURI_HAL_NFC_LL_GT_NFCF furi_hal_nfc_ll_ms2fc(20U) /*!< GTF Digital 2.0 8.7.4.1 & B.4 */ -#define FURI_HAL_NFC_LL_GT_NFCV furi_hal_nfc_ll_ms2fc(5U) /*!< GTV Digital 2.0 9.7.5.1 & B.5 */ -#define FURI_HAL_NFC_LL_GT_PICOPASS furi_hal_nfc_ll_ms2fc(1U) /*!< GT Picopass */ -#define FURI_HAL_NFC_LL_GT_AP2P furi_hal_nfc_ll_ms2fc(5U) /*!< TIRFG Ecma 340 11.1.1 */ -#define FURI_HAL_NFC_LL_GT_AP2P_ADJUSTED \ - furi_hal_nfc_ll_ms2fc( \ - 5U + \ - 25U) /*!< Adjusted GT for greater interoperability (Sony XPERIA P, Nokia N9, Huawei P2) */ - -void furi_hal_nfc_ll_set_guard_time(uint32_t cycles); - -typedef enum { - FuriHalNfcErrorHandlingNone = 0, /*!< No special error handling will be performed */ - FuriHalNfcErrorHandlingNfc = 1, /*!< Error handling set to perform as NFC compliant device */ - FuriHalNfcErrorHandlingEmvco = - 2 /*!< Error handling set to perform as EMVCo compliant device */ -} FuriHalNfcErrorHandling; - -void furi_hal_nfc_ll_set_error_handling(FuriHalNfcErrorHandling eHandling); - -/* RFAL Frame Delay Time (FDT) Listen default values */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_NFCA_POLLER \ - 1172U /*!< FDTA,LISTEN,MIN (n=9) Last bit: Logic "1" - tnn,min/2 Digital 1.1 6.10 ; EMV CCP Spec Book D v2.01 4.8.1.3 */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_NFCB_POLLER \ - 1008U /*!< TR0B,MIN Digital 1.1 7.1.3 & A.3 ; EMV CCP Spec Book D v2.01 4.8.1.3 & Table A.5 */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_NFCF_POLLER \ - 2672U /*!< TR0F,LISTEN,MIN Digital 1.1 8.7.1.1 & A.4 */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_NFCV_POLLER \ - 4310U /*!< FDTV,LISTEN,MIN t1 min Digital 2.1 B.5 ; ISO15693-3 2009 9.1 */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_PICOPASS_POLLER \ - 3400U /*!< ISO15693 t1 min - observed adjustment */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_AP2P_POLLER \ - 64U /*!< FDT AP2P No actual FDTListen is required as fields switch and collision avoidance */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_NFCA_LISTENER 1172U /*!< FDTA,LISTEN,MIN Digital 1.1 6.10 */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_NFCB_LISTENER \ - 1024U /*!< TR0B,MIN Digital 1.1 7.1.3 & A.3 ; EMV CCP Spec Book D v2.01 4.8.1.3 & Table A.5 */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_NFCF_LISTENER \ - 2688U /*!< TR0F,LISTEN,MIN Digital 2.1 8.7.1.1 & B.4 */ -#define FURI_HAL_NFC_LL_FDT_LISTEN_AP2P_LISTENER \ - 64U /*!< FDT AP2P No actual FDTListen exists as fields switch and collision avoidance */ - -void furi_hal_nfc_ll_set_fdt_listen(uint32_t cycles); - -/* RFAL Frame Delay Time (FDT) Poll default values */ -#define FURI_HAL_NFC_LL_FDT_POLL_NFCA_POLLER \ - 6780U /*!< FDTA,POLL,MIN Digital 1.1 6.10.3.1 & A.2 */ -#define FURI_HAL_NFC_LL_FDT_POLL_NFCA_T1T_POLLER \ - 384U /*!< RRDDT1T,MIN,B1 Digital 1.1 10.7.1 & A.5 */ -#define FURI_HAL_NFC_LL_FDT_POLL_NFCB_POLLER \ - 6780U /*!< FDTB,POLL,MIN = TR2B,MIN,DEFAULT Digital 1.1 7.9.3 & A.3 ; EMVCo 3.0 FDTB,PCD,MIN Table A.5 */ -#define FURI_HAL_NFC_LL_FDT_POLL_NFCF_POLLER 6800U /*!< FDTF,POLL,MIN Digital 2.1 8.7.3 & B.4 */ -#define FURI_HAL_NFC_LL_FDT_POLL_NFCV_POLLER 4192U /*!< FDTV,POLL Digital 2.1 9.7.3.1 & B.5 */ -#define FURI_HAL_NFC_LL_FDT_POLL_PICOPASS_POLLER 1790U /*!< FDT Max */ -#define FURI_HAL_NFC_LL_FDT_POLL_AP2P_POLLER \ - 0U /*!< FDT AP2P No actual FDTPoll exists as fields switch and collision avoidance */ - -void furi_hal_nfc_ll_set_fdt_poll(uint32_t FDTPoll); - -void furi_hal_nfc_ll_txrx_on(); - -void furi_hal_nfc_ll_txrx_off(); - -FuriHalNfcReturn furi_hal_nfc_ll_txrx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt); - -FuriHalNfcReturn furi_hal_nfc_ll_txrx_bits( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt); - -void furi_hal_nfc_ll_poll(); - -void furi_hal_nfc_field_detect_start(); - -bool furi_hal_nfc_field_is_present(); - -#ifdef __cplusplus -} -#endif diff --git a/furi/core/base.h b/furi/core/base.h index 29e874192..642ff2b6c 100644 --- a/furi/core/base.h +++ b/furi/core/base.h @@ -2,6 +2,7 @@ #include #include +#include #ifdef __cplusplus extern "C" { diff --git a/furi/core/check.c b/furi/core/check.c index 8888eddfb..b56db6563 100644 --- a/furi/core/check.c +++ b/furi/core/check.c @@ -55,8 +55,6 @@ PLACE_IN_SECTION("MB_MEM2") uint32_t __furi_check_registers[13] = {0}; : "memory"); extern size_t xPortGetTotalHeapSize(void); -extern size_t xPortGetFreeHeapSize(void); -extern size_t xPortGetMinimumEverFreeHeapSize(void); static void __furi_put_uint32_as_text(uint32_t data) { char tmp_str[] = "-2147483648"; @@ -128,7 +126,7 @@ static void __furi_print_name(bool isr) { } } -FURI_NORETURN void __furi_crash() { +FURI_NORETURN void __furi_crash_implementation() { __disable_irq(); GET_MESSAGE_AND_STORE_REGISTERS(); @@ -179,7 +177,7 @@ FURI_NORETURN void __furi_crash() { __builtin_unreachable(); } -FURI_NORETURN void __furi_halt() { +FURI_NORETURN void __furi_halt_implementation() { __disable_irq(); GET_MESSAGE_AND_STORE_REGISTERS(); diff --git a/furi/core/check.h b/furi/core/check.h index 004422e80..2d5df4cf6 100644 --- a/furi/core/check.h +++ b/furi/core/check.h @@ -28,39 +28,51 @@ extern "C" { #define __FURI_CHECK_MESSAGE_FLAG (0x02) /** Crash system */ -FURI_NORETURN void __furi_crash(); +FURI_NORETURN void __furi_crash_implementation(); /** Halt system */ -FURI_NORETURN void __furi_halt(); +FURI_NORETURN void __furi_halt_implementation(); /** Crash system with message. Show message after reboot. */ -#define furi_crash(message) \ +#define __furi_crash(message) \ do { \ register const void* r12 asm("r12") = (void*)message; \ asm volatile("sukima%=:" : : "r"(r12)); \ - __furi_crash(); \ + __furi_crash_implementation(); \ } while(0) +/** Crash system + * + * @param optional message (const char*) + */ +#define furi_crash(...) M_APPLY(__furi_crash, M_IF_EMPTY(__VA_ARGS__)((NULL), (__VA_ARGS__))) + /** Halt system with message. */ -#define furi_halt(message) \ +#define __furi_halt(message) \ do { \ register const void* r12 asm("r12") = (void*)message; \ asm volatile("sukima%=:" : : "r"(r12)); \ - __furi_halt(); \ + __furi_halt_implementation(); \ } while(0) +/** Halt system + * + * @param optional message (const char*) + */ +#define furi_halt(...) M_APPLY(__furi_halt, M_IF_EMPTY(__VA_ARGS__)((NULL), (__VA_ARGS__))) + /** Check condition and crash if check failed */ #define __furi_check(__e, __m) \ do { \ if(!(__e)) { \ - furi_crash(__m); \ + __furi_crash(__m); \ } \ } while(0) /** Check condition and crash if failed * * @param condition to check - * @param optional message + * @param optional message (const char*) */ #define furi_check(...) \ M_APPLY(__furi_check, M_DEFAULT_ARGS(2, (__FURI_CHECK_MESSAGE_FLAG), __VA_ARGS__)) @@ -70,7 +82,7 @@ FURI_NORETURN void __furi_halt(); #define __furi_assert(__e, __m) \ do { \ if(!(__e)) { \ - furi_crash(__m); \ + __furi_crash(__m); \ } \ } while(0) #else @@ -86,7 +98,7 @@ FURI_NORETURN void __furi_halt(); * @warning only will do check if firmware compiled in debug mode * * @param condition to check - * @param optional message + * @param optional message (const char*) */ #define furi_assert(...) \ M_APPLY(__furi_assert, M_DEFAULT_ARGS(2, (__FURI_ASSERT_MESSAGE_FLAG), __VA_ARGS__)) diff --git a/furi/core/common_defines.h b/furi/core/common_defines.h index 5bd218d35..2b30c3b06 100644 --- a/furi/core/common_defines.h +++ b/furi/core/common_defines.h @@ -2,8 +2,6 @@ #include "core_defines.h" #include -#include -#include #ifdef __cplusplus extern "C" { diff --git a/furi/core/critical.c b/furi/core/critical.c index 57fe2403b..3bef2be38 100644 --- a/furi/core/critical.c +++ b/furi/core/critical.c @@ -1,5 +1,8 @@ #include "common_defines.h" +#include +#include + __FuriCriticalInfo __furi_critical_enter(void) { __FuriCriticalInfo info; diff --git a/furi/core/event_flag.c b/furi/core/event_flag.c index 9406a581f..96b959187 100644 --- a/furi/core/event_flag.c +++ b/furi/core/event_flag.c @@ -2,6 +2,7 @@ #include "common_defines.h" #include "check.h" +#include #include #define FURI_EVENT_FLAG_MAX_BITS_EVENT_GROUPS 24U diff --git a/furi/core/kernel.c b/furi/core/kernel.c index 7928ad11c..89a50a9b5 100644 --- a/furi/core/kernel.c +++ b/furi/core/kernel.c @@ -5,6 +5,9 @@ #include +#include +#include + #include CMSIS_device_header bool furi_kernel_is_irq_or_masked() { @@ -31,6 +34,10 @@ bool furi_kernel_is_irq_or_masked() { return (irq); } +bool furi_kernel_is_running() { + return xTaskGetSchedulerState() != taskSCHEDULER_RUNNING; +} + int32_t furi_kernel_lock() { furi_assert(!furi_kernel_is_irq_or_masked()); diff --git a/furi/core/kernel.h b/furi/core/kernel.h index 371f76c1f..c962402ef 100644 --- a/furi/core/kernel.h +++ b/furi/core/kernel.h @@ -27,6 +27,12 @@ extern "C" { */ bool furi_kernel_is_irq_or_masked(); +/** Check if kernel is running + * + * @return true if running, false otherwise + */ +bool furi_kernel_is_running(); + /** Lock kernel, pause process scheduling * * @warning This should never be called in interrupt request context. diff --git a/furi/core/memmgr_heap.c b/furi/core/memmgr_heap.c index 82667debc..826772a67 100644 --- a/furi/core/memmgr_heap.c +++ b/furi/core/memmgr_heap.c @@ -47,8 +47,8 @@ all the API functions to use the MPU wrappers. That should only be done when task.h is included from an application file. */ #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE -#include "FreeRTOS.h" -#include "task.h" +#include +#include #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE diff --git a/furi/core/message_queue.c b/furi/core/message_queue.c index ddf56f006..e20fa420a 100644 --- a/furi/core/message_queue.c +++ b/furi/core/message_queue.c @@ -1,8 +1,9 @@ #include "kernel.h" #include "message_queue.h" +#include "check.h" + #include #include -#include "check.h" FuriMessageQueue* furi_message_queue_alloc(uint32_t msg_count, uint32_t msg_size) { furi_assert((furi_kernel_is_irq_or_masked() == 0U) && (msg_count > 0U) && (msg_size > 0U)); diff --git a/furi/core/mutex.c b/furi/core/mutex.c index 9fb964a1e..8794e10dc 100644 --- a/furi/core/mutex.c +++ b/furi/core/mutex.c @@ -2,6 +2,7 @@ #include "check.h" #include "common_defines.h" +#include #include FuriMutex* furi_mutex_alloc(FuriMutexType type) { diff --git a/furi/core/semaphore.c b/furi/core/semaphore.c index 8c99bfc54..1f1a07780 100644 --- a/furi/core/semaphore.c +++ b/furi/core/semaphore.c @@ -2,6 +2,7 @@ #include "check.h" #include "common_defines.h" +#include #include FuriSemaphore* furi_semaphore_alloc(uint32_t max_count, uint32_t initial_count) { diff --git a/furi/core/stream_buffer.c b/furi/core/stream_buffer.c index bf483948b..a13d256b1 100644 --- a/furi/core/stream_buffer.c +++ b/furi/core/stream_buffer.c @@ -2,6 +2,7 @@ #include "check.h" #include "stream_buffer.h" #include "common_defines.h" + #include #include diff --git a/furi/core/thread.c b/furi/core/thread.c index de50bde7a..db4feeb4e 100644 --- a/furi/core/thread.c +++ b/furi/core/thread.c @@ -7,11 +7,13 @@ #include "mutex.h" #include "string.h" -#include #include "log.h" #include #include +#include +#include + #define TAG "FuriThread" #define THREAD_NOTIFY_INDEX 1 // Index 0 is used for stream buffers diff --git a/furi/core/thread.h b/furi/core/thread.h index 692f2a100..44d66fb21 100644 --- a/furi/core/thread.h +++ b/furi/core/thread.h @@ -8,6 +8,9 @@ #include "base.h" #include "common_defines.h" +#include +#include + #ifdef __cplusplus extern "C" { #endif @@ -28,7 +31,8 @@ typedef enum { FuriThreadPriorityNormal = 16, /**< Normal */ FuriThreadPriorityHigh = 17, /**< High */ FuriThreadPriorityHighest = 18, /**< Highest */ - FuriThreadPriorityIsr = (configMAX_PRIORITIES - 1), /**< Deferred ISR (highest possible) */ + FuriThreadPriorityIsr = + (FURI_CONFIG_THREAD_MAX_PRIORITIES - 1), /**< Deferred ISR (highest possible) */ } FuriThreadPriority; /** FuriThread anonymous structure */ diff --git a/furi/core/timer.c b/furi/core/timer.c index 7743ffe70..17347e5c7 100644 --- a/furi/core/timer.c +++ b/furi/core/timer.c @@ -51,7 +51,7 @@ FuriTimer* furi_timer_alloc(FuriTimerCallback func, FuriTimerType type, void* co callb = (TimerCallback_t*)((uint32_t)callb | 1U); // TimerCallback function is always provided as a callback and is used to call application // specified function with its context both stored in structure callb. - hTimer = xTimerCreate(NULL, 1, reload, callb, TimerCallback); + hTimer = xTimerCreate(NULL, portMAX_DELAY, reload, callb, TimerCallback); furi_check(hTimer); /* Return timer ID */ @@ -83,6 +83,7 @@ void furi_timer_free(FuriTimer* instance) { FuriStatus furi_timer_start(FuriTimer* instance, uint32_t ticks) { furi_assert(!furi_kernel_is_irq_or_masked()); furi_assert(instance); + furi_assert(ticks < portMAX_DELAY); TimerHandle_t hTimer = (TimerHandle_t)instance; FuriStatus stat; @@ -97,6 +98,25 @@ FuriStatus furi_timer_start(FuriTimer* instance, uint32_t ticks) { return (stat); } +FuriStatus furi_timer_restart(FuriTimer* instance, uint32_t ticks) { + furi_assert(!furi_kernel_is_irq_or_masked()); + furi_assert(instance); + furi_assert(ticks < portMAX_DELAY); + + TimerHandle_t hTimer = (TimerHandle_t)instance; + FuriStatus stat; + + if(xTimerChangePeriod(hTimer, ticks, portMAX_DELAY) == pdPASS && + xTimerReset(hTimer, portMAX_DELAY) == pdPASS) { + stat = FuriStatusOk; + } else { + stat = FuriStatusErrorResource; + } + + /* Return execution status */ + return (stat); +} + FuriStatus furi_timer_stop(FuriTimer* instance) { furi_assert(!furi_kernel_is_irq_or_masked()); furi_assert(instance); @@ -125,6 +145,15 @@ uint32_t furi_timer_is_running(FuriTimer* instance) { return (uint32_t)xTimerIsTimerActive(hTimer); } +uint32_t furi_timer_get_expire_time(FuriTimer* instance) { + furi_assert(!furi_kernel_is_irq_or_masked()); + furi_assert(instance); + + TimerHandle_t hTimer = (TimerHandle_t)instance; + + return (uint32_t)xTimerGetExpiryTime(hTimer); +} + void furi_timer_pending_callback(FuriTimerPendigCallback callback, void* context, uint32_t arg) { BaseType_t ret = pdFAIL; if(furi_kernel_is_irq_or_masked()) { @@ -133,4 +162,19 @@ void furi_timer_pending_callback(FuriTimerPendigCallback callback, void* context ret = xTimerPendFunctionCall(callback, context, arg, FuriWaitForever); } furi_check(ret == pdPASS); +} + +void furi_timer_set_thread_priority(FuriTimerThreadPriority priority) { + furi_assert(!furi_kernel_is_irq_or_masked()); + + TaskHandle_t task_handle = xTimerGetTimerDaemonTaskHandle(); + furi_check(task_handle); // Don't call this method before timer task start + + if(priority == FuriTimerThreadPriorityNormal) { + vTaskPrioritySet(task_handle, configTIMER_TASK_PRIORITY); + } else if(priority == FuriTimerThreadPriorityElevated) { + vTaskPrioritySet(task_handle, configMAX_PRIORITIES - 1); + } else { + furi_crash(); + } } \ No newline at end of file diff --git a/furi/core/timer.h b/furi/core/timer.h index 3f43de5fd..d27ef5025 100644 --- a/furi/core/timer.h +++ b/furi/core/timer.h @@ -34,12 +34,21 @@ void furi_timer_free(FuriTimer* instance); /** Start timer * * @param instance The pointer to FuriTimer instance - * @param[in] ticks The ticks + * @param[in] ticks The interval in ticks * * @return The furi status. */ FuriStatus furi_timer_start(FuriTimer* instance, uint32_t ticks); +/** Restart timer with previous timeout value + * + * @param instance The pointer to FuriTimer instance + * @param[in] ticks The interval in ticks + * + * @return The furi status. + */ +FuriStatus furi_timer_restart(FuriTimer* instance, uint32_t ticks); + /** Stop timer * * @param instance The pointer to FuriTimer instance @@ -56,10 +65,29 @@ FuriStatus furi_timer_stop(FuriTimer* instance); */ uint32_t furi_timer_is_running(FuriTimer* instance); +/** Get timer expire time + * + * @param instance The Timer instance + * + * @return expire tick + */ +uint32_t furi_timer_get_expire_time(FuriTimer* instance); + typedef void (*FuriTimerPendigCallback)(void* context, uint32_t arg); void furi_timer_pending_callback(FuriTimerPendigCallback callback, void* context, uint32_t arg); +typedef enum { + FuriTimerThreadPriorityNormal, /**< Lower then other threads */ + FuriTimerThreadPriorityElevated, /**< Same as other threads */ +} FuriTimerThreadPriority; + +/** Set Timer thread priority + * + * @param[in] priority The priority + */ +void furi_timer_set_thread_priority(FuriTimerThreadPriority priority); + #ifdef __cplusplus } #endif diff --git a/furi/flipper.c b/furi/flipper.c index 8806ce27f..b29424a9f 100644 --- a/furi/flipper.c +++ b/furi/flipper.c @@ -5,6 +5,8 @@ #include #include +#include + #define TAG "Flipper" static void flipper_print_version(const char* target, const Version* version) { diff --git a/furi/furi.c b/furi/furi.c index cc0e3f4f1..6247e259f 100644 --- a/furi/furi.c +++ b/furi/furi.c @@ -1,6 +1,8 @@ #include "furi.h" #include -#include "queue.h" + +#include +#include void furi_init() { furi_assert(!furi_kernel_is_irq_or_masked()); diff --git a/furi/furi.h b/furi/furi.h index cfdeb2c0f..422509055 100644 --- a/furi/furi.h +++ b/furi/furi.h @@ -21,8 +21,8 @@ #include -// FreeRTOS timer, REMOVE AFTER REFACTORING -#include +// Workaround for math.h leaking through HAL in older versions +#include #ifdef __cplusplus extern "C" { diff --git a/lib/ReadMe.md b/lib/ReadMe.md index 138bef2b3..326d933aa 100644 --- a/lib/ReadMe.md +++ b/lib/ReadMe.md @@ -2,7 +2,6 @@ - `FreeRTOS-Kernel` - FreeRTOS kernel source code - `FreeRTOS-glue` - Extra glue to hold together FreeRTOS kernel and flipper firmware -- `ST25RFAL002` - ST25R3916 Driver and protocol stack - `app-scened-template` - C++ app library - `callback-connector` - Callback connector library - `cmsis_core` - CMSIS Core package, contain cortex-m core headers diff --git a/lib/SConscript b/lib/SConscript index 907a5a41d..f2cc9d18a 100644 --- a/lib/SConscript +++ b/lib/SConscript @@ -5,11 +5,11 @@ env.Append( Dir("app-scened-template"), Dir("digital_signal"), Dir("pulse_reader"), + Dir("signal_reader"), Dir("drivers"), Dir("flipper_format"), Dir("infrared"), Dir("nfc"), - Dir("ST25RFAL002"), Dir("subghz"), Dir("toolbox"), Dir("u8g2"), @@ -83,7 +83,6 @@ libs = env.BuildModules( "print", "microtar", "toolbox", - "ST25RFAL002", "libusb_stm32", "drivers", "fatfs", @@ -97,6 +96,7 @@ libs = env.BuildModules( "nfc", "digital_signal", "pulse_reader", + "signal_reader", "appframe", "misc", "lfrfid", diff --git a/lib/ST25RFAL002/SConscript b/lib/ST25RFAL002/SConscript deleted file mode 100644 index d86d2d002..000000000 --- a/lib/ST25RFAL002/SConscript +++ /dev/null @@ -1,19 +0,0 @@ -Import("env") - -env.Append( - CPPPATH=[ - "#/lib/ST25RFAL002", - "#/lib/ST25RFAL002/include", - "#/lib/ST25RFAL002/source/st25r3916", - ], -) - - -libenv = env.Clone(FW_LIB_NAME="st25rfal002") -libenv.ApplyLibFlags() - -sources = libenv.GlobRecursive("*.c") - -lib = libenv.StaticLibrary("${FW_LIB_NAME}", sources) -libenv.Install("${LIB_DIST_DIR}", lib) -Return("lib") diff --git a/lib/ST25RFAL002/doc/Release_Notes.html b/lib/ST25RFAL002/doc/Release_Notes.html deleted file mode 100755 index 28d501c09..000000000 --- a/lib/ST25RFAL002/doc/Release_Notes.html +++ /dev/null @@ -1,354 +0,0 @@ - - - - - - - - - - - - - Release Notes for RFAL Library - - - - - - - - - -
-


-

-
- - - - - - -
- - - - - - - - - -

-
-

Release -Notes for RFAL software Library

-

Copyright -2019 STMicroelectronics

-

-
-

 

- - - - - - -

-
The RFAL Library -(RF Abstraction Layer) provides several functionalities required to perform RF/NFC communications. -The RFAL encapsulates the different RF ICs (ST25R3911, ST25R3916, ST25R95 and future ST25R devices) into a common and easy to use interface.
-
- The technologies currently supported by RFAL are: -
    -
  • NFC-A \ ISO14443A (T1T, T2T, T4TA)
  • -
  • NFC-B \ ISO14443B (T4TB)
  • -
  • NFC-F \ FeliCa (T3T)
  • -
  • NFC-V \ ISO15693 (T5T)
  • -
  • P2P \ ISO18092 (NFCIP1, Passive-Active P2P)
  • -
  • ST25TB (ISO14443-2 Type B with Proprietary Protocol)
  • -
  • PicoPass \ iClass
  • -
  • B' \ Calypso
  • -
  • CTS \ CTM
  • -
-

- The protocols provided by RFAL are: -
    -
  • ISO-DEP (ISO14443-4)
  • -
  • NFC-DEP (ISO18092)
  • -
-
-
-
    -
- -

Update History

-
- -

V2.2.0 / 22-May-2020

-

-

Main Changes

-
    -
  • Better alignment to NFC Forum latest requirements (CR12)
  • -
  • Extended NFC-V module with non-addressed mode support and improved aticollision
  • -
  • Feature Switches changed to be not mandatory. Modules disabled by default
  • -
  • Aligned APIs on platform.h (breaks compatibility with previous versions, see example in rfal.chm)
  • -
  • Added API for release/deletion of timers
  • -
  • ST25R3916 default analog table modified to X-NUCLEO-NFC06A1 board
  • -
  • Improved AP2P operation
  • -
  • Fixed issues introduced on previous release linked to SFGT and anticollision retries
  • -
  • Introduced Low-Power mode
  • -
  • Several driver improvements
  • -
-
- -

V2.1.2 / 27-Jan-2020

-

-

Main Changes

-
    -
  • Extended ISO-DEP and NFC-A module to support non-blocking activation interfaces
  • -
  • Extended NFC/HL module to make use of the new APIs further splitting the execution of the worker during the different activities
  • -
  • Modified NFC-A anticollision to strictly comply to NFC Forum DP. A separate proprietary method is now available.
  • -
  • NFC-V changed to use OOK (100% AM) by default
  • -
  • Fixed FWT used by NFC-V Sleep
  • -
  • Fixed NFC-F FDT Poll value
  • -
  • Fixed incorrect register access on ST25R3911B RFO Get/Set method
  • -
  • SPI driver modified to clear Rx buffer prior to operation
  • -
  • Added further code size optimizations based on enabled features
  • -
  • Updated ST25R3916 driver to DS Rev2
  • -
  • Updated SW Tag Detection as describded in AN Rev3
  • -
  • Several driver improvements
  • -
-
- -

V2.1.0 / 30-Sep-2019

-

-

Main Changes

-
    -
  • Extended RFAL NFC Higher Layer for increased functionality and configurations
  • -
  • Several improvements on the ISO-DEP protocol layer
  • -
  • Protocol buffer sizes made fully configurable for increased memory management
  • -
  • Introduced option for Collision Avoidance with Automatic Gain Control
  • -
  • Several driver improvements
  • -
  • ST25R3916 overheat protection disabled
  • -
  • RF Transceive modified for transmission errors to precede other errors
  • -
  • Analog Configs extended to support different DPO power levels
  • -
-
- -

V2.0.10 / 25-Jun-2019

-

-

Main Changes

-
    -
  • Various improvements on RFAL NFC Higher layer
  • -
  • Added alternative NFC-V anticollision method (non NFC Forum compliant)
  • -
  • Several minor improvements and fixes
  • -
-
- -

V2.0.6 / 10-Apr-2019

-

-

Main Changes

-
    -
  • Several NFC-V interoperability improvements
  • -
  • Extended support for specific features of ST's ISO15693 Tags. New ST25Dx module added
  • -
  • Interrupt handling changed and further protection added
  • -
  • RFAL feature switches have been modified and features are now disabled if omitted
  • -
  • ST25R3916 AAT (Automatic Antenna Tuning) module added
  • -
  • RFAL NFC Higher layer added
  • -
  • Several driver improvements
  • -
-
- -

V2.0.4 / 06-Fev-2019

-

Provided with ST25R3916 DISCO v1.0.0 / EMVCo v1.2.0

-

Main Changes

-
    -
  • Minor improvements on NFC-F module
  • -
  • Several improvements on NFC-V module including support for ST proprietary features
  • -
  • Fixed issue with Delta RWT calculation
  • -
  • Fixed incorrect usage of NFCB dTbPoll / DdFWT
  • -
  • Added compile switch for Listen Mode
  • -
  • Low power Listen Mode support added
  • -
  • Listen Mode aligned to NFC Forum Digital 2.1
  • -
  • Added handling for EMVCo 3.0 static FDTListen
  • -
  • Introduced SW Tag Detection
  • -
-
- -

V2.0.2 / 31-Oct-2018

-

Provided with ST25R3916 DISCO v0.9.4 (binary only)

-

Main Changes

-
    -
  • New T4T module added
  • -
  • Added support for T3T Check and Update commands
  • -
  • Improved NFC-V module and added Write Multiple Blocks support
  • -
  • New rfalWorker protection added for improved control in multi-thread environments
  • -
  • Added support for user defined Analog Config tables
  • -
  • Several driver improvements and protections added
  • -
-
- -

V2.0.0 / 28-Aug-2018

- -

Main Changes

-
    -
  • MISRA C 2012 compliant
  • -
  • ST25R3916 support added
  • -
  • ST25R95 support added
  • -
  • Fix unwanted Field Detector disable when entering Wake-up mode
  • -
  • Extended Analog Config to have specific events
  • -
  • Fixed NFC-DEP potential issue if DID used
  • -
  • Extended NFC-V commands
  • -
  • T2T module added
  • -
  • Improved initial Listen mode handling
  • -
  • Extended Wake-Up mode to support Capacitive measurement
  • -
-
- -

V1.3.6 / 08-May-2018

-

Provided with ST25R3911B DISCO v1.2.0

-

Main Changes

-
    -
  • Added ISO15693 x4 and x8 mode support
  • -
  • Added S(PARAMETERS) support
  • -
  • Interface changes for measurement, Wake-Up and DPO methods
  • -
  • Added further feature switches to enable/disable individual modules
  • -
  • Changed communication protection
  • -
  • Improved NFC-A anti-collision
  • -
  • Several driver improvements
  • -
-
-

V1.3.4 / 07-May-2018

- -

Main Changes

-
    -
  • Fixed NFC-V Read operation in addressed mode
  • -
-
-

V1.3.2 / 31-January-2018

- -

Main Changes

-
    -
  • Modified Wake-Up mode interface
  • -
  • Fixed SFGI calculation in ISO-DEP
  • -
-
-

V1.3.0 / 22-January-2018

- -

Main Changes

-
    -
  • Introduced a new IRQ status handling to read the registers only once
  • -
  • Several changes for supporting Linux platform
  • -
  • SPI Select/Deselect moved to platform.h
  • -
  • Additional protection of the IRQ status reading, new macros available: platformProtectST25R391xIrqStatus / platformUnprotectST25R391xIrqStatus
  • -
  • Renamed the IRQ Enable/Disable macros to platformProtectST25R391xComm / platformUnprotectST25R391xComm
  • -
  • Renamed SPI pins from chip specific to ST25R391X
  • -
  • Introduced a new option ST25R391X_COM_SINGLETXRX which executes SPI in one single exchange (additional buffer required)
  • -
  • Updated and added errata handlings to latest ST25R3911 Errata version
  • -
  • Fixed inconsistency on Analog settings for NFC-V
  • -
  • Fixed issue on NFC-V 1of256 decoding
  • -
  • Changed the default NFC-A FDT Listen to be more strict
  • -
  • Added Wake-Up mode support
  • -
  • Added RFAL version definition
  • -
-
-

V1.2.0 / 17-August-2017

-

Provided with ST25R3911B Disco v1.1.16

-

Main Changes

-
    -
  • Aligned Technology modules to NFC Activity v1.1 and EMVCo v2.6
  • -
  • Extended NFC-B Collision Resolution allowing user define Slots
  • -
  • Added feature switches to enable/disable individual modules
  • -
  • ISO-DEP Interface changes allowing more user configurations and further EMVCo alignment
  • -
  • Changed ST25TB detection to always perform Anti Collision loop regardeless of the result of the Poll
  • -
  • Fixed FIFO WL handling
  • -
  • Modified FDT Poll handling
  • -
  • changed rfalCalibrate() to not overwrite dynamic configs
  • -
  • Added adjustment for TR1PUTMIN
  • -
- -
-

V1.1.0 / 30-June-2017

-

Provided with ST25R3911B Disco v1.1.12

-

Main Changes

-
    -
  • EMD suppression enabled for ST25R3911B
  • -
- -
-

V1.0.0 / 16-May-2017

-

Provided with X-NUCLEO-NFC05A1 v1.0.0

-

Main Changes

-
    -
  • Added support for B', CTS and PicoPass/iClass mode
  • -
  • Several impromvements for NFC-V mode
  • -
  • Improved error detection during NFC-B collision resolution
  • -
  • Extended T1T module
  • -
- -
-

V0.9.0 / 02-March-2017

-

Provided with ST25R3911B Discovery Kit on Embedded World Conference (binary only)

-

Main Changes

- -
- -
-

-
-
-

 

-
- diff --git a/lib/ST25RFAL002/doc/ST25R3916_MisraComplianceReport.html b/lib/ST25RFAL002/doc/ST25R3916_MisraComplianceReport.html deleted file mode 100755 index e4ffaa933..000000000 --- a/lib/ST25RFAL002/doc/ST25R3916_MisraComplianceReport.html +++ /dev/null @@ -1,8867 +0,0 @@ - - - - - -PRQA GEP/GCS/GRP Report - - - - -
-
-
-
-
- -This section targets to provide an overview of Guidelines Enforcement Plan (GEP).
-
-This document will only focus on STMicroelectronics NFC RF Abstraction Layer (RFAL).
-
-The project has been designed to comply with the standard ISO/IEC 9899:1999 ([C99]). -
-
-

1. Tools version

-The tool used for MISRA compliance is:
-
-PRQA Framework - v2.2.2
-

-It is composed of the following subcomponents: -

-
    -
  • Component: qacpp

  • -
      Version: 4.2.0
    -
      Target: C++
    -
  • Component: rcma

  • -
      Version: 1.6.0
    -
      Target: C_CPP
    -
  • Component: m3cm

  • -
      Version: 2.3.1
    -
      Target: C
    -
  • Component: qac

  • -
      Version: 9.3.1
    -
      Target: C
    -
      -
    • Options:
    • -
        -d : __schedule_barrier=_ignore_semi
      -
        -namelength : 63
      -
    -
-

2. Configuration

-This section targets to provide the main configuration options used for MISRA compliance.
-
-The project complies to [C99],
-the variables length has been consequently set to a dedicated value (cf 'namelength' option in table above). -
-
-Repository/components:
-
    -
  • MCU target:
  • -
      STM32

    -
  • Parent repository:
  • -
      ST25R3916_nucleo

    -
  • RFAL information:
  • -
      Path: .../ST25R3916_nucleo/rfal
    -
      Version: v2.1.2
    -
  • Project repositories SHA1:
  • -
      .../ST25R3916_nucleo: 959b80e
    -
      .../ST25R3916_nucleo/common: 09bc5ef
    -
      .../ST25R3916_nucleo/nucleo: 22a04ae
    -
      .../ST25R3916_nucleo/rfal: f08099c
    -
    -
-

3. Assistance/Enforcement

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GuidelineCategoryDescriptionAssistance/Enforcement Sub Rules
Dir-1.1RequiredAny implementation-defined behaviour on which the output of the program depends shall be documented and understood
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
0202 [I] '-' character in '[]' conversion specification is implementation defined.
0284 [I] Multiple character constants have implementation defined values.
0285 [I] Character constant contains character which is not a member of the basic source character set.
0286 [I] String literal contains character which is not a member of the basic source character set.
0287 [I] Header name contains character which is not a member of the basic source character set.
0288 [I] Source file '%s' has comments containing characters which are not members of the basic source character set.
0289 [I] Source file '%s' has preprocessing tokens containing characters which are not members of the basic source character set.
0292 [I] Source file '%s' has comments containing one of the characters '$', '@' or '`'.
0299 [I] Source file '%s' includes #pragma directives containing characters which are not members of the basic source character set.
0314 [I] Cast from a pointer to object type to a pointer to void.
0315 [I] Implicit conversion from a pointer to object type to a pointer to void.
0371 [L] Nesting levels of blocks exceeds 127 - program does not conform strictly to ISO:C99.
0372 [L] More than 63 levels of nested conditional inclusion - program does not conform strictly to ISO:C99.
0375 [L] Nesting of parenthesized expressions exceeds 63 - program does not conform strictly to ISO:C99.
0380 [L] Number of macro definitions exceeds 4095 - program does not conform strictly to ISO:C99.
0388 [L] '#include "%s"' causes nesting to exceed 15 levels - program does not conform strictly to ISO:C99.
0390 [L] Number of members in 'struct' or 'union' exceeds 1023 - program does not conform strictly to ISO:C99.
0391 [L] Number of enumeration constants exceeds 1023 - program does not conform strictly to ISO:C99.
0392 [L] Nesting of 'struct' or 'union' types exceeds 63 - program does not conform strictly to ISO:C99.
0581 [I] Floating-point constant may be too small to be representable.
0634 [I] Bit-fields in this struct/union have not been declared explicitly as unsigned or signed.
2850 Constant: Implicit conversion to a signed integer type of insufficient size.
2851 Definite: Implicit conversion to a signed integer type of insufficient size.
2852 Apparent: Implicit conversion to a signed integer type of insufficient size.
2855 Constant: Casting to a signed integer type of insufficient size.
2856 Definite: Casting to a signed integer type of insufficient size.
2857 Apparent: Casting to a signed integer type of insufficient size.
2860 Constant: Implementation-defined value resulting from left shift operation on expression of signed type.
2861 Definite: Implementation-defined value resulting from left shift operation on expression of signed type.
2862 Apparent: Implementation-defined value resulting from left shift operation on expression of signed type.
2895 Constant: Negative value cast to an unsigned type.
2896 Definite: Negative value cast to an unsigned type.
2897 Apparent: Negative value cast to an unsigned type.
3116 Unrecognized #pragma arguments '%s' This #pragma directive has been ignored.
-
Dir-2.1RequiredAll source files shall compile without any compilation errorsUnassisted

-Remarks:
-Dedicated checks deployed in Jenkins.
Dir-3.1RequiredAll code shall be traceable to documented requirementsUnassisted

-Remarks:
-Limited management of requirements.
Dir-4.1RequiredRun-time failures shall be minimized
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
2791 Definite: Right hand operand of shift operator is negative or too large.
2792 Apparent: Right hand operand of shift operator is negative or too large.
2801 Definite: Overflow in signed arithmetic operation.
2802 Apparent: Overflow in signed arithmetic operation.
2811 Definite: Dereference of NULL pointer.
2812 Apparent: Dereference of NULL pointer.
2821 Definite: Arithmetic operation on NULL pointer.
2822 Apparent: Arithmetic operation on NULL pointer.
2831 Definite: Division by zero.
2832 Apparent: Division by zero.
2841 Definite: Dereference of an invalid pointer value.
2842 Apparent: Dereference of an invalid pointer value.
2845 Constant: Maximum number of characters to be written is larger than the target buffer size.
2846 Definite: Maximum number of characters to be written is larger than the target buffer size.
2847 Apparent: Maximum number of characters to be written is larger than the target buffer size.
2871 Infinite loop identified.
2872 This loop, if entered, will never terminate.
2877 This loop will never be executed more than once.
-
Dir-4.10RequiredPrecautions shall be taken in order to prevent the contents of a header file being included more then once
- - - - - -
QacDescription
0883 Include file code is not protected against repeated inclusion
-
Dir-4.11RequiredThe validity of values passed to library functions shall be checkedUnassisted

-Remarks:
-No automated check deployed.
-Manual checks done by developers.
Dir-4.12RequiredDynamic memory allocation shall not be usedUnassisted

-Remarks:
-No memory allocation functions (malloc(), calloc(), realloc()) being called in RFAL.
Dir-4.13AdvisoryFunctions which are designed to provide operations on a resource should be called in an appropriate sequenceUnassisted
Dir-4.14RequiredThe validity of values received from external sources shall be checked
- - - - - -
QacDescription
2956 Definite: Using object '%s' with tainted value.
-
Dir-4.2AdvisoryAll usage of assembly language should be documented
- - - - - - - - - -
QacDescription
1003 [E] '#%s' is a language extension for in-line assembler. All statements located between #asm and #endasm will be ignored.
1006 [E] This in-line assembler construct is a language extension. The code has been ignored.
-
Dir-4.3RequiredAssembly language shall be encapsulated and isolated
- - - - - - - - - -
QacDescription
3006 This function contains a mixture of in-line assembler statements and C statements.
3008 This function contains a mixture of in-line assembler statements and C code.
-
Dir-4.4AdvisorySections of code should not be "commented out"Unassisted
Dir-4.5AdvisoryIdentifiers in the same name space with overlapping visibility should be typographically unambiguousUnassisted
Dir-4.6Advisorytypedefs that indicate size and signedness should be used in place of the basic numerical types
- - - - - -
QacDescription
5209 Use of basic type '%s'.
-
Dir-4.7RequiredIf a function returns error information, then that error information shall be testedUnassisted

-Remarks:
-Dir-4.7 is similar to Rule-17.7 which is currently dismissed.
-This directive is consequently considered as disapplied.
Dir-4.8AdvisoryIf a pointer to a structure or union is never dereferenced within a translation unit, then the implementation of the object should be hiddenUnassisted
Dir-4.9AdvisoryA function should be used in preference to a function-like macro where they are interchangeable
- - - - - -
QacDescription
3453 A function could probably be used instead of this function-like macro.
-
Rule-1.1RequiredThe program shall contain no violations of the standard C syntax and constraints, and shall not exceed the implementation's translation limits
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
0232 [C] Value of hex escape sequence is not representable in type 'unsigned char'.
0233 [C] Value of octal escape sequence is not representable in type 'unsigned char'.
0244 [C] Value of character constant is not representable in type 'int'.
0268 [S] Comment open at end of translation unit.
0321 [C] Declaration within 'for' statement defines an identifier '%s' which is not an object.
0322 [C] Illegal storage class specifier used in 'for' statement declaration.
0338 [C] Octal or hex escape sequence value is too large for 'unsigned char' or 'wchar_t' type.
0422 [C] Function call contains fewer arguments than prototype specifies.
0423 [C] Function call contains more arguments than prototype specifies.
0426 [C] Called function has incomplete return type.
0427 [C] Object identifier used as if it were a function or a function pointer identifier.
0429 [C] Function argument is not of arithmetic type.
0430 [C] Function argument is not of compatible 'struct'/'union' type.
0431 [C] Function argument points to a more heavily qualified type.
0432 [C] Function argument is not of compatible pointer type.
0435 [C] The 'struct'/'union' member '%s' does not exist.
0436 [C] Left operand of '.' must be a 'struct' or 'union' object.
0437 [C] Left operand of '->' must be a pointer to a 'struct' or 'union' object.
0446 [C] Operand of ++/-- must have scalar (arithmetic or pointer) type.
0447 [C] Operand of ++/-- must be a modifiable object.
0448 [C] Operand of ++/-- must not be a pointer to an object of unknown size.
0449 [C] Operand of ++/-- must not be a pointer to a function.
0450 [C] An expression of array type cannot be cast.
0451 [C] Subscripting requires a pointer (or array lvalue).
0452 [C] Cannot subscript a pointer to an object of unknown size.
0453 [C] An array subscript must have integral type.
0454 [C] The address-of operator '&' cannot be applied to an object declared with 'register'.
0456 [C] This expression does not have an address - '&' may only be applied to an lvalue or a function designator.
0457 [C] The address-of operator '&' cannot be applied to a bit-field.
0458 [C] Indirection operator '*' requires operand of pointer type.
0460 [C] The keyword static is used in the declaration of the index of an array which is not a function parameter.
0461 [C] The keyword static is used in the declaration of an inner index of a multi-dimensional array.
0462 [C] A type qualifier (const, volatile or restrict) is used in the declaration of the index of an array which is not a function parameter.
0463 [C] A type qualifier (const, volatile or restrict) is used in the declaration of an inner index of a multi-dimensional array.
0466 [C] Unary '+' requires arithmetic operand.
0467 [C] Operand of '!' must have scalar (arithmetic or pointer) type.
0468 [C] Unary '-' requires arithmetic operand.
0469 [C] Bitwise not '~' requires integral operand.
0476 [C] 'sizeof' cannot be applied to a bit-field.
0477 [C] 'sizeof' cannot be applied to a function.
0478 [C] 'sizeof' cannot be applied to an object of unknown size.
0481 [C] Only scalar expressions may be cast to other types.
0482 [C] Expressions may only be cast to 'void' or scalar types.
0483 [C] A pointer to an object of unknown size cannot be the operand of an addition operator.
0484 [C] A pointer to an object of unknown size cannot be the operand of a subtraction operator.
0485 [C] Only integral expressions may be added to pointers.
0486 [C] Only integral expressions and compatible pointers may be subtracted from pointers.
0487 [C] If two pointers are subtracted, they must be pointers that address compatible types.
0493 [C] Type of left operand is not compatible with this operator.
0494 [C] Type of right operand is not compatible with this operator.
0495 [C] Left operand of '%', '<<', '>>', '&', '^' or '|' must have integral type.
0496 [C] Right operand of '%', '<<', '>>', '&', '^' or '|' must have integral type.
0513 [C] Relational operator used to compare pointers to incompatible types.
0514 [C] Relational operator used to compare a pointer with an incompatible operand.
0515 [C] Equality operator used to compare a pointer with an incompatible operand.
0536 [C] First operand of '&&', '||' or '?' must have scalar (arithmetic or pointer) type.
0537 [C] Second operand of '&&' or '||' must have scalar (arithmetic or pointer) type.
0540 [C] 2nd and 3rd operands of conditional operator '?' must have compatible types.
0541 [C] Argument no. %s does not have object type.
0542 [C] Controlling expression must have scalar (arithmetic or pointer) type.
0546 [C] 'enum %s' has unknown content. Use of an enum tag with undefined content is not permitted.
0547 [C] This declaration of tag '%s' conflicts with a previous declaration.
0550 [C] Left operand of '+=' or '-=' is a pointer to an object of unknown size.
0554 [C] 'static %s()' has been declared and called but no definition has been given.
0555 [C] Invalid assignment to object of void type or array type.
0556 [C] Left operand of assignment must be a modifiable object.
0557 [C] Right operand of assignment is not of arithmetic type.
0558 [C] Right operand of '+=' or '-=' must have integral type when left operand is a pointer.
0559 [C] Right operand of '<<=', '>>=', '&=', '|=', '^=' or '%=' must have integral type.
0560 [C] Left operand of '<<=', '>>=', '&=', '|=', '^=' or '%=' must have integral type.
0561 [C] Right operand of assignment is not of compatible 'struct'/'union' type.
0562 [C] Right operand of assignment points to a more heavily qualified type.
0563 [C] Right operand of assignment is not of compatible pointer type.
0564 [C] Left operand of assignment must be an lvalue (it must designate an object).
0565 [C] Left operand of '+=' or '-=' must be of arithmetic or pointer to object type.
0580 [C] Constant is too large to be representable.
0588 [C] Width of bit-field must be an integral constant expression.
0589 [C] Enumeration constant must be an integral constant expression.
0590 [C] Array bound must be an integral constant expression.
0591 [C] A 'case' label must be an integral constant expression.
0605 [C] A declaration must declare a tag or an identifier.
0616 [C] Illegal combination of type specifiers or storage class specifiers.
0619 [C] The identifier '%s' has already been defined in the current scope within the ordinary identifier namespace.
0620 [C] Cannot initialize '%s' because it has unknown size.
0621 [C] The struct/union '%s' cannot be initialized because it has unknown size.
0622 [C] The identifier '%s' has been declared both with and without linkage in the same scope.
0627 [C] '%s' has different type to previous declaration in the same scope.
0628 [C] '%s' has different type to previous declaration at wider scope.
0629 [C] More than one definition of '%s' (with internal linkage).
0631 [C] More than one declaration of '%s' (with no linkage).
0638 [C] Duplicate member name '%s' in 'struct' or 'union'.
0640 [C] '%s' in 'struct' or 'union' type may not have 'void' type.
0641 [C] '%s' in 'struct' or 'union' type may not have function type.
0642 [C] '%s' in 'struct' or 'union' type may not be an array of unknown size.
0643 [C] '%s' in 'struct' or 'union' type may not be a 'struct' or 'union' with unknown content.
0644 [C] Width of bit-field must be no bigger than the width of an 'int'.
0645 [C] A zero width bit-field cannot be given a name.
0646 [C] Enumeration constants must have values representable as 'int's.
0649 [C] K&R style declaration of parameters is not legal after a function header that includes a parameter list.
0650 [C] Illegal storage class specifier on named function parameter.
0651 [C] Missing type specifiers in function declaration.
0653 [C] Duplicate definition of 'struct', 'union' or 'enum' tag '%s'.
0655 [C] Illegal storage class specifier on unnamed function parameter.
0656 [C] Function return type cannot be function or array type, or an incomplete struct/union (for function definition).
0657 [C] Unnamed parameter specified in function definition.
0659 [C] The identifier '%s' was not given in the parameter list.
0664 [C] Parameter specified with type 'void'.
0665 [C] Two parameters have been declared with the same name '%s'.
0669 [C] The restrict qualifier can only be applied to pointer types derived from object or incomplete types.
0671 [C] Initializer for object of arithmetic type is not of arithmetic type.
0673 [C] Initializer points to a more heavily qualified type.
0674 [C] Initializer for pointer is of incompatible type.
0675 [C] Initializer is not of compatible 'struct'/'union' type.
0677 [C] Array size is negative, or unrepresentable.
0682 [C] Initializer for object of a character type is a string literal.
0683 [C] Initializer for object of a character type is a wide string literal.
0684 [C] Too many initializers.
0685 [C] Initializer for any object with static storage duration must be a constant expression.
0690 [C] String literal contains too many characters to initialize object.
0698 [C] String literal used to initialize an object of incompatible type.
0699 [C] String literal used to initialize a pointer of incompatible type.
0708 [C] No definition found for the label '%s' in this function.
0709 [C] Initialization of locally declared 'extern %s' is illegal.
0736 [C] 'case' label does not have unique value within this 'switch' statement.
0737 [C] More than one 'default' label found in 'switch' statement.
0738 [C] Controlling expression in a 'switch' statement must have integral type.
0746 [C] 'return exp;' found in '%s()' whose return type is 'void'.
0747 [C] 'return exp;' found in '%s()' whose return type is qualified 'void'.
0755 [C] 'return' expression is not of arithmetic type.
0756 [C] 'return' expression is not of compatible 'struct'/'union' type.
0757 [C] 'return' expression points to a more heavily qualified type.
0758 [C] 'return' expression is not of compatible pointer type.
0766 [C] 'continue' statement found outside an iteration statement.
0767 [C] 'break' statement found outside a 'switch' or iteration statement.
0768 [C] 'case' or 'default' found outside a 'switch' statement.
0774 [C] 'auto' may not be specified on global declaration of '%s'.
0775 [C] 'register' may not be specified on global declaration of '%s'.
0801 [C] The '##' operator may not be the first token in a macro replacement list.
0802 [C] The '##' operator may not be the last token in a macro replacement list.
0803 [C] The '#' operator may only appear before a macro parameter.
0804 [C] Macro parameter '%s' is not unique.
0811 [C] The glue operator '##' may only appear in a '#define' preprocessing directive.
0812 [C] Header name token '' found outside '#include' preprocessing directive.
0817 [S] Closing quote or bracket '>' missing from include filename.
0818 [Q] Cannot find '%s' - Perhaps the appropriate search path was not given ?
0821 [C] '#include' does not identify a header or source file that can be processed.
0834 [C] Function-like macro '%s()' is being redefined as an object-like macro.
0835 [C] Macro '%s' is being redefined with different parameter names.
0844 [C] Macro '%s' is being redefined with a different replacement list.
0845 [C] Object-like macro '%s' is being redefined as a function-like macro.
0851 [C] More arguments in macro call than specified in definition.
0852 [S] Unable to find the ')' that marks the end of the macro call.
0866 [C] The string literal in a '#line' directive cannot be a 'wide string literal'.
0873 [C] Preprocessing token cannot be converted to an actual token.
0877 [C] '#if' and '#elif' expressions may contain only integral constants.
0940 [C] Illegal usage of a variably modified type.
0941 [C] A variable length array may not be initialized.
0943 [C] Jump to label '%s' is a jump into the scope of an identifier with variably modified type.
0944 [C] The label '%s' is inside the scope of an identifier with variably modified type.
1023 [C] Using '__alignof__' on function types is illegal.
1024 [C] Using '__alignof__' on incomplete types is illegal.
1025 [C] Using '__alignof__' on bit-fields is illegal.
1033 [C] The identifier __VA_ARGS__ may only be used in the replacement list of a variadic macro.
1047 [C] Function is being declared with default argument syntax after a previous call to the function. This is not allowed.
1048 [C] Default argument values are missing for some parameters in this function declaration. This is not allowed.
1050 [C] Nested functions cannot be 'extern' or 'static'.
1061 [C] Structure '%1s' with flexible array member '%2s' cannot be used in the declaration of structure member '%3s'.
1062 [C] Structure '%1s' with flexible array member '%2s' cannot be used in the declaration of array elements.
3236 [C] 'inline' may not be applied to function 'main'.
3237 [C] inline function '%1s' has external linkage and is defining an object, '%2s', with static storage duration.
3238 [C] inline function '%1s' has external linkage and is referring to an object, '%2s', with internal linkage.
3244 [C] 'inline' may only be used in the declaration of a function identifier.
-
Rule-1.2AdvisoryLanguage extensions should not be used
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
0240 [E] This file contains the control-M character at the end of a line.
0241 [E] This file contains the control-Z character - was this transferred from a PC?
0246 [E] Binary integer constants are a language extension.
0551 [E] Cast may not operate on the left operand of the assignment operator.
0601 [E] Function 'main()' is not of type 'int (void)' or 'int (int, char *[])'.
0633 [E] Empty structures and unions are a language extension.
0635 [E] Bit-fields in this struct/union have been declared with types other than int, signed int, unsigned int or _Bool.
0660 [E] Defining an unnamed member in a struct or union. This is a language extension.
0662 [E] Accessing a member of an unnamed struct or union member in this way is a language extension.
0830 [E] Unrecognized text encountered after a preprocessing directive.
0831 [E] Use of '\\' in this '#include' line is a PC extension - this usage is non-portable.
0840 [E] Extra tokens at end of #include directive.
0883 Include file code is not protected against repeated inclusion
0899 [E] Unrecognized preprocessing directive has been ignored - assumed to be a language extension.
0981 [E] Redundant semicolon in 'struct' or 'union' member declaration list is a language extension.
1001 [E] '#include %s' is a VMS extension.
1002 [E] '%s' is not a legal identifier in ISO C.
1003 [E] '#%s' is a language extension for in-line assembler. All statements located between #asm and #endasm will be ignored.
1006 [E] This in-line assembler construct is a language extension. The code has been ignored.
1008 [E] '#%s' is not a legal ISO C preprocessing directive.
1012 [E] Use of a C++ reference type ('type &') will be treated as a language extension.
1014 [E] Non-standard type specifier - this will be treated as a language extension.
1015 [E] '%s' is not a legal keyword in ISO C - this will be treated as a language extension.
1019 [E] '@ address' is not supported in ISO C - this will be treated as a language extension.
1020 [E] '__typeof__' is not supported in ISO C, and is treated as a language extension.
1021 [E] A statement expression is not supported in ISO C, and is treated as a language extension.
1022 [E] '__alignof__' is not supported in ISO C, and is treated as a language extension.
1026 [E] The indicated @word construct has been ignored.
1028 [E] Use of the sizeof operator in a preprocessing directive is a language extension.
1029 [E] Whitespace encountered between backslash and new-line has been ignored.
1034 [E] Macro defined with named variable argument list. This is a language extension.
1035 [E] No macro arguments supplied for variable argument list. This is a language extension.
1036 [E] Comma before ## ignored in expansion of variadic macro. This is a language extension.
1037 [E] Arrays of length zero are a language extension.
1038 [E] The sequence ", ##__VA_ARGS__" is a language extension.
1039 [E] Treating array of length one as potentially flexible member.
1041 [E] Empty aggregate initializers are a language extension.
1042 [E] Using I64 or UI64 as an integer constant suffix. This is a language extension.
1043 [E] Defining an anonymous union object. This is a language extension.
1044 [E] Defining an anonymous struct object. This is a language extension.
1045 [E] Use of the #include_next preprocessing directive is a language extension.
1046 [E] Function is being declared with default argument syntax. This is a language extension.
1049 [E] Nested functions are a language extension.
3445 [E] Conditional expression with middle operand omitted is a language extension.
3664 [E] Using a dot operator to access an individual bit is a language extension.
-
Rule-1.3RequiredThere shall be no occurrence of undefined or critical unspecified behaviour
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
0160 [U] Using unsupported conversion specifier number %s.
0161 [U] Unknown length modifier used with 'i' or 'd' conversion specifier, number %s.
0162 [U] Unknown length modifier used with 'o' conversion specifier, number %s.
0163 [U] Unknown length modifier used with 'u' conversion specifier, number %s.
0164 [U] Unknown length modifier used with 'x' conversion specifier, number %s.
0165 [U] Unknown length modifier used with 'X' conversion specifier, number %s.
0166 [U] Unknown length modifier used with 'f' conversion specifier, number %s.
0167 [U] Unknown length modifier used with 'e' conversion specifier, number %s.
0168 [U] Unknown length modifier used with 'E' conversion specifier, number %s.
0169 [U] Unknown length modifier used with 'g' conversion specifier, number %s.
0170 [U] Unknown length modifier used with 'G' conversion specifier, number %s.
0171 [U] Unknown length modifier used with 'c' conversion specifier, number %s.
0172 [U] Unknown length modifier used with '%%' conversion specifier, number %s.
0173 [U] Unknown length modifier used with 's' conversion specifier, number %s.
0174 [U] Unknown length modifier used with 'n' conversion specifier, number %s.
0175 [U] Unknown length modifier used with 'p' conversion specifier, number %s.
0176 [U] Incomplete conversion specifier, number %s.
0177 [U] Field width of format conversion specifier exceeds 509 characters.
0178 [U] Precision of format conversion specifier exceeds 509 characters.
0179 [U] Argument type does not match conversion specifier number %s.
0184 [U] Insufficient arguments to satisfy conversion specifier, number %s.
0185 [U] Call contains more arguments than conversion specifiers.
0186 [U] A call to this function must include at least one argument.
0190 [U] Using unsupported conversion specifier number %s.
0191 [U] Unknown length modifier used with 'd/i/n' conversion specifier, number %s.
0192 [U] Unknown length modifier used with 'o' conversion specifier, number %s.
0193 [U] Unknown length modifier used with 'u' conversion specifier, number %s.
0194 [U] Unknown length modifier used with 'x/X' conversion specifier, number %s.
0195 [U] Unknown length modifier used with 'e/E/f/F/g/G' conversion specifier, number %s.
0196 [U] Unknown length modifier used with 's' conversion specifier, number %s.
0197 [U] Unknown length modifier used with 'p' conversion specifier, number %s.
0198 [U] Unknown length modifier used with '%%' conversion specifier, number %s.
0199 [U] Unknown length modifier used with '[' conversion specifier, number %s.
0200 [U] Unknown length modifier used with 'c' conversion specifier, number %s.
0201 [U] Incomplete conversion specifier, number %s.
0203 [U] Value of character prior to '-' in '[]' is greater than following character.
0204 [U] Field width of format conversion specifier exceeds 509 characters.
0206 [U] Argument type does not match conversion specifier number %s.
0207 [U] 'scanf' expects address of objects being stored into.
0208 [U] Same character occurs in scanset more than once.
0235 [U] Unknown escape sequence.
0275 [U] Floating value is out of range for conversion to destination type.
0301 [u] Cast between a pointer to object and a floating type.
0302 [u] Cast between a pointer to function and a floating type.
0304 [U] The address of an array declared 'register' may not be computed.
0307 [u] Cast between a pointer to object and a pointer to function.
0309 [U] Integral type is not large enough to hold a pointer value.
0327 [I] Cast between a pointer to void and an floating type.
0337 [U] String literal has undefined value. This may be a result of using '#' on \\.
0400 [U] '%s' is modified more than once between sequence points - evaluation order unspecified.
0401 [U] '%s' may be modified more than once between sequence points - evaluation order unspecified.
0402 [U] '%s' is modified and accessed between sequence points - evaluation order unspecified.
0403 [U] '%s' may be modified and accessed between sequence points - evaluation order unspecified.
0404 More than one read access to volatile objects between sequence points.
0405 More than one modification of volatile objects between sequence points.
0475 [u] Operand of 'sizeof' is an expression designating a bit-field.
0543 [U] 'void' expressions have no value and may not be used in expressions.
0544 [U] The value of an incomplete 'union' may not be used.
0545 [U] The value of an incomplete 'struct' may not be used.
0602 [U] The identifier '%s' is reserved for use by the library.
0603 [U] The macro identifier '%s' is reserved.
0623 [U] '%s' has incomplete type and no linkage - this is undefined.
0625 [U] '%s' has been declared with both internal and external linkage - the behaviour is undefined.
0626 [U] '%s' has different type to previous declaration (which is no longer in scope).
0630 [U] More than one definition of '%s' (with external linkage).
0632 [U] Tentative definition of '%s' with internal linkage cannot have unknown size.
0636 [U] There are no named members in this 'struct' or 'union'.
0654 [U] Using 'const' or 'volatile' in a function return type is undefined.
0658 [U] Parameter cannot have 'void' type.
0661 [U] '%s()' may not have a storage class specifier of 'static' when declared at block scope.
0667 [U] '%s' is declared as a typedef and may not be redeclared as an object at an inner scope without an explicit type specifier.
0668 [U] '%s' is declared as a typedef and may not be redeclared as a member of a 'struct' or 'union' without an explicit type specifier.
0672 [U] The initializer for a 'struct', 'union' or array is not enclosed in braces.
0676 [u] Array element is of function type. Arrays cannot be constructed from function types.
0678 [u] Array element is array of unknown size. Arrays cannot be constructed from incomplete types.
0680 [u] Array element is 'void' or an incomplete 'struct' or 'union'. Arrays cannot be constructed from incomplete types.
0706 [U] Label '%s' is not unique within this function.
0745 [U] 'return;' found in '%s()', which has been defined with a non-'void' return type.
0777 [U] External identifier does not differ from other identifier(s) (e.g. '%s') within the specified number of significant characters.
0779 [U] Identifier does not differ from other identifier(s) (e.g. '%s') within the specified number of significant characters.
0813 [U] Using any of the characters ' " or /* in '#include <%s>' gives undefined behaviour.
0814 [U] Using the characters ' or /* in '#include "%s"' gives undefined behaviour.
0836 [U] Definition of macro named 'defined'.
0837 [U] Use of '#undef' to remove the operator 'defined'.
0840 [E] Extra tokens at end of #include directive.
0848 [U] Attempting to #undef '%s', which is a predefined macro name.
0853 [U] Macro arguments contain a sequence of tokens that has the form of a preprocessing directive.
0854 [U] Attempting to #define '%s', which is a predefined macro name.
0864 [U] '#line' directive specifies line number which is not in the range 1 to 32767.
0865 [U] '#line' directive is badly formed.
0867 [U] '#line' has not been followed by a line number.
0872 [U] Result of '##' operator is not a legal preprocessing token.
0874 [U] Character string literal and wide character string literal are adjacent.
0885 [U] The token 'defined' is generated in the expansion of this macro.
0887 [U] Use of 'defined' must match either 'defined(identifier)' or 'defined identifier'.
0888 [U] 'defined' requires an identifier as an argument.
0914 [U] Source file does not end with a newline character.
0915 [U] Source file ends with a backslash character followed by a newline.
0942 [U] A * can only be used to specify array size within function prototype scope.
1331 Type or number of arguments doesn't match previous use of the function.
1332 Type or number of arguments doesn't match prototype found later.
1333 Type or number of arguments doesn't match function definition found later.
2800 Constant: Overflow in signed arithmetic operation.
2810 Constant: Dereference of NULL pointer.
2820 Constant: Arithmetic operation on NULL pointer.
2830 Constant: Division by zero.
2840 Constant: Dereference of an invalid pointer value.
3113 [U] 'return' statement includes no expression but function '%s()' is implicitly of type 'int'.
3114 [U] Function '%s()' is implicitly of type 'int' but ends without returning a value.
3239 [U] inline function '%1s' has external linkage, but is not defined within this translation unit.
3311 [u] An earlier jump to this statement will bypass the initialization of local variables.
3312 [u] This goto statement will jump into a previous block and bypass the initialization of local variables.
3319 [U] Function called with number of arguments which differs from number of parameters in definition.
3320 Type of argument no. %s differs from its type in definition of function.
3437 [u] The assert macro has been suppressed to call a function of that name.
3438 [U] #undef'ing the assert macro to call a function of that name causes undefined behaviour.
1509 '%1s' has external linkage and has multiple definitions.
1510 '%1s' has external linkage and has incompatible declarations.
-
Rule-10.1RequiredOperands shall not be of an inappropriate essential type.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
3101 Unary '-' applied to an operand of type unsigned int or unsigned long gives an unsigned result.
3102 Unary '-' applied to an operand whose underlying type is unsigned.
4500 An expression of 'essentially Boolean' type (%1s) is being used as an array subscript.
4501 An expression of 'essentially Boolean' type (%1s) is being used as the %2s operand of this arithmetic operator (%3s).
4502 An expression of 'essentially Boolean' type (%1s) is being used as the %2s operand of this bitwise operator (%3s).
4503 An expression of 'essentially Boolean' type (%1s) is being used as the left-hand operand of this shift operator (%2s).
4504 An expression of 'essentially Boolean' type (%1s) is being used as the right-hand operand of this shift operator (%2s).
4505 An expression of 'essentially Boolean' type (%1s) is being used as the %2s operand of this relational operator (%3s).
4507 An expression of 'essentially Boolean' type (%1s) is being used as the operand of this increment/decrement operator (%2s).
4510 An expression of 'essentially character' type (%1s) is being used as an array subscript.
4511 An expression of 'essentially character' type (%1s) is being used as the %2s operand of this arithmetic operator (%3s).
4512 An expression of 'essentially character' type (%1s) is being used as the %2s operand of this bitwise operator (%3s).
4513 An expression of 'essentially character' type (%1s) is being used as the left-hand operand of this shift operator (%2s).
4514 An expression of 'essentially character' type (%1s) is being used as the right-hand operand of this shift operator (%2s).
4518 An expression of 'essentially character' type (%1s) is being used as the %2s operand of this logical operator (%3s).
4519 An expression of 'essentially character' type (%1s) is being used as the first operand of this conditional operator (%2s).
4521 An expression of 'essentially enum' type (%1s) is being used as the %2s operand of this arithmetic operator (%3s).
4522 An expression of 'essentially enum' type (%1s) is being used as the %2s operand of this bitwise operator (%3s).
4523 An expression of 'essentially enum' type (%1s) is being used as the left-hand operand of this shift operator (%2s).
4524 An expression of 'essentially enum' type (%1s) is being used as the right-hand operand of this shift operator (%2s).
4527 An expression of 'essentially enum' type is being used as the operand of this increment/decrement operator.
4528 An expression of 'essentially enum' type (%1s) is being used as the %2s operand of this logical operator (%3s).
4529 An expression of 'essentially enum' type (%1s) is being used as the first operand of this conditional operator (%2s).
4532 An expression of 'essentially signed' type (%1s) is being used as the %2s operand of this bitwise operator (%3s).
4533 An expression of 'essentially signed' type (%1s) is being used as the left-hand operand of this shift operator (%2s).
4534 An expression of 'essentially signed' type (%1s) is being used as the right-hand operand of this shift operator (%2s).
4538 An expression of 'essentially signed' type (%1s) is being used as the %2s operand of this logical operator (%3s).
4539 An expression of 'essentially signed' type (%1s) is being used as the first operand of this conditional operator (%2s).
4542 A non-negative constant expression of 'essentially signed' type (%1s) is being used as the %2s operand of this bitwise operator (%3s).
4543 A non-negative constant expression of 'essentially signed' type (%1s) is being used as the left-hand operand of this shift operator (%2s).
4548 A non-negative constant expression of 'essentially signed' type (%1s) is being used as the %2s operand of this logical operator (%3s).
4549 A non-negative constant expression of 'essentially signed' type (%1s) is being used as the first operand of this conditional operator (%2s).
4558 An expression of 'essentially unsigned' type (%1s) is being used as the %2s operand of this logical operator (%3s).
4559 An expression of 'essentially unsigned' type (%1s) is being used as the first operand of this conditional operator (%2s).
4568 An expression of 'essentially floating' type (%1s) is being used as the %2s operand of this logical operator (%3s).
4569 An expression of 'essentially floating' type (%1s) is being used as the first operand of this conditional operator (%2s).
-
Rule-10.2RequiredExpressions of essentially character type shall not be used inappropriately in addition and subtraction operations
- - - - - - - - - - - - - - - - - -
QacDescription
1810 An operand of 'essentially character' type is being added to another operand of 'essentially character' type.
1811 An operand of 'essentially character' type is being subtracted from an operand of 'essentially signed' type.
1812 An operand of 'essentially character' type is being subtracted from an operand of 'essentially unsigned' type.
1813 An operand of 'essentially character' type is being balanced with an operand of 'essentially floating' type in this arithmetic operation.
-
Rule-10.3RequiredThe value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
0570 This switch case label of 'essential type' '%1s', is not consistent with a controlling expression of essential type '%2s'.
0572 This switch case label of 'essential type' '%1s' is not consistent with a controlling expression which has an essential type of lower rank (%2s).
1257 An integer constant suffixed with L or LL is being converted to a type of lower rank on assignment.
1264 A suffixed floating constant is being converted to a different floating type on assignment.
1265 An unsuffixed floating constant is being converted to a different floating type on assignment.
1266 A floating constant is being converted to integral type on assignment.
1291 An integer constant of 'essentially unsigned' type is being converted to signed type on assignment.
1292 An integer constant of 'essentially signed' type is being converted to type char on assignment.
1293 An integer constant of 'essentially unsigned' type is being converted to type char on assignment.
1294 An integer constant of 'essentially signed' type is being converted to type _Bool on assignment.
1295 An integer constant of 'essentially unsigned' type is being converted to type _Bool on assignment.
1296 An integer constant of 'essentially signed' type is being converted to enum type on assignment.
1297 An integer constant of 'essentially unsigned' type is being converted to enum type on assignment.
1298 An integer constant of 'essentially signed' type is being converted to floating type on assignment.
1299 An integer constant of 'essentially unsigned' type is being converted to floating type on assignment.
2850 Constant: Implicit conversion to a signed integer type of insufficient size.
2890 Constant: Negative value implicitly converted to an unsigned type.
2900 Constant: Positive integer value truncated by implicit conversion to a smaller unsigned type.
4401 An expression of 'essentially Boolean' type (%1s) is being converted to character type, '%2s' on assignment.
4402 An expression of 'essentially Boolean' type (%1s) is being converted to enum type, '%2s' on assignment.
4403 An expression of 'essentially Boolean' type (%1s) is being converted to signed type, '%2s' on assignment.
4404 An expression of 'essentially Boolean' type (%1s) is being converted to unsigned type, '%2s' on assignment.
4405 An expression of 'essentially Boolean' type (%1s) is being converted to floating type, '%2s' on assignment.
4410 An expression of 'essentially character' type (%1s) is being converted to Boolean type, '%2s' on assignment.
4412 An expression of 'essentially character' type (%1s) is being converted to enum type, '%2s' on assignment.
4413 An expression of 'essentially character' type (%1s) is being converted to signed type, '%2s' on assignment.
4414 An expression of 'essentially character' type (%1s) is being converted to unsigned type, '%2s' on assignment.
4415 An expression of 'essentially character' type (%1s) is being converted to floating type, '%2s' on assignment.
4420 An expression of 'essentially enum' type (%1s) is being converted to Boolean type, '%2s' on assignment.
4421 An expression of 'essentially enum' type (%1s) is being converted to character type, '%2s' on assignment.
4422 An expression of 'essentially enum' type (%1s) is being converted to a different enum type, '%2s' on assignment.
4423 An expression of 'essentially enum' type (%1s) is being converted to signed type, '%2s' on assignment.
4424 An expression of 'essentially enum' type (%1s) is being converted to unsigned type, '%2s' on assignment.
4425 An expression of 'essentially enum' type (%1s) is being converted to floating type, '%2s' on assignment.
4430 An expression of 'essentially signed' type (%1s) is being converted to Boolean type, '%2s' on assignment.
4431 An expression of 'essentially signed' type (%1s) is being converted to character type, '%2s' on assignment.
4432 An expression of 'essentially signed' type (%1s) is being converted to enum type, '%2s' on assignment.
4434 A non-constant expression of 'essentially signed' type (%1s) is being converted to unsigned type, '%2s' on assignment.
4435 A non-constant expression of 'essentially signed' type (%1s) is being converted to floating type, '%2s' on assignment.
4437 A constant expression of 'essentially signed' type (%1s) is being converted to floating type, '%2s' on assignment.
4440 An expression of 'essentially unsigned' type (%1s) is being converted to Boolean type, '%2s' on assignment.
4441 An expression of 'essentially unsigned' type (%1s) is being converted to character type, '%2s' on assignment.
4442 An expression of 'essentially unsigned' type (%1s) is being converted to enum type, '%2s' on assignment.
4443 A non-constant expression of 'essentially unsigned' type (%1s) is being converted to a wider signed type, '%2s' on assignment.
4445 An expression of 'essentially unsigned' type (%1s) is being converted to floating type, '%2s' on assignment.
4446 A non-constant expression of 'essentially unsigned' type (%1s) is being converted to signed type, '%2s' on assignment.
4447 A constant expression of 'essentially unsigned' type (%1s) is being converted to signed type, '%2s' on assignment.
4450 An expression of 'essentially floating' type (%1s) is being converted to Boolean type, '%2s' on assignment.
4451 An expression of 'essentially floating' type (%1s) is being converted to character type, '%2s' on assignment.
4452 An expression of 'essentially floating' type (%1s) is being converted to enum type, '%2s' on assignment.
4453 An expression of 'essentially floating' type (%1s) is being converted to signed type, '%2s' on assignment.
4454 An expression of 'essentially floating' type (%1s) is being converted to unsigned type, '%2s' on assignment.
4460 A non-constant expression of 'essentially signed' type (%1s) is being converted to narrower signed type, '%2s' on assignment.
4461 A non-constant expression of 'essentially unsigned' type (%1s) is being converted to narrower unsigned type, '%2s' on assignment.
4462 A non-constant expression of 'essentially floating' type (%1s) is being converted to narrower floating type, '%2s' on assignment.
4463 A constant expression of 'essentially signed' type (%1s) is being converted to narrower signed type, '%2s' on assignment.
4464 A constant expression of 'essentially unsigned' type (%1s) is being converted to narrower unsigned type, '%2s' on assignment.
4465 A constant expression of 'essentially floating' type (%1s) is being converted to narrower floating type, '%2s' on assignment.
-
Rule-10.4RequiredBoth operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
1800 The %1s operand (essential type: '%2s') will be implicitly converted to a floating type, '%3s', in this arithmetic operation.
1802 The %1s operand (essential type: '%2s') will be implicitly converted to a floating type, '%3s', in this relational operation.
1803 The %1s operand (essential type: '%2s') will be implicitly converted to a floating type, '%3s', in this equality operation.
1804 The %1s operand (essential type: '%2s') will be implicitly converted to a floating type, '%3s', in this conditional operation.
1820 The %1s operand is non-constant and 'essentially signed' (%2s) but will be implicitly converted to an unsigned type (%3s) in this arithmetic operation.
1821 The %1s operand is non-constant and 'essentially signed' (%2s) but will be implicitly converted to an unsigned type (%3s) in this bitwise operation.
1822 The %1s operand is non-constant and 'essentially signed' (%2s) but will be implicitly converted to an unsigned type (%3s) in this relational operation.
1823 The %1s operand is non-constant and 'essentially signed' (%2s) but will be implicitly converted to an unsigned type (%3s) in this equality operation.
1824 The %1s operand is non-constant and 'essentially signed' (%2s) but will be implicitly converted to an unsigned type (%3s) in this conditional operation.
1830 The %1s operand is constant, 'essentially signed' (%2s) and negative but will be implicitly converted to an unsigned type (%3s) in this arithmetic operation.
1831 The %1s operand is constant, 'essentially signed' (%2s) and negative but will be implicitly converted to an unsigned type (%3s) in this bitwise operation.
1832 The %1s operand is constant, 'essentially signed' (%2s) and negative but will be implicitly converted to an unsigned type (%3s) in this relational operation.
1833 The %1s operand is constant, 'essentially signed' (%2s) and negative but will be implicitly converted to an unsigned type (%3s) in this equality operation.
1834 The %1s operand is constant, 'essentially signed' (%2s) and negative but will be implicitly converted to an unsigned type (%3s) in this conditional operation.
1840 The %1s operand is constant, 'essentially signed' (%2s) and non-negative but will be implicitly converted to an unsigned type (%3s) in this arithmetic operation.
1841 The %1s operand is constant, 'essentially signed' (%2s) and non-negative but will be implicitly converted to an unsigned type (%3s) in this bitwise operation.
1842 The %1s operand is constant, 'essentially signed' (%2s) and non-negative but will be implicitly converted to an unsigned type (%3s) in this relational operation.
1843 The %1s operand is constant, 'essentially signed' (%2s) and non-negative but will be implicitly converted to an unsigned type (%3s) in this equality operation.
1844 The %1s operand is constant, 'essentially signed' (%2s) and non-negative but will be implicitly converted to an unsigned type (%3s) in this conditional operation.
1850 The %1s operand is 'essentially unsigned' (%2s) but will be implicitly converted to a signed type (%3s) in this arithmetic operation.
1851 The %1s operand is 'essentially unsigned' (%2s) but will be implicitly converted to a signed type (%3s) in this bitwise operation.
1852 The %1s operand is 'essentially unsigned' (%2s) but will be implicitly converted to a signed type (%3s) in this relational operation.
1853 The %1s operand is 'essentially unsigned' (%2s) but will be implicitly converted to a signed type (%3s) in this equality operation.
1854 The %1s operand is 'essentially unsigned' (%2s) but will be implicitly converted to a signed type (%3s) in this conditional operation.
1860 The operands of this arithmetic operator are of different 'essential signedness' but will generate a result of type 'signed int'.
1861 The operands of this bitwise operator are of different 'essential signedness' but will generate a result of type 'signed int'.
1862 The operands of this relational operator are of different 'essential signedness' but will both be promoted to 'signed int' for comparison.
1863 The operands of this equality operator are of different 'essential signedness' but will both be promoted to 'signed int' for comparison.
1864 The 2nd and 3rd operands of this conditional operator are of different 'essential signedness'. The result will be in the promoted type 'signed int'.
1880 The operands of this relational operator are expressions of different 'essential type' categories (%1s and %2s).
1881 The operands of this equality operator are expressions of different 'essential type' categories (%1s and %2s).
1882 The 2nd and 3rd operands of this conditional operator are expressions of different 'essential type' categories (%1s and %2s).
-
Rule-10.5AdvisoryThe value of an expression should not be cast to an inappropriate essential type
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
4301 An expression of 'essentially Boolean' type (%1s) is being cast to character type '%2s'.
4302 An expression of 'essentially Boolean' type (%1s) is being cast to enum type '%2s'.
4303 An expression of 'essentially Boolean' type (%1s) is being cast to signed type '%2s'.
4304 An expression of 'essentially Boolean' type (%1s) is being cast to unsigned type '%2s'.
4305 An expression of 'essentially Boolean' type (%1s) is being cast to floating type '%2s'.
4310 An expression of 'essentially character' type (%1s) is being cast to Boolean type, '%2s'.
4312 An expression of 'essentially character' type (%1s) is being cast to enum type, '%2s'.
4315 An expression of 'essentially character' type (%1s) is being cast to floating type, '%2s'.
4320 An expression of 'essentially enum' type (%1s) is being cast to Boolean type, '%2s'.
4322 An expression of 'essentially enum' type (%1s) is being cast to a different enum type, '%2s'.
4330 An expression of 'essentially signed' type (%1s) is being cast to Boolean type '%2s'.
4332 An expression of 'essentially signed' type (%1s) is being cast to enum type, '%2s'.
4340 An expression of 'essentially unsigned' type (%1s) is being cast to Boolean type '%2s'.
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
4350 An expression of 'essentially floating' type (%1s) is being cast to Boolean type '%2s'.
4351 An expression of 'essentially floating' type (%1s) is being cast to character type '%2s'.
4352 An expression of 'essentially floating' type (%1s) is being cast to enum type, '%2s'.
-
Rule-10.6RequiredThe value of a composite expression shall not be assigned to an object with wider essential type
- - - - - - - - - - - - - - - - - -
QacDescription
4490 A composite expression of 'essentially signed' type (%1s) is being converted to wider signed type, '%2s' on assignment.
4491 A composite expression of 'essentially unsigned' type (%1s) is being converted to wider unsigned type, '%2s' on assignment.
4492 A composite expression of 'essentially floating' type (%1s) is being converted to wider floating type, '%2s' on assignment.
4499 An expression which is the result of a ~ or << operation has been converted to a wider essential type on assignment.
-
Rule-10.7RequiredIf a composite expression is used as one operand of an operator in which the usual arithmetic conversions are performed then the other operand shall not have wider essential type
- - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
1890 A composite expression of 'essentially signed' type (%1s) is being implicitly converted to a wider signed type, '%2s'.
1891 A composite expression of 'essentially unsigned' type (%1s) is being implicitly converted to a wider unsigned type, '%2s'.
1892 A composite expression of 'essentially floating' type (%1s) is being implicitly converted to a wider floating type, '%2s'.
1893 The 2nd and 3rd operands of this conditional operator are both 'essentially signed' ('%1s' and '%2s') but one is a composite expression of a narrower type than the other.
1894 The 2nd and 3rd operands of this conditional operator are both 'essentially unsigned' ('%1s' and '%2s') but one is a composite expression of a narrower type than the other.
1895 The 2nd and 3rd operands of this conditional operator are both 'essentially floating' ('%1s' and '%2s') but one is a composite expression of a narrower type than the other.
-
Rule-10.8RequiredThe value of a composite expression shall not be cast to a different essential type category or a wider essential type
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
4389 A composite expression of 'essentially char' type (%1s) is being cast to a different type category, '%2s'.
4390 A composite expression of 'essentially signed' type (%1s) is being cast to a wider signed type, '%2s'.
4391 A composite expression of 'essentially unsigned' type (%1s) is being cast to a wider unsigned type, '%2s'.
4392 A composite expression of 'essentially floating' type (%1s) is being cast to a wider floating type, '%2s'.
4393 A composite expression of 'essentially signed' type (%1s) is being cast to a different type category, '%2s'.
4394 A composite expression of 'essentially unsigned' type (%1s) is being cast to a different type category, '%2s'.
4395 A composite expression of 'essentially floating' type (%1s) is being cast to a different type category, '%2s'.
4398 An expression which is the result of a ~ or << operation has been cast to a different essential type category.
4399 An expression which is the result of a ~ or << operation has been cast to a wider type.
-
Rule-11.1RequiredConversions shall not be performed between a pointer to a function and any other type
- - - - - - - - - - - - - - - - - -
QacDescription
0302 [u] Cast between a pointer to function and a floating type.
0305 [I] Cast between a pointer to function and an integral type.
0307 [u] Cast between a pointer to object and a pointer to function.
0313 Casting to different function pointer type.
-
Rule-11.2RequiredConversions shall not be performed between a pointer to an incomplete type and any other type
- - - - - - - - - - - - - - - - - -
QacDescription
0308 Non-portable cast involving pointer to an incomplete type.
0323 [u] Cast between a pointer to incomplete type and a floating type.
0324 [u] Cast between a pointer to incomplete type and an integral type.
0325 [u] Cast between a pointer to incomplete type and a pointer to function.
-
Rule-11.3RequiredA cast shall not be performed between a pointer to object type and a pointer to a different object type
- - - - - - - - - -
QacDescription
0310 Casting to different object pointer type.
3305 Pointer cast to stricter alignment.
-
Rule-11.4AdvisoryA conversion should not be performed between a pointer to object and an integer type
- - - - - - - - - - - - - - - - - - - - - -
QacDescription
0303 [I] Cast between a pointer to volatile object and an integral type.
0306 [I] Cast between a pointer to object and an integral type.
0360 An expression of pointer type is being converted to type _Bool on assignment.
0361 An expression of pointer type is being cast to type _Bool.
0362 An expression of essentially Boolean type is being cast to a pointer.
-
Rule-11.5AdvisoryA conversion should not be performed from pointer to void into pointer to object
- - - - - - - - - -
QacDescription
0316 [I] Cast from a pointer to void to a pointer to object type.
0317 [I] Implicit conversion from a pointer to void to a pointer to object type.
-
Rule-11.6RequiredA cast shall not be performed between pointer to void and an arithmetic type
- - - - - - - - - -
QacDescription
0326 [I] Cast between a pointer to void and an integral type.
0327 [I] Cast between a pointer to void and an floating type.
-
Rule-11.7RequiredA cast shall not be performed between pointer to object and a non-integer arithmetic type
- - - - - - - - - -
QacDescription
0301 [u] Cast between a pointer to object and a floating type.
0328 [u] Cast between a pointer to object and an essential type other than signed/unsigned.
-
Rule-11.8RequiredA cast shall not remove any const or volatile qualification from the type pointed to by a pointer
- - - - - - - - - -
QacDescription
0311 Dangerous pointer cast results in loss of const qualification.
0312 Dangerous pointer cast results in loss of volatile qualification.
-
Rule-11.9RequiredThe macro NULL shall be the only permitted form of integer null pointer constant
- - - - - - - - - -
QacDescription
3003 This character constant is being interpreted as a NULL pointer constant.
3004 This integral constant expression is being interpreted as a NULL pointer constant.
-
Rule-12.1AdvisoryThe precedence of operators within expressions should be made explicit
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
3389 Extra parentheses recommended to clarify the ordering of a % operator and another arithmetic operator (* / % + -).
3391 Extra parentheses recommended. A conditional operation is the operand of another conditional operator.
3392 Extra parentheses recommended. A shift, relational or equality operation is the operand of a second identical operator.
3394 Extra parentheses recommended. A shift, relational or equality operation is the operand of a different operator with the same precedence.
3395 Extra parentheses recommended. A * or / operation is the operand of a + or - operator.
3396 Extra parentheses recommended. A binary operation is the operand of a conditional operator.
3397 Extra parentheses recommended. A binary operation is the operand of a binary operator with different precedence.
-
Rule-12.2RequiredThe right hand operand of a shift operator shall lie in the range zero to one less than the width in bits of the essential type of the left hand operand
- - - - - - - - - - - - - - - - - -
QacDescription
0499 Right operand of shift operator is greater than or equal to the width of the essential type of the left operand.
2790 Constant: Right hand operand of shift operator is negative or too large.
2791 Definite: Right hand operand of shift operator is negative or too large.
2792 Apparent: Right hand operand of shift operator is negative or too large.
-
Rule-12.3AdvisoryThe comma operator should not be used
- - - - - - - - - -
QacDescription
3417 The comma operator has been used outside a 'for' statement.
3418 The comma operator has been used in a 'for' statement.
-
Rule-12.4AdvisoryEvaluation of constant expressions should not lead to unsigned integer wrap-around
- - - - - -
QacDescription
2910 Constant: Wraparound in unsigned arithmetic operation.
-
Rule-12.5MandatoryThe sizeof operator shall not have an operand which is a function parameter declared as 'array of type'
- - - - - -
QacDescription
1321 Operand of sizeof is a function parameter of array type.
-
Rule-13.1RequiredInitializer lists shall not contain persistent side-effects
- - - - - -
QacDescription
3421 Expression with possible side effects is used in an initializer list.
-
Rule-13.2RequiredThe value of an expression and its persistent side-effects shall be the same under all permitted evaluation orders
- - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
0400 [U] '%s' is modified more than once between sequence points - evaluation order unspecified.
0401 [U] '%s' may be modified more than once between sequence points - evaluation order unspecified.
0402 [U] '%s' is modified and accessed between sequence points - evaluation order unspecified.
0403 [U] '%s' may be modified and accessed between sequence points - evaluation order unspecified.
0404 More than one read access to volatile objects between sequence points.
0405 More than one modification of volatile objects between sequence points.
-
Rule-13.3AdvisoryA full expression containing an increment (++) or decrement (--) operator should have no other potential side effects other than that caused by the increment or decrement operator
- - - - - -
QacDescription
3440 Using the value resulting from a ++ or -- operation.
-
Rule-13.4AdvisoryThe result of an assignment operator should not be used
- - - - - - - - - -
QacDescription
3226 The result of an assignment is being used in an arithmetic operation or another assigning operation.
3326 The result of an assignment is being used in a logical operation.
-
Rule-13.5RequiredThe right hand operand of a logical && or || operator shall not contain persistent side effects
- - - - - -
QacDescription
3415 Right hand operand of '&&' or '||' is an expression with possible side effects.
-
Rule-13.6MandatoryThe operand of the sizeof operator shall not contain any expression which has potential side-effects
- - - - - - - - - -
QacDescription
0945 [C99] Operand of sizeof is an expression of variable length array type with side effects.
3307 The operand of 'sizeof' is an expression with implied side effects, but they will not be evaluated.
-
Rule-14.1RequiredA loop counter shall not have essentially floating type
- - - - - - - - - - - - - -
QacDescription
3339 Floating point variable used as 'while' loop control variable.
3340 Floating point variable used as 'for' loop control variable.
3342 Controlling expression of 'for' loop is a floating point comparison.
-
Rule-14.2RequiredA for loop shall be well-formed
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
2461 Loop control variable in this 'for' statement, %s, has file scope.
2462 The variable initialized in the first expression of this 'for' statement is not the variable identified as the 'loop control variable' (%s).
2463 The variable incremented in the third expression of this 'for' statement is not the variable identified as the 'loop control variable' (%s).
2464 Loop control variable, %s, modified twice in for-loop header.
2467 Loop control variable in this 'for' statement, %s, is not modified inside loop.
2468 Loop control variable in this 'for' statement, %s, is not modified inside loop but has file scope.
2469 Loop control variable in this 'for' statement, %s, is modified in the body of the loop.
2471 Unable to identify a loop control variable.
2472 More than one possible loop control variable.
-
Rule-14.3RequiredControlling expressions shall not be invariant
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
2741 This 'if' controlling expression is a constant expression and its value is 'true'.
2742 This 'if' controlling expression is a constant expression and its value is 'false'.
2990 The value of this loop controlling expression is always 'true'.
2991 The value of this 'if' controlling expression is always 'true'.
2992 The value of this 'if' controlling expression is always 'false'.
2993 The value of this 'do - while' loop controlling expression is always 'false'. The loop will only be executed once.
2994 The value of this 'while' or 'for' loop controlling expression is always 'false'. The loop will not be entered.
2997 The first operand of this conditional operator is always 'true'.
2998 The first operand of this conditional operator is always 'false'.
3493 The first operand of this conditional operator is always constant 'true'.
3494 The first operand of this conditional operator is always constant 'false'.
-
Rule-14.4RequiredThe controlling expression of an if-statement and the controlling expression of an iteration-statement shall have essentially Boolean type
- - - - - -
QacDescription
3344 Controlling expression is not an 'essentially Boolean' expression.
-
Rule-15.1AdvisoryThe goto statement should not be used
- - - - - -
QacDescription
2001 A 'goto' statement has been used.
-
Rule-15.2RequiredThe goto statement shall jump to a label declared later in the same function
- - - - - -
QacDescription
3310 This 'goto' statement involves a backward jump.
-
Rule-15.3RequiredAny label referenced by a goto statement shall be declared in the same block, or in any block enclosing the goto statement
- - - - - -
QacDescription
3327 This goto statement references a label that is declared in a separate block.
-
Rule-15.4AdvisoryThere should be no more than one break or goto statement used to terminate any iteration statement
- - - - - -
QacDescription
0771 More than one 'break' statement has been used to terminate this iteration statement.
-
Rule-15.5AdvisoryA function should have a single point of exit at the end
- - - - - -
QacDescription
2889 This function has more than one 'return' path.
-
Rule-15.6RequiredThe body of an iteration-statement or a selection-statement shall be a compound-statement
- - - - - - - - - - - - - - - - - - - - - -
QacDescription
2212 Body of control statement is not enclosed within braces.
2214 Body of control statement is on the same line and is not enclosed within braces.
2218 Body of switch statement is not enclosed within braces.
2219 Body of switch statement is on the same line and is not enclosed within braces.
3402 Braces are needed to clarify the structure of this 'if'-'if'-'else' statement.
-
Rule-15.7RequiredAll if ... else if constructs shall be terminated with an else statement
- - - - - - - - - -
QacDescription
2004 No concluding 'else' exists in this 'if'-'else'-'if' statement.
2013 This 'if .. else if ' construct 'else' statement is empty.
-
Rule-16.1RequiredAll switch statements shall be well-formed
- - - - - - - - - -
QacDescription
2008 Code statements precede the first label in this 'switch' construct.
3234 Declarations precede the first label in this 'switch' construct.
-
Rule-16.2RequiredA switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statement
- - - - - -
QacDescription
2019 'Switch' label is located within a nested code block.
-
Rule-16.3RequiredAn unconditional break statement shall terminate every switch-clause
- - - - - - - - - -
QacDescription
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
2020 Final 'switch' clause does not end with an explicit 'jump' statement.
-
Rule-16.4RequiredEvery switch statement shall have a default label
- - - - - - - - - -
QacDescription
2002 No 'default' label found in this 'switch' statement.
2016 This 'switch' statement 'default' clause is empty.
-
Rule-16.5RequiredA default label shall appear as either the first or the last switch label of a switch statement
- - - - - -
QacDescription
2012 This 'default' label is neither the first nor the last label within the 'switch' block.
-
Rule-16.6RequiredEvery switch statement shall have at least two switch-clauses
- - - - - -
QacDescription
3315 This 'switch' statement is redundant.
-
Rule-16.7RequiredA switch-expression shall not have essentially Boolean type
- - - - - -
QacDescription
0735 Switch expression is of essentially Boolean type.
-
Rule-17.1RequiredThe features of shall not be used
- - - - - - - - - -
QacDescription
5130 Use of standard header file .
1337 Function defined with a variable number of parameters.
-
Rule-17.2RequiredFunctions shall not call themselves, either directly or indirectly
- - - - - - - - - -
QacDescription
3670 Recursive call to function containing this call.
1520 Functions are indirectly recursive.
-
Rule-17.3MandatoryA function shall not be declared implicitly
- - - - - -
QacDescription
3335 No function declaration. Implicit declaration inserted: 'extern int %s();'.
-
Rule-17.4MandatoryAll exit paths from a function with non-void return type shall have an explicit return statement with an expression
- - - - - - - - - - - - - - - - - - - - - -
QacDescription
0745 [U] 'return;' found in '%s()', which has been defined with a non-'void' return type.
2887 Function 'main' ends with an implicit 'return' statement.
2888 This function has been declared with a non-void 'return' type but ends with an implicit 'return ;' statement.
3113 [U] 'return' statement includes no expression but function '%s()' is implicitly of type 'int'.
3114 [U] Function '%s()' is implicitly of type 'int' but ends without returning a value.
-
Rule-17.5AdvisoryThe function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elements
- - - - - - - - - - - - - - - - - -
QacDescription
2781 Definite: Function argument has fewer elements than the array dimension in the parameter declaration for non-inlined call.
2782 Apparent: Function argument has fewer elements than the array dimension in the parameter declaration for non-inlined call.
2783 Suspicious: Function argument has fewer elements than the array dimension in the parameter declaration for non-inlined call.
2784 Possible: Function argument has fewer elements than the array dimension in the parameter declaration for non-inlined call.
-
Rule-17.6MandatoryThe declaration of an array parameter shall not contain the static keyword between the [ ]
- - - - - -
QacDescription
1058 [C99] The keyword 'static' is used in the declaration of a function parameter of array type.
-
Rule-17.7RequiredThe value returned by a function having non-void return type shall be used
- - - - - -
QacDescription
3200 '%s' returns a value which is not being used.
-
Rule-17.8AdvisoryA function parameter should not be modified
- - - - - - - - - - - - - -
QacDescription
1338 The parameter '%s' is being modified.
1339 Evaluating the address of the parameter '%s'.
1340 Storing the address of the parameter '%s' in a constant pointer.
-
Rule-18.1RequiredA pointer resulting from arithmetic on a pointer operand shall address an element of the same array as that pointer operand
- - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
2840 Constant: Dereference of an invalid pointer value.
2841 Definite: Dereference of an invalid pointer value.
2842 Apparent: Dereference of an invalid pointer value.
2930 Constant: Computing an invalid pointer value.
2931 Definite: Computing an invalid pointer value.
2932 Apparent: Computing an invalid pointer value.
-
Rule-18.2RequiredSubtraction between pointers shall only be applied to pointers that address elements of the same array
- - - - - - - - - - - - - -
QacDescription
2668 Subtraction of a pointer to an array and a pointer to a non array.
2761 Definite: Subtracting pointers that address different objects.
2762 Apparent: Subtracting pointers that address different objects.
-
Rule-18.3RequiredThe relational operators >, >=, < and <= shall not be applied to objects of pointer type except where they point into the same object
- - - - - - - - - - - - - -
QacDescription
2669 Comparison of a pointer to an array and a pointer to a non array.
2771 Definite: Comparing pointers that address different objects.
2772 Apparent: Comparing pointers that address different objects.
-
Rule-18.4AdvisoryThe +, -, += and -= operators should not be applied to an expression of pointer type
- - - - - -
QacDescription
0488 Performing pointer arithmetic.
-
Rule-18.5AdvisoryDeclarations should contain no more than two levels of pointer nesting
- - - - - - - - - - - - - - - - - -
QacDescription
3260 Typedef defined with more than 2 levels of indirection.
3261 Member of struct/union defined with more than 2 levels of indirection.
3262 Object defined or declared with more than 2 levels of indirection.
3263 Function defined or declared with a return type which has more than 2 levels of indirection.
-
Rule-18.6RequiredThe address of an object with automatic storage shall not be copied to another object that persists after the first object has ceased to exist
- - - - - - - - - - - - - - - - - -
QacDescription
3217 Address of automatic object exported to a pointer with linkage or wider scope.
3225 Address of automatic object exported using a function parameter.
3230 Address of automatic object assigned to local pointer with static storage duration.
4140 Address of automatic object exported in function return value.
-
Rule-18.7RequiredFlexible array members shall not be declared
- - - - - -
QacDescription
1060 [C99] A flexible array member has been declared.
-
Rule-18.8RequiredVariable-length array types shall not be used
- - - - - - - - - -
QacDescription
1051 [C99] A variable length array has been declared.
1052 [C99] A variable length array of unspecified size has been declared.
-
Rule-19.1MandatoryAn object shall not be assigned or copied to an overlapping object
- - - - - - - - - - - - - -
QacDescription
0681 [U] Assignment between two incompatible members of the same union.
2776 Definite: Copy between overlapping objects.
2777 Apparent: Copy between overlapping objects.
-
Rule-19.2AdvisoryThe union keyword should not be used
- - - - - - - - - -
QacDescription
0750 A union type specifier has been defined.
0759 An object of union type has been defined.
-
Rule-2.1RequiredA project shall not contain unreachable code
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
0594 Negative 'case' label expression is incompatible with unsigned controlling expression in 'switch' statement.
1460 'Switch' label value, %s, not contained in enum type.
2744 This 'while' or 'for' loop controlling expression is a constant expression and its value is 'false'. The loop will not be entered.
2880 This code is unreachable.
2882 This 'switch' statement will bypass the initialization of local variables.
3219 Static function '%s()' is not used within this translation unit.
1503 The function '%1s' is defined but is not used within this project.
-
Rule-2.2RequiredThere shall be no dead code
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
2980 The value of this function parameter is never used before being modified.
2981 This initialization is redundant. The value of this object is never used before being modified.
2982 This assignment is redundant. The value of this object is never used before being modified.
2983 This assignment is redundant. The value of this object is never subsequently used.
2985 This operation is redundant. The value of the result is always that of the left-hand operand.
2986 This operation is redundant. The value of the result is always that of the right-hand operand.
2987 This function call produces no side effects and is redundant.
2995 The result of this logical operation is always 'true'.
2996 The result of this logical operation is always 'false'.
3110 The left-hand operand of this ',' has no side effects.
3112 This statement has no side-effect - it can be removed.
3404 Statement contains a redundant * operator at top level. *p++ means *(p++) not (*p)++.
3422 Statement contains a redundant operator at top level.
3423 Statement contains a redundant cast at top level.
3424 Statement contains a redundant & or | at top level.
3425 One branch of this conditional operation is a redundant expression.
3426 Right hand side of comma expression has no side effect and its value is not used.
3427 Right hand side of logical operator has no side effect and its value is not used.
-
Rule-2.3AdvisoryA project should not contain unused type declarations
- - - - - -
QacDescription
3205 The identifier '%s' is not used and could be removed.
-
Rule-2.4AdvisoryA project should not contain unused tag declarations
- - - - - - - - - -
QacDescription
3213 The tag '%s' is not used and could be removed.
1755 The tag '%1s' is declared but not used within this project.
-
Rule-2.5AdvisoryA project should not contain unused macro declarations
- - - - - -
QacDescription
3214 The macro '%s' is not used and could be removed.
-
Rule-2.6AdvisoryA function should not contain unused label declarations
- - - - - -
QacDescription
3202 The label '%s:' is not used in this function and could be removed.
-
Rule-2.7AdvisoryThere should be no unused parameters in functions
- - - - - -
QacDescription
3206 The parameter '%s' is not used in this function.
-
Rule-20.1Advisory#include directives should only be preceded by preprocessor directives or comments
- - - - - -
QacDescription
5087 Use of #include directive after code fragment.
-
Rule-20.10AdvisoryThe # and ## preprocessor operators should not be used
- - - - - - - - - -
QacDescription
0341 Using the stringify operator '#'.
0342 Using the glue operator '##'.
-
Rule-20.11RequiredA macro parameter immediately following a # operator shall not immediately be followed by a ## operator
- - - - - -
QacDescription
0892 This macro parameter is preceded by '#' and followed by '##'.
-
Rule-20.12RequiredA macro parameter used as an operand to the # or ## operators, which is itself subject to further macro replacement, shall only be used as an operand to these operators
- - - - - -
QacDescription
0893 Macro parameter '%s' is inconsistently subject to macro replacement.
-
Rule-20.13RequiredA line whose first token is # shall be a valid preprocessing directive
- - - - - -
QacDescription
3115 Unrecognized preprocessing directive has been ignored because of conditional inclusion directives.
-
Rule-20.14RequiredAll #else, #elif and #endif preprocessor directives shall reside in the same file as the #if, #ifdef or #ifndef directive to which they are related
- - - - - - - - - -
QacDescription
3317 '#if...' not matched by '#endif' in included file. This is probably an error.
3318 '#else'/'#elif'/'#endif' in included file matched '#if...' in parent file. This is probably an error.
-
Rule-20.2RequiredThe ', " or \ characters and the /* or // character sequences shall not occur in a header file name
- - - - - - - - - - - - - -
QacDescription
0813 [U] Using any of the characters ' " or /* in '#include <%s>' gives undefined behaviour.
0814 [U] Using the characters ' or /* in '#include "%s"' gives undefined behaviour.
0831 [E] Use of '\\' in this '#include' line is a PC extension - this usage is non-portable.
-
Rule-20.3RequiredThe #include directive shall be followed by either a or "filename" sequence
- - - - - - - - - - - - - -
QacDescription
0817 [S] Closing quote or bracket '>' missing from include filename.
0821 [C] '#include' does not identify a header or source file that can be processed.
0840 [E] Extra tokens at end of #include directive.
-
Rule-20.4RequiredA macro shall not be defined with the same name as a keyword
- - - - - - - - - -
QacDescription
3439 Macro redefines a keyword.
3468 The name of this macro is a reserved identifier in C90 and a keyword in C99.
-
Rule-20.5Advisory#undef should not be used
- - - - - -
QacDescription
0841 Using '#undef'.
-
Rule-20.6RequiredTokens that look like a preprocessing directive shall not occur within a macro argument
- - - - - -
QacDescription
0853 [U] Macro arguments contain a sequence of tokens that has the form of a preprocessing directive.
-
Rule-20.7RequiredExpressions resulting from the expansion of macro parameters shall be enclosed in parentheses
- - - - - - - - - -
QacDescription
3430 Macro argument expression may require parentheses.
3432 Simple macro argument expression is not parenthesized.
-
Rule-20.8RequiredThe controlling expression of a #if or #elif preprocessing directive shall evaluate to 0 or 1
- - - - - -
QacDescription
0894 '#%s' directive controlling expression does not evaluate to zero or one.
-
Rule-20.9RequiredAll identifiers used in the controlling expression of #if or #elif preprocessing directives shall be #define'd before evaluation
- - - - - -
QacDescription
3332 The macro '%s' used in this '#if' or '#elif' expression is not defined.
-
Rule-21.1Required#define and #undef shall not be used on a reserved identifier or reserved macro name
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
0603 [U] The macro identifier '%s' is reserved.
0836 [U] Definition of macro named 'defined'.
0848 [U] Attempting to #undef '%s', which is a predefined macro name.
0854 [U] Attempting to #define '%s', which is a predefined macro name.
4600 The macro '%1s' is also defined in '<%2s>'.
4601 The macro '%1s' is the name of an identifier in '<%2s>'.
4620 The macro '%1s' may also be defined as a macro in '<%2s>'.
4621 The macro '%1s' may also be defined as a typedef in '<%2s>'.
-
Rule-21.10RequiredThe Standard Library time and date functions shall not be used
- - - - - -
QacDescription
5127 Use of standard header file .
-
Rule-21.11RequiredThe standard header file shall not be used
- - - - - -
QacDescription
5131 Use of standard header file .
-
Rule-21.12AdvisoryThe exception handling features of should not be used
- - - - - -
QacDescription
5136 Use of exception handling identifier: feclearexcept, fegetexceptflag, feraiseexcept, fesetexceptflag or fetestexcept.
-
Rule-21.13MandatoryAny value passed to a function in shall be representable as an unsigned char or be the value EOF
- - - - - - - - - -
QacDescription
2796 Definite: Calling a standard library character handling function with an invalid character value.
2797 Apparent: Calling a standard library character handling function with an invalid character value.
-
Rule-21.14RequiredThe Standard Library function memcmp shall not be used to compare null terminated strings
- - - - - - - - - -
QacDescription
2785 Constant: Null terminated string is being passed as argument to Standard Library function memcmp.
2786 Definite: Null terminated string is being passed as argument to Standard Library function memcmp.
-
Rule-21.15RequiredThe pointer arguments to the Standard Library functions memcpy, memmove and memcmp shall be pointers to qualified or unqualified versions of compatible types
- - - - - - - - - - - - - -
QacDescription
1487 Comparing the representations of objects of different types.
1495 Destination and source objects have incompatible types.
1496 Destination and source objects may have incompatible types.
-
Rule-21.16RequiredThe pointer arguments to the Standard Library function memcpy shall point to either a pointer type, an essentially signed type, an essentially unsigned type, an essentially Boolean type or an essentially enum type
- - - - - - - - - - - - - - - - - - - - - -
QacDescription
1488 Comparison of a struct object representation.
1489 Comparison of a union object representation.
1490 Comparison of a floating point object representation.
1491 Comparison of an object representation.
1497 Comparison of a string object representation.
-
Rule-21.17MandatoryUse of the string handling functions from shall not result in accesses beyond the bounds of the objects referenced by their pointer parameters
- - - - - - - - - -
QacDescription
2835 Constant: Non null terminated string used in a string function.
2836 Definite: Non null terminated string used in a string function.
-
Rule-21.18MandatoryThe size_t argument passed to any function in shall have an appropriate value
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
2840 Constant: Dereference of an invalid pointer value.
2841 Definite: Dereference of an invalid pointer value.
2842 Apparent: Dereference of an invalid pointer value.
2865 Constant: Using 0 as size parameter of a function call.
2866 Definite: Using 0 as size parameter of a function call.
2867 Apparent: Using 0 as size parameter of a function call.
2868 Suspicious: Using 0 as size parameter of a function call.
2869 Possible: Using 0 as size parameter of a function call.
-
Rule-21.19MandatoryThe pointers returned by the Standard Library functions lovaleconv, getenv, setlocale or strerror shall only be used as if they have pointer to const-qualified type
- - - - - - - - - - - - - - - - - -
QacDescription
1492 The result of library function '%s' is used to modify the referenced object.
1493 The result of library function '%s' is used as a pointer to a modifiable object.
1494 The result of library function '%s' might be modified.
1498 The string referenced by type 'struct lconv' member '%s' is being modified.
-
Rule-21.2RequiredA reserved identifier or macro name shall not be declared
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
0602 [U] The identifier '%s' is reserved for use by the library.
4602 The identifier '%1s' is declared as a macro in '<%2s>'.
4603 The object/function '%1s'is being defined with the same name as an ordinary identifier defined in '<%2s>'.
4604 The object/function '%1s' is being declared with the same name as an ordinary identifier defined in '<%2s>'.
4605 The typedef '%1s' is also defined in '<%2s>'.
4606 The typedef '%1s' has the same name as another ordinary identifier in '<%2s>'.
4607 The enum constant '%1s' has the same name as another ordinary identifier in '<%2s>'.
4608 The tag '%1s' is also defined in '<%2s>'.
-
Rule-21.20MandatoryThe pointer returned by the Standard Library functions asctime, ctime, gmtime, localtime, localeconv, getenv, setlocale, or strerror shall not be used following a subsequent call to the same function
- - - - - - - - - -
QacDescription
2681 Definite: Using an invalidated value '%s' returned from a Standard Library function.
2682 Apparent: Using an invalidated value '%s' returned from a Standard Library function.
-
Rule-21.3RequiredThe memory allocation and deallocation functions of shall not be used
- - - - - -
QacDescription
5118 Use of memory allocation or deallocation function: calloc, malloc, realloc or free.
-
Rule-21.4RequiredThe standard header file shall not be used
- - - - - -
QacDescription
5132 Use of standard header file .
-
Rule-21.5RequiredThe standard header file shall not be used
- - - - - -
QacDescription
5123 Use of standard header file .
-
Rule-21.6RequiredThe Standard Library input/output functions shall not be used
- - - - - -
QacDescription
5124 The Standard Library input/output functions shall not be used
-
Rule-21.7RequiredThe atof, atoi, atol and atoll functions of shall not be used
- - - - - -
QacDescription
5125 Use of function: atof, atoi, atol or atoll.
-
Rule-21.8RequiredThe library functions abort, exit and system of shall not be used
- - - - - - - - - -
QacDescription
5126 Use of function: abort, exit or system.
5128 Use of function: getenv.
-
Rule-21.9RequiredThe library functions bsearch and qsort of shall not be used
- - - - - -
QacDescription
5135 Use of function: bsearch or qsort.
-
Rule-22.1RequiredAll resources obtained dynamically by means of Standard Library functions shall be explicitly released
- - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
2701 Definite: Opened file is not closed.
2702 Apparent: Opened file is not closed.
2706 Definite: Allocated memory is not deallocated.
2707 Apparent: Allocated memory is not deallocated.
2736 Definite: Created resource is not destroyed.
2737 Apparent: Created resource is not destroyed.
-
Rule-22.10RequiredThe value of errno shall only be tested when the last function to be called was an errno-setting-function
- - - - - -
QacDescription
2503 Testing of 'errno' is not immediately preceded by a call to an 'errno' setting function.
-
Rule-22.2MandatoryA block of memory shall only be freed if it was allocated by means of a Standard Library function
- - - - - - - - - -
QacDescription
2721 Definite: Deallocation of non dynamic memory.
2722 Apparent: Deallocation of non dynamic memory.
-
Rule-22.3RequiredThe same file shall not be open for read and write access at the same time on different streams
- - - - - - - - - - - - - -
QacDescription
2691 Definite: The same file will be open with write access and another mode.
2692 Apparent: The same file will be open with write access and another mode.
2693 Suspicious: The same file will be open with write access and another mode.
-
Rule-22.4MandatoryThere shall be no attempt to write to a stream which has been opened as read-only
- - - - - - - - - - - - - -
QacDescription
2686 Definite: Writing to a file opened for reading.
2687 Apparent: Writing to a file opened for reading.
2688 Suspicious: Writing to a file opened for reading.
-
Rule-22.5MandatoryA pointer to a FILE object shall not be dereferenced
- - - - - - - - - -
QacDescription
1485 A pointer to a FILE object is dereferenced.
1486 A pointer to a FILE object is converted to a different type.
-
Rule-22.6MandatoryThe value of a pointer to a FILE shall not be used after the associated stream has been closed
- - - - - - - - - -
QacDescription
2696 Definite: Attempt to access a file which has been closed.
2697 Apparent: Attempt to access a file which has been closed.
-
Rule-22.7RequiredThe macro EOF shall on ly be compared with the unmodified return value from any Standard Library function capable of returning EOF
- - - - - - - - - -
QacDescription
2671 Definite: The value being compared with macro EOF does not originate from an EOF returning function.
2676 Definite: The value originating from an EOF returning function was modified before being compared with macro EOF.
-
Rule-22.8RequiredThe value of errno shall be set to zero prior to a call to an errno-setting-function
- - - - - -
QacDescription
2500 Call to '%s' is not immediately preceded by the zeroing of 'errno'.
-
Rule-22.9RequiredThe value of errno shall be tested against zero after calling an errno-setting-function
- - - - - -
QacDescription
2501 Call to '%s' is not immediately followed by the testing of 'errno'.
-
Rule-3.1RequiredThe character sequences /* and // shall not be used within a comment.
- - - - - -
QacDescription
3108 Nested comments are not recognized in the ISO standard.
-
Rule-3.2RequiredLine-splicing shall not be used in // comments.
- - - - - -
QacDescription
5134 C++ style comment uses line splicing.
-
Rule-4.1RequiredOctal and hexadecimal escape sequences shall be terminated
- - - - - - - - - -
QacDescription
3636 Octal escape sequence '%s' is not terminated.
3637 Hexadecimal escape sequence '%s' is not terminated.
-
Rule-4.2AdvisoryTrigraphs should not be used
- - - - - -
QacDescription
3601 Trigraphs (??x) are an ISO feature.
-
Rule-5.1RequiredExternal identifiers shall be distinct
- - - - - -
QacDescription
0777 [U] External identifier does not differ from other identifier(s) (e.g. '%s') within the specified number of significant characters.
-
Rule-5.2RequiredIdentifiers declared in the same scope and name space shall be distinct
- - - - - -
QacDescription
0779 [U] Identifier does not differ from other identifier(s) (e.g. '%s') within the specified number of significant characters.
-
Rule-5.3RequiredAn identifier declared in an inner scope shall not hide an identifier declared in an outer scope
- - - - - - - - - - - - - -
QacDescription
0795 Identifier matches other identifier(s) (e.g. '%s') in an outer scope within the specified number of significant characters.
2547 This declaration of tag '%s' hides a more global declaration.
3334 This declaration of '%s' hides a more global declaration.
-
Rule-5.4RequiredMacro identifiers shall be distinct
- - - - - - - - - -
QacDescription
0788 This identifier, '%s', is used as both a macro name and a function-like macro parameter name.
0791 [U] Macro identifier does not differ from other macro identifier(s) (e.g. '%s') within the specified number of significant characters.
-
Rule-5.5RequiredIdentifiers shall be distinct from macro names
- - - - - - - - - - - - - - - - - -
QacDescription
0784 Identifier '%s' is also used as a macro name.
0785 Identifier matches other macro name(s) (e.g. '%s') in first 31 characters.
0786 Identifier matches other macro name(s) (e.g. '%s') in first 63 characters.
0787 Identifier does not differ from other macro name(s) (e.g. '%s') within the specified number of significant characters.
-
Rule-5.6RequiredA typedef name shall be a unique identifier
- - - - - - - - - - - - - -
QacDescription
1506 The identifier '%1s' is declared as a typedef and is used elsewhere for a different kind of declaration.
1507 '%1s' is used as a typedef for different types.
1508 The typedef '%1s' is declared in more than one location.
-
Rule-5.7RequiredA tag name shall be a unique identifier
- - - - - - - - - -
QacDescription
2547 This declaration of tag '%s' hides a more global declaration.
1750 '%1s' has multiple definitions.
-
Rule-5.8RequiredIdentifiers that define objects or functions with external linkage shall be unique
- - - - - - - - - - - - - -
QacDescription
1525 Object/function with external linkage has same identifier as another object/function with internal linkage.
1526 Object with no linkage has same identifier as another object/function with external linkage.
1756 External identifier '%1s' shall be unique.
-
Rule-5.9AdvisoryIdentifiers that define objects or functions with internal linkage should be unique
- - - - - - - - - - - - - -
QacDescription
1525 Object/function with external linkage has same identifier as another object/function with internal linkage.
1527 Object/function with internal linkage has same identifier as another object/function with internal linkage.
1528 Object with no linkage has same identifier as another object/function with internal linkage.
-
Rule-6.1RequiredBit-fields shall only be declared with an appropriate type
- - - - - - - - - -
QacDescription
0634 [I] Bit-fields in this struct/union have not been declared explicitly as unsigned or signed.
0635 [E] Bit-fields in this struct/union have been declared with types other than int, signed int, unsigned int or _Bool.
-
Rule-6.2RequiredSingle-bit named bit fields shall not be of a signed type
- - - - - -
QacDescription
3660 Named bit-field consisting of a single bit declared with a signed type.
-
Rule-7.1RequiredOctal constants shall not be used
- - - - - - - - - -
QacDescription
0336 Macro defined as an octal constant.
0339 Octal constant used.
-
Rule-7.2RequiredA "u" or "U" suffix shall be applied to all integer constants that are represented in an unsigned type
- - - - - -
QacDescription
1281 Integer literal constant is of an unsigned type but does not include a "U" suffix.
-
Rule-7.3RequiredThe lowercase character "l" shall not be used in a literal suffix
- - - - - -
QacDescription
1280 A lowercase letter L (l) has been used in an integer or floating suffix.
-
Rule-7.4RequiredA string literal shall not be assigned to an object unless the object's type is "pointer to const-qualified char"
- - - - - - - - - -
QacDescription
0752 String literal passed as argument to function whose parameter is not a 'pointer to const'.
0753 String literal assigned to pointer which is not a 'pointer to const'.
-
Rule-8.1RequiredTypes shall be explicitly specified
- - - - - - - - - - - - - -
QacDescription
2050 The 'int' type specifier has been omitted from a function declaration.
2051 The 'int' type specifier has been omitted from an object declaration.
1525 Object/function with external linkage has same identifier as another object/function with internal linkage.
-
Rule-8.10RequiredAn inline function shall be declared with the static storage class
- - - - - - - - - -
QacDescription
3240 inline function '%s' is being defined with external linkage.
3243 inline function '%s' is also an 'external definition'.
-
Rule-8.11AdvisoryWhen an array with external linkage is declared, its size should be explicitly specified
- - - - - -
QacDescription
3684 Array declared with unknown size.
-
Rule-8.12RequiredWithin an enumerator list, the value of an implicitly-specified enumeration constant shall be unique
- - - - - -
QacDescription
0724 The value of this implicitly-specified enumeration constant is not unique.
-
Rule-8.13AdvisoryA pointer should point to a const-qualified type whenever possible
- - - - - -
QacDescription
3673 The object addressed by the pointer parameter '%s' is not modified and so the pointer could be of type 'pointer to const'.
-
Rule-8.14RequiredThe restrict type qualifier shall not be used
- - - - - -
QacDescription
1057 [C99] The keyword 'restrict' has been used.
-
Rule-8.2RequiredFunction types shall be in prototype form with named parameters
- - - - - - - - - - - - - - - - - - - - - -
QacDescription
1335 Parameter identifiers missing in function prototype declaration.
1336 Parameter identifiers missing in declaration of a function type.
3001 Function has been declared with an empty parameter list.
3002 Defining '%s()' with an identifier list and separate parameter declarations is an obsolescent feature.
3007 "void" has been omitted when defining a function with no parameters.
-
Rule-8.3RequiredAll declarations of an object or function shall use the same names and type qualifiers
- - - - - - - - - - - - - -
QacDescription
0624 Function '%s' is declared using typedefs which are different to those in a previous declaration.
1330 The parameter identifiers in this function declaration differ from those in a previous declaration.
3675 Function parameter declared with type qualification which differs from previous declaration.
-
Rule-8.4RequiredA compatible declaration shall be visible when an object or function with external linkage is defined
- - - - - -
QacDescription
3408 '%s' has external linkage and is being defined without any previous declaration.
-
Rule-8.5RequiredAn external object or function shall be declared once in one and only one file
- - - - - - - - - - - - - -
QacDescription
3449 Multiple declarations of external object or function.
3451 The global identifier '%s' has been declared in more than one file.
1513 Identifier '%1s' with external linkage has separate non-defining declarations in more than one location.
-
Rule-8.6RequiredAn identifier with external linkage shall have exactly one external definition
- - - - - - - - - - - - - - - - - - - - - -
QacDescription
0630 [U] More than one definition of '%s' (with external linkage).
3406 Object/function '%s', with external linkage, has been defined in a header file.
1509 '%1s' has external linkage and has multiple definitions.
1752 The object '%1s' with external linkage is declared but not defined within this project.
1753 The function '%1s' with external linkage is declared but not defined within this project.
-
Rule-8.7AdvisoryFunctions and objects should not be defined with external linkage if they are referenced in only one translation unit
- - - - - - - - - - - - - - - - - -
QacDescription
1504 The object '%1s' is only referenced in the translation unit where it is defined.
1505 The function '%1s' is only referenced in the translation unit where it is defined.
1531 The object '%1s' is referenced in only one translation unit - but not the one in which it is defined.
1532 The function '%1s' is only referenced in one translation unit - but not the one in which it is defined.
-
Rule-8.8RequiredThe static storage class specifier shall be used in all declarations of objects and functions that have internal linkage
- - - - - -
QacDescription
3224 This identifier has previously been declared with internal linkage but is not declared here with the static storage class specifier.
-
Rule-8.9AdvisoryAn object should be defined at block scope if its identifier only appears in a single function
- - - - - - - - - - - - - -
QacDescription
3218 File scope static, '%s', is only accessed in one function.
1514 The object '%1s' is only referenced by function '%2s', in the translation unit where it is defined
1533 The object '%1s' is only referenced by function '%2s'.
-
Rule-9.1MandatoryThe value of an object with automatic storage duration shall not be read before it has been set
- - - - - - - - - - - - - - - - - - - - - -
QacDescription
2883 This 'goto' statement will always bypass the initialization of local variables.
2961 Definite: Using value of uninitialized automatic object '%s'.
2962 Apparent: Using value of uninitialized automatic object '%s'.
2971 Definite: Passing address of uninitialized object '%s' to a function parameter declared as a pointer to const.
2972 Apparent: Passing address of uninitialized object '%s' to a function parameter declared as a pointer to const.
-
Rule-9.2RequiredThe initializer for an aggregate or union shall be enclosed in braces
- - - - - - - - - -
QacDescription
0693 Struct initializer is missing the optional {.
0694 Array initializer is missing the optional {.
-
Rule-9.3RequiredArrays shall not be partially initialized
- - - - - -
QacDescription
0686 Array has fewer initializers than its declared size. Default initialization is applied to the remainder of the array elements.
-
Rule-9.4RequiredAn element of an object shall not be initialized more than once
- - - - - - - - - - - - - -
QacDescription
1397 Array element '%s' has already been initialized.
1398 Structure member '%s' has already been initialized.
1399 A union member has already been initialized.
-
Rule-9.5RequiredWhere designated initializers are used to initialize an array object the size of the array shall be specified explicitly
- - - - - -
QacDescription
3676 Designators are used to initialize an array of unspecified size.
-
-
-
- -This section targets to provide an overview of Guidelines Recategorization Plan. -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GuidelineDescriptionCategoryRevised Category
Dir-1.1Any implementation-defined behaviour on which the output of the program depends shall be documented and understoodRequiredRequired
Dir-2.1All source files shall compile without any compilation errorsRequiredDisapplied
Dir-3.1All code shall be traceable to documented requirementsRequiredDisapplied
Dir-4.1Run-time failures shall be minimizedRequiredRequired
Dir-4.10Precautions shall be taken in order to prevent the contents of a header file being included more then onceRequiredRequired
Dir-4.11The validity of values passed to library functions shall be checkedRequiredDisapplied
Dir-4.12Dynamic memory allocation shall not be usedRequiredDisapplied
Dir-4.13Functions which are designed to provide operations on a resource should be called in an appropriate sequenceAdvisoryDisapplied
Dir-4.14The validity of values received from external sources shall be checkedRequiredRequired
Dir-4.2All usage of assembly language should be documentedAdvisoryAdvisory
Dir-4.3Assembly language shall be encapsulated and isolatedRequiredRequired
Dir-4.4Sections of code should not be "commented out"AdvisoryDisapplied
Dir-4.5Identifiers in the same name space with overlapping visibility should be typographically unambiguousAdvisoryDisapplied
Dir-4.6typedefs that indicate size and signedness should be used in place of the basic numerical typesAdvisoryAdvisory
Dir-4.7If a function returns error information, then that error information shall be testedRequiredDisapplied
Dir-4.8If a pointer to a structure or union is never dereferenced within a translation unit, then the implementation of the object should be hiddenAdvisoryDisapplied
Dir-4.9A function should be used in preference to a function-like macro where they are interchangeableAdvisoryDisapplied
Rule-1.1The program shall contain no violations of the standard C syntax and constraints, and shall not exceed the implementation's translation limitsRequiredRequired
Rule-1.2Language extensions should not be usedAdvisoryAdvisory
Rule-1.3There shall be no occurrence of undefined or critical unspecified behaviourRequiredRequired
Rule-10.1Operands shall not be of an inappropriate essential type.RequiredRequired
Rule-10.2Expressions of essentially character type shall not be used inappropriately in addition and subtraction operationsRequiredRequired
Rule-10.3The value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category.RequiredRequired
Rule-10.4Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type categoryRequiredRequired
Rule-10.5The value of an expression should not be cast to an inappropriate essential typeAdvisoryAdvisory
Rule-10.6The value of a composite expression shall not be assigned to an object with wider essential typeRequiredRequired
Rule-10.7If a composite expression is used as one operand of an operator in which the usual arithmetic conversions are performed then the other operand shall not have wider essential typeRequiredRequired
Rule-10.8The value of a composite expression shall not be cast to a different essential type category or a wider essential typeRequiredRequired
Rule-11.1Conversions shall not be performed between a pointer to a function and any other typeRequiredRequired
Rule-11.2Conversions shall not be performed between a pointer to an incomplete type and any other typeRequiredRequired
Rule-11.3A cast shall not be performed between a pointer to object type and a pointer to a different object typeRequiredRequired
Rule-11.4A conversion should not be performed between a pointer to object and an integer typeAdvisoryAdvisory
Rule-11.5A conversion should not be performed from pointer to void into pointer to objectAdvisoryAdvisory
Rule-11.6A cast shall not be performed between pointer to void and an arithmetic typeRequiredRequired
Rule-11.7A cast shall not be performed between pointer to object and a non-integer arithmetic typeRequiredRequired
Rule-11.8A cast shall not remove any const or volatile qualification from the type pointed to by a pointerRequiredRequired
Rule-11.9The macro NULL shall be the only permitted form of integer null pointer constantRequiredDisapplied
Rule-12.1The precedence of operators within expressions should be made explicitAdvisoryAdvisory
Rule-12.2The right hand operand of a shift operator shall lie in the range zero to one less than the width in bits of the essential type of the left hand operandRequiredRequired
Rule-12.3The comma operator should not be usedAdvisoryAdvisory
Rule-12.4Evaluation of constant expressions should not lead to unsigned integer wrap-aroundAdvisoryAdvisory
Rule-12.5The sizeof operator shall not have an operand which is a function parameter declared as 'array of type'MandatoryMandatory
Rule-13.1Initializer lists shall not contain persistent side-effectsRequiredRequired
Rule-13.2The value of an expression and its persistent side-effects shall be the same under all permitted evaluation ordersRequiredRequired
Rule-13.3A full expression containing an increment (++) or decrement (--) operator should have no other potential side effects other than that caused by the increment or decrement operatorAdvisoryDisapplied
Rule-13.4The result of an assignment operator should not be usedAdvisoryAdvisory
Rule-13.5The right hand operand of a logical && or || operator shall not contain persistent side effectsRequiredRequired
Rule-13.6The operand of the sizeof operator shall not contain any expression which has potential side-effectsMandatoryMandatory
Rule-14.1A loop counter shall not have essentially floating typeRequiredRequired
Rule-14.2A for loop shall be well-formedRequiredRequired
Rule-14.3Controlling expressions shall not be invariantRequiredRequired
Rule-14.4The controlling expression of an if-statement and the controlling expression of an iteration-statement shall have essentially Boolean typeRequiredRequired
Rule-15.1The goto statement should not be usedAdvisoryAdvisory
Rule-15.2The goto statement shall jump to a label declared later in the same functionRequiredRequired
Rule-15.3Any label referenced by a goto statement shall be declared in the same block, or in any block enclosing the goto statementRequiredRequired
Rule-15.4There should be no more than one break or goto statement used to terminate any iteration statementAdvisoryAdvisory
Rule-15.5A function should have a single point of exit at the endAdvisoryDisapplied
Rule-15.6The body of an iteration-statement or a selection-statement shall be a compound-statementRequiredRequired
Rule-15.7All if ... else if constructs shall be terminated with an else statementRequiredRequired
Rule-16.1All switch statements shall be well-formedRequiredRequired
Rule-16.2A switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statementRequiredRequired
Rule-16.3An unconditional break statement shall terminate every switch-clauseRequiredRequired
Rule-16.4Every switch statement shall have a default labelRequiredRequired
Rule-16.5A default label shall appear as either the first or the last switch label of a switch statementRequiredRequired
Rule-16.6Every switch statement shall have at least two switch-clausesRequiredRequired
Rule-16.7A switch-expression shall not have essentially Boolean typeRequiredRequired
Rule-17.1The features of shall not be usedRequiredRequired
Rule-17.2Functions shall not call themselves, either directly or indirectlyRequiredRequired
Rule-17.3A function shall not be declared implicitlyMandatoryMandatory
Rule-17.4All exit paths from a function with non-void return type shall have an explicit return statement with an expressionMandatoryMandatory
Rule-17.5The function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elementsAdvisoryAdvisory
Rule-17.6The declaration of an array parameter shall not contain the static keyword between the [ ]MandatoryMandatory
Rule-17.7The value returned by a function having non-void return type shall be usedRequiredDisapplied
Rule-17.8A function parameter should not be modifiedAdvisoryAdvisory
Rule-18.1A pointer resulting from arithmetic on a pointer operand shall address an element of the same array as that pointer operandRequiredRequired
Rule-18.2Subtraction between pointers shall only be applied to pointers that address elements of the same arrayRequiredRequired
Rule-18.3The relational operators >, >=, < and <= shall not be applied to objects of pointer type except where they point into the same objectRequiredRequired
Rule-18.4The +, -, += and -= operators should not be applied to an expression of pointer typeAdvisoryAdvisory
Rule-18.5Declarations should contain no more than two levels of pointer nestingAdvisoryAdvisory
Rule-18.6The address of an object with automatic storage shall not be copied to another object that persists after the first object has ceased to existRequiredRequired
Rule-18.7Flexible array members shall not be declaredRequiredRequired
Rule-18.8Variable-length array types shall not be usedRequiredRequired
Rule-19.1An object shall not be assigned or copied to an overlapping objectMandatoryMandatory
Rule-19.2The union keyword should not be usedAdvisoryAdvisory
Rule-2.1A project shall not contain unreachable codeRequiredRequired
Rule-2.2There shall be no dead codeRequiredRequired
Rule-2.3A project should not contain unused type declarationsAdvisoryDisapplied
Rule-2.4A project should not contain unused tag declarationsAdvisoryAdvisory
Rule-2.5A project should not contain unused macro declarationsAdvisoryDisapplied
Rule-2.6A function should not contain unused label declarationsAdvisoryAdvisory
Rule-2.7There should be no unused parameters in functionsAdvisoryAdvisory
Rule-20.1#include directives should only be preceded by preprocessor directives or commentsAdvisoryAdvisory
Rule-20.10The # and ## preprocessor operators should not be usedAdvisoryAdvisory
Rule-20.11A macro parameter immediately following a # operator shall not immediately be followed by a ## operatorRequiredRequired
Rule-20.12A macro parameter used as an operand to the # or ## operators, which is itself subject to further macro replacement, shall only be used as an operand to these operatorsRequiredRequired
Rule-20.13A line whose first token is # shall be a valid preprocessing directiveRequiredRequired
Rule-20.14All #else, #elif and #endif preprocessor directives shall reside in the same file as the #if, #ifdef or #ifndef directive to which they are relatedRequiredRequired
Rule-20.2The ', " or \ characters and the /* or // character sequences shall not occur in a header file nameRequiredRequired
Rule-20.3The #include directive shall be followed by either a or "filename" sequenceRequiredRequired
Rule-20.4A macro shall not be defined with the same name as a keywordRequiredRequired
Rule-20.5#undef should not be usedAdvisoryAdvisory
Rule-20.6Tokens that look like a preprocessing directive shall not occur within a macro argumentRequiredRequired
Rule-20.7Expressions resulting from the expansion of macro parameters shall be enclosed in parenthesesRequiredRequired
Rule-20.8The controlling expression of a #if or #elif preprocessing directive shall evaluate to 0 or 1RequiredRequired
Rule-20.9All identifiers used in the controlling expression of #if or #elif preprocessing directives shall be #define'd before evaluationRequiredRequired
Rule-21.1#define and #undef shall not be used on a reserved identifier or reserved macro nameRequiredRequired
Rule-21.10The Standard Library time and date functions shall not be usedRequiredRequired
Rule-21.11The standard header file shall not be usedRequiredRequired
Rule-21.12The exception handling features of should not be usedAdvisoryAdvisory
Rule-21.13Any value passed to a function in shall be representable as an unsigned char or be the value EOFMandatoryMandatory
Rule-21.14The Standard Library function memcmp shall not be used to compare null terminated stringsRequiredRequired
Rule-21.15The pointer arguments to the Standard Library functions memcpy, memmove and memcmp shall be pointers to qualified or unqualified versions of compatible typesRequiredRequired
Rule-21.16The pointer arguments to the Standard Library function memcpy shall point to either a pointer type, an essentially signed type, an essentially unsigned type, an essentially Boolean type or an essentially enum typeRequiredRequired
Rule-21.17Use of the string handling functions from shall not result in accesses beyond the bounds of the objects referenced by their pointer parametersMandatoryMandatory
Rule-21.18The size_t argument passed to any function in shall have an appropriate valueMandatoryMandatory
Rule-21.19The pointers returned by the Standard Library functions lovaleconv, getenv, setlocale or strerror shall only be used as if they have pointer to const-qualified typeMandatoryMandatory
Rule-21.2A reserved identifier or macro name shall not be declaredRequiredRequired
Rule-21.20The pointer returned by the Standard Library functions asctime, ctime, gmtime, localtime, localeconv, getenv, setlocale, or strerror shall not be used following a subsequent call to the same functionMandatoryMandatory
Rule-21.3The memory allocation and deallocation functions of shall not be usedRequiredRequired
Rule-21.4The standard header file shall not be usedRequiredRequired
Rule-21.5The standard header file shall not be usedRequiredRequired
Rule-21.6The Standard Library input/output functions shall not be usedRequiredRequired
Rule-21.7The atof, atoi, atol and atoll functions of shall not be usedRequiredRequired
Rule-21.8The library functions abort, exit and system of shall not be usedRequiredRequired
Rule-21.9The library functions bsearch and qsort of shall not be usedRequiredRequired
Rule-22.1All resources obtained dynamically by means of Standard Library functions shall be explicitly releasedRequiredRequired
Rule-22.10The value of errno shall only be tested when the last function to be called was an errno-setting-functionRequiredRequired
Rule-22.2A block of memory shall only be freed if it was allocated by means of a Standard Library functionMandatoryMandatory
Rule-22.3The same file shall not be open for read and write access at the same time on different streamsRequiredRequired
Rule-22.4There shall be no attempt to write to a stream which has been opened as read-onlyMandatoryMandatory
Rule-22.5A pointer to a FILE object shall not be dereferencedMandatoryMandatory
Rule-22.6The value of a pointer to a FILE shall not be used after the associated stream has been closedMandatoryMandatory
Rule-22.7The macro EOF shall on ly be compared with the unmodified return value from any Standard Library function capable of returning EOFRequiredRequired
Rule-22.8The value of errno shall be set to zero prior to a call to an errno-setting-functionRequiredRequired
Rule-22.9The value of errno shall be tested against zero after calling an errno-setting-functionRequiredRequired
Rule-3.1The character sequences /* and // shall not be used within a comment.RequiredRequired
Rule-3.2Line-splicing shall not be used in // comments.RequiredRequired
Rule-4.1Octal and hexadecimal escape sequences shall be terminatedRequiredRequired
Rule-4.2Trigraphs should not be usedAdvisoryAdvisory
Rule-5.1External identifiers shall be distinctRequiredRequired
Rule-5.2Identifiers declared in the same scope and name space shall be distinctRequiredRequired
Rule-5.3An identifier declared in an inner scope shall not hide an identifier declared in an outer scopeRequiredRequired
Rule-5.4Macro identifiers shall be distinctRequiredRequired
Rule-5.5Identifiers shall be distinct from macro namesRequiredRequired
Rule-5.6A typedef name shall be a unique identifierRequiredRequired
Rule-5.7A tag name shall be a unique identifierRequiredRequired
Rule-5.8Identifiers that define objects or functions with external linkage shall be uniqueRequiredRequired
Rule-5.9Identifiers that define objects or functions with internal linkage should be uniqueAdvisoryAdvisory
Rule-6.1Bit-fields shall only be declared with an appropriate typeRequiredRequired
Rule-6.2Single-bit named bit fields shall not be of a signed typeRequiredRequired
Rule-7.1Octal constants shall not be usedRequiredRequired
Rule-7.2A "u" or "U" suffix shall be applied to all integer constants that are represented in an unsigned typeRequiredRequired
Rule-7.3The lowercase character "l" shall not be used in a literal suffixRequiredRequired
Rule-7.4A string literal shall not be assigned to an object unless the object's type is "pointer to const-qualified char"RequiredRequired
Rule-8.1Types shall be explicitly specifiedRequiredRequired
Rule-8.10An inline function shall be declared with the static storage classRequiredRequired
Rule-8.11When an array with external linkage is declared, its size should be explicitly specifiedAdvisoryAdvisory
Rule-8.12Within an enumerator list, the value of an implicitly-specified enumeration constant shall be uniqueRequiredRequired
Rule-8.13A pointer should point to a const-qualified type whenever possibleAdvisoryAdvisory
Rule-8.14The restrict type qualifier shall not be usedRequiredRequired
Rule-8.2Function types shall be in prototype form with named parametersRequiredRequired
Rule-8.3All declarations of an object or function shall use the same names and type qualifiersRequiredRequired
Rule-8.4A compatible declaration shall be visible when an object or function with external linkage is definedRequiredRequired
Rule-8.5An external object or function shall be declared once in one and only one fileRequiredRequired
Rule-8.6An identifier with external linkage shall have exactly one external definitionRequiredRequired
Rule-8.7Functions and objects should not be defined with external linkage if they are referenced in only one translation unitAdvisoryDisapplied
Rule-8.8The static storage class specifier shall be used in all declarations of objects and functions that have internal linkageRequiredRequired
Rule-8.9An object should be defined at block scope if its identifier only appears in a single functionAdvisoryAdvisory
Rule-9.1The value of an object with automatic storage duration shall not be read before it has been setMandatoryMandatory
Rule-9.2The initializer for an aggregate or union shall be enclosed in bracesRequiredRequired
Rule-9.3Arrays shall not be partially initializedRequiredRequired
Rule-9.4An element of an object shall not be initialized more than onceRequiredRequired
Rule-9.5Where designated initializers are used to initialize an array object the size of the array shall be specified explicitlyRequiredRequired
-
-
- -This section targets to provide an overview of Guidelines Compliance Summary. -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GuidelineCategoryDescriptionCompliance
Dir-1.1RequiredAny implementation-defined behaviour on which the output of the program depends shall be documented and understoodCompliant

with deviations:
-
- - - - - - - - - - - - - -
QacDescription
0292 [I] Source file '%s' has comments containing one of the characters '$', '@' or '`'.
0315 [I] Implicit conversion from a pointer to object type to a pointer to void.
0380 [L] Number of macro definitions exceeds 4095 - program does not conform strictly to ISO:C99.
-
Dir-2.1RequiredAll source files shall compile without any compilation errorsDisapplied
Dir-3.1RequiredAll code shall be traceable to documented requirementsDisapplied
Dir-4.1RequiredRun-time failures shall be minimizedCompliant
Dir-4.10RequiredPrecautions shall be taken in order to prevent the contents of a header file being included more then onceCompliant
Dir-4.11RequiredThe validity of values passed to library functions shall be checkedDisapplied
Dir-4.12RequiredDynamic memory allocation shall not be usedDisapplied
Dir-4.13AdvisoryFunctions which are designed to provide operations on a resource should be called in an appropriate sequenceDisapplied
Dir-4.14RequiredThe validity of values received from external sources shall be checkedCompliant
Dir-4.2AdvisoryAll usage of assembly language should be documentedCompliant
Dir-4.3RequiredAssembly language shall be encapsulated and isolatedCompliant
Dir-4.4AdvisorySections of code should not be "commented out"Disapplied
Dir-4.5AdvisoryIdentifiers in the same name space with overlapping visibility should be typographically unambiguousDisapplied
Dir-4.6Advisorytypedefs that indicate size and signedness should be used in place of the basic numerical typesCompliant
Dir-4.7RequiredIf a function returns error information, then that error information shall be testedDisapplied
Dir-4.8AdvisoryIf a pointer to a structure or union is never dereferenced within a translation unit, then the implementation of the object should be hiddenDisapplied
Dir-4.9AdvisoryA function should be used in preference to a function-like macro where they are interchangeableDisapplied
Rule-1.1RequiredThe program shall contain no violations of the standard C syntax and constraints, and shall not exceed the implementation's translation limitsCompliant
Rule-1.2AdvisoryLanguage extensions should not be usedCompliant
Rule-1.3RequiredThere shall be no occurrence of undefined or critical unspecified behaviourCompliant
Rule-10.1RequiredOperands shall not be of an inappropriate essential type.Compliant
Rule-10.2RequiredExpressions of essentially character type shall not be used inappropriately in addition and subtraction operationsCompliant
Rule-10.3RequiredThe value of an expression shall not be assigned to an object with a narrower essential type or of a different essential type category.Compliant
Rule-10.4RequiredBoth operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type categoryCompliant
Rule-10.5AdvisoryThe value of an expression should not be cast to an inappropriate essential typeCompliant
Rule-10.6RequiredThe value of a composite expression shall not be assigned to an object with wider essential typeCompliant
Rule-10.7RequiredIf a composite expression is used as one operand of an operator in which the usual arithmetic conversions are performed then the other operand shall not have wider essential typeCompliant
Rule-10.8RequiredThe value of a composite expression shall not be cast to a different essential type category or a wider essential typeCompliant
Rule-11.1RequiredConversions shall not be performed between a pointer to a function and any other typeCompliant
Rule-11.2RequiredConversions shall not be performed between a pointer to an incomplete type and any other typeCompliant
Rule-11.3RequiredA cast shall not be performed between a pointer to object type and a pointer to a different object typeCompliant
Rule-11.4AdvisoryA conversion should not be performed between a pointer to object and an integer typeCompliant

with deviations:
-
- - - - - -
QacDescription
0306 [I] Cast between a pointer to object and an integral type.
-
Rule-11.5AdvisoryA conversion should not be performed from pointer to void into pointer to objectCompliant
Rule-11.6RequiredA cast shall not be performed between pointer to void and an arithmetic typeCompliant
Rule-11.7RequiredA cast shall not be performed between pointer to object and a non-integer arithmetic typeCompliant
Rule-11.8RequiredA cast shall not remove any const or volatile qualification from the type pointed to by a pointerCompliant
Rule-11.9RequiredThe macro NULL shall be the only permitted form of integer null pointer constantDisapplied
Rule-12.1AdvisoryThe precedence of operators within expressions should be made explicitCompliant
Rule-12.2RequiredThe right hand operand of a shift operator shall lie in the range zero to one less than the width in bits of the essential type of the left hand operandCompliant
Rule-12.3AdvisoryThe comma operator should not be usedCompliant
Rule-12.4AdvisoryEvaluation of constant expressions should not lead to unsigned integer wrap-aroundCompliant
Rule-12.5MandatoryThe sizeof operator shall not have an operand which is a function parameter declared as 'array of type'Compliant
Rule-13.1RequiredInitializer lists shall not contain persistent side-effectsCompliant
Rule-13.2RequiredThe value of an expression and its persistent side-effects shall be the same under all permitted evaluation ordersCompliant
Rule-13.3AdvisoryA full expression containing an increment (++) or decrement (--) operator should have no other potential side effects other than that caused by the increment or decrement operatorDisapplied
Rule-13.4AdvisoryThe result of an assignment operator should not be usedCompliant
Rule-13.5RequiredThe right hand operand of a logical && or || operator shall not contain persistent side effectsCompliant
Rule-13.6MandatoryThe operand of the sizeof operator shall not contain any expression which has potential side-effectsCompliant
Rule-14.1RequiredA loop counter shall not have essentially floating typeCompliant
Rule-14.2RequiredA for loop shall be well-formedCompliant
Rule-14.3RequiredControlling expressions shall not be invariantCompliant

with deviations:
-
- - - - - - - - - - - - - - - - - - - - - -
QacDescription
2991 The value of this 'if' controlling expression is always 'true'.
2992 The value of this 'if' controlling expression is always 'false'.
2998 The first operand of this conditional operator is always 'false'.
3493 The first operand of this conditional operator is always constant 'true'.
3494 The first operand of this conditional operator is always constant 'false'.
-
Rule-14.4RequiredThe controlling expression of an if-statement and the controlling expression of an iteration-statement shall have essentially Boolean typeCompliant
Rule-15.1AdvisoryThe goto statement should not be usedCompliant
Rule-15.2RequiredThe goto statement shall jump to a label declared later in the same functionCompliant
Rule-15.3RequiredAny label referenced by a goto statement shall be declared in the same block, or in any block enclosing the goto statementCompliant
Rule-15.4AdvisoryThere should be no more than one break or goto statement used to terminate any iteration statementCompliant
Rule-15.5AdvisoryA function should have a single point of exit at the endDisapplied
Rule-15.6RequiredThe body of an iteration-statement or a selection-statement shall be a compound-statementCompliant
Rule-15.7RequiredAll if ... else if constructs shall be terminated with an else statementCompliant
Rule-16.1RequiredAll switch statements shall be well-formedCompliant
Rule-16.2RequiredA switch label shall only be used when the most closely-enclosing compound statement is the body of a switch statementCompliant
Rule-16.3RequiredAn unconditional break statement shall terminate every switch-clauseCompliant
Rule-16.4RequiredEvery switch statement shall have a default labelCompliant
Rule-16.5RequiredA default label shall appear as either the first or the last switch label of a switch statementCompliant
Rule-16.6RequiredEvery switch statement shall have at least two switch-clausesCompliant
Rule-16.7RequiredA switch-expression shall not have essentially Boolean typeCompliant
Rule-17.1RequiredThe features of shall not be usedCompliant
Rule-17.2RequiredFunctions shall not call themselves, either directly or indirectlyCompliant
Rule-17.3MandatoryA function shall not be declared implicitlyCompliant
Rule-17.4MandatoryAll exit paths from a function with non-void return type shall have an explicit return statement with an expressionCompliant
Rule-17.5AdvisoryThe function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elementsCompliant
Rule-17.6MandatoryThe declaration of an array parameter shall not contain the static keyword between the [ ]Compliant
Rule-17.7RequiredThe value returned by a function having non-void return type shall be usedDisapplied
Rule-17.8AdvisoryA function parameter should not be modifiedCompliant
Rule-18.1RequiredA pointer resulting from arithmetic on a pointer operand shall address an element of the same array as that pointer operandCompliant
Rule-18.2RequiredSubtraction between pointers shall only be applied to pointers that address elements of the same arrayCompliant
Rule-18.3RequiredThe relational operators >, >=, < and <= shall not be applied to objects of pointer type except where they point into the same objectCompliant
Rule-18.4AdvisoryThe +, -, += and -= operators should not be applied to an expression of pointer typeCompliant
Rule-18.5AdvisoryDeclarations should contain no more than two levels of pointer nestingCompliant
Rule-18.6RequiredThe address of an object with automatic storage shall not be copied to another object that persists after the first object has ceased to existCompliant
Rule-18.7RequiredFlexible array members shall not be declaredCompliant
Rule-18.8RequiredVariable-length array types shall not be usedCompliant
Rule-19.1MandatoryAn object shall not be assigned or copied to an overlapping objectCompliant
Rule-19.2AdvisoryThe union keyword should not be usedCompliant
Rule-2.1RequiredA project shall not contain unreachable codeCompliant

with deviations:
-
- - - - - -
QacDescription
1503 The function '%1s' is defined but is not used within this project.
-
Rule-2.2RequiredThere shall be no dead codeCompliant

with deviations:
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
2982 This assignment is redundant. The value of this object is never used before being modified.
2983 This assignment is redundant. The value of this object is never subsequently used.
2985 This operation is redundant. The value of the result is always that of the left-hand operand.
2986 This operation is redundant. The value of the result is always that of the right-hand operand.
2995 The result of this logical operation is always 'true'.
2996 The result of this logical operation is always 'false'.
3112 This statement has no side-effect - it can be removed.
-
Rule-2.3AdvisoryA project should not contain unused type declarationsDisapplied
Rule-2.4AdvisoryA project should not contain unused tag declarationsCompliant
Rule-2.5AdvisoryA project should not contain unused macro declarationsDisapplied
Rule-2.6AdvisoryA function should not contain unused label declarationsCompliant
Rule-2.7AdvisoryThere should be no unused parameters in functionsCompliant
Rule-20.1Advisory#include directives should only be preceded by preprocessor directives or commentsCompliant
Rule-20.10AdvisoryThe # and ## preprocessor operators should not be usedCompliant
Rule-20.11RequiredA macro parameter immediately following a # operator shall not immediately be followed by a ## operatorCompliant
Rule-20.12RequiredA macro parameter used as an operand to the # or ## operators, which is itself subject to further macro replacement, shall only be used as an operand to these operatorsCompliant
Rule-20.13RequiredA line whose first token is # shall be a valid preprocessing directiveCompliant
Rule-20.14RequiredAll #else, #elif and #endif preprocessor directives shall reside in the same file as the #if, #ifdef or #ifndef directive to which they are relatedCompliant
Rule-20.2RequiredThe ', " or \ characters and the /* or // character sequences shall not occur in a header file nameCompliant
Rule-20.3RequiredThe #include directive shall be followed by either a or "filename" sequenceCompliant
Rule-20.4RequiredA macro shall not be defined with the same name as a keywordCompliant
Rule-20.5Advisory#undef should not be usedCompliant
Rule-20.6RequiredTokens that look like a preprocessing directive shall not occur within a macro argumentCompliant
Rule-20.7RequiredExpressions resulting from the expansion of macro parameters shall be enclosed in parenthesesCompliant
Rule-20.8RequiredThe controlling expression of a #if or #elif preprocessing directive shall evaluate to 0 or 1Compliant
Rule-20.9RequiredAll identifiers used in the controlling expression of #if or #elif preprocessing directives shall be #define'd before evaluationCompliant
Rule-21.1Required#define and #undef shall not be used on a reserved identifier or reserved macro nameCompliant
Rule-21.10RequiredThe Standard Library time and date functions shall not be usedCompliant
Rule-21.11RequiredThe standard header file shall not be usedCompliant
Rule-21.12AdvisoryThe exception handling features of should not be usedCompliant
Rule-21.13MandatoryAny value passed to a function in shall be representable as an unsigned char or be the value EOFCompliant
Rule-21.14RequiredThe Standard Library function memcmp shall not be used to compare null terminated stringsCompliant
Rule-21.15RequiredThe pointer arguments to the Standard Library functions memcpy, memmove and memcmp shall be pointers to qualified or unqualified versions of compatible typesCompliant
Rule-21.16RequiredThe pointer arguments to the Standard Library function memcpy shall point to either a pointer type, an essentially signed type, an essentially unsigned type, an essentially Boolean type or an essentially enum typeCompliant
Rule-21.17MandatoryUse of the string handling functions from shall not result in accesses beyond the bounds of the objects referenced by their pointer parametersCompliant
Rule-21.18MandatoryThe size_t argument passed to any function in shall have an appropriate valueCompliant
Rule-21.19MandatoryThe pointers returned by the Standard Library functions lovaleconv, getenv, setlocale or strerror shall only be used as if they have pointer to const-qualified typeCompliant
Rule-21.2RequiredA reserved identifier or macro name shall not be declaredCompliant
Rule-21.20MandatoryThe pointer returned by the Standard Library functions asctime, ctime, gmtime, localtime, localeconv, getenv, setlocale, or strerror shall not be used following a subsequent call to the same functionCompliant
Rule-21.3RequiredThe memory allocation and deallocation functions of shall not be usedCompliant
Rule-21.4RequiredThe standard header file shall not be usedCompliant
Rule-21.5RequiredThe standard header file shall not be usedCompliant
Rule-21.6RequiredThe Standard Library input/output functions shall not be usedCompliant
Rule-21.7RequiredThe atof, atoi, atol and atoll functions of shall not be usedCompliant
Rule-21.8RequiredThe library functions abort, exit and system of shall not be usedCompliant

with deviations:
-
- - - - - -
QacDescription
5128 Use of function: getenv.
-
Rule-21.9RequiredThe library functions bsearch and qsort of shall not be usedCompliant
Rule-22.1RequiredAll resources obtained dynamically by means of Standard Library functions shall be explicitly releasedCompliant
Rule-22.10RequiredThe value of errno shall only be tested when the last function to be called was an errno-setting-functionCompliant
Rule-22.2MandatoryA block of memory shall only be freed if it was allocated by means of a Standard Library functionCompliant
Rule-22.3RequiredThe same file shall not be open for read and write access at the same time on different streamsCompliant
Rule-22.4MandatoryThere shall be no attempt to write to a stream which has been opened as read-onlyCompliant
Rule-22.5MandatoryA pointer to a FILE object shall not be dereferencedCompliant
Rule-22.6MandatoryThe value of a pointer to a FILE shall not be used after the associated stream has been closedCompliant
Rule-22.7RequiredThe macro EOF shall on ly be compared with the unmodified return value from any Standard Library function capable of returning EOFCompliant
Rule-22.8RequiredThe value of errno shall be set to zero prior to a call to an errno-setting-functionCompliant
Rule-22.9RequiredThe value of errno shall be tested against zero after calling an errno-setting-functionCompliant
Rule-3.1RequiredThe character sequences /* and // shall not be used within a comment.Compliant
Rule-3.2RequiredLine-splicing shall not be used in // comments.Compliant
Rule-4.1RequiredOctal and hexadecimal escape sequences shall be terminatedCompliant
Rule-4.2AdvisoryTrigraphs should not be usedCompliant
Rule-5.1RequiredExternal identifiers shall be distinctCompliant
Rule-5.2RequiredIdentifiers declared in the same scope and name space shall be distinctCompliant
Rule-5.3RequiredAn identifier declared in an inner scope shall not hide an identifier declared in an outer scopeCompliant
Rule-5.4RequiredMacro identifiers shall be distinctCompliant
Rule-5.5RequiredIdentifiers shall be distinct from macro namesCompliant
Rule-5.6RequiredA typedef name shall be a unique identifierCompliant
Rule-5.7RequiredA tag name shall be a unique identifierCompliant
Rule-5.8RequiredIdentifiers that define objects or functions with external linkage shall be uniqueCompliant
Rule-5.9AdvisoryIdentifiers that define objects or functions with internal linkage should be uniqueCompliant
Rule-6.1RequiredBit-fields shall only be declared with an appropriate typeCompliant
Rule-6.2RequiredSingle-bit named bit fields shall not be of a signed typeCompliant
Rule-7.1RequiredOctal constants shall not be usedCompliant
Rule-7.2RequiredA "u" or "U" suffix shall be applied to all integer constants that are represented in an unsigned typeCompliant
Rule-7.3RequiredThe lowercase character "l" shall not be used in a literal suffixCompliant
Rule-7.4RequiredA string literal shall not be assigned to an object unless the object's type is "pointer to const-qualified char"Compliant
Rule-8.1RequiredTypes shall be explicitly specifiedCompliant
Rule-8.10RequiredAn inline function shall be declared with the static storage classCompliant
Rule-8.11AdvisoryWhen an array with external linkage is declared, its size should be explicitly specifiedCompliant
Rule-8.12RequiredWithin an enumerator list, the value of an implicitly-specified enumeration constant shall be uniqueCompliant
Rule-8.13AdvisoryA pointer should point to a const-qualified type whenever possibleCompliant
Rule-8.14RequiredThe restrict type qualifier shall not be usedCompliant
Rule-8.2RequiredFunction types shall be in prototype form with named parametersCompliant
Rule-8.3RequiredAll declarations of an object or function shall use the same names and type qualifiersCompliant
Rule-8.4RequiredA compatible declaration shall be visible when an object or function with external linkage is definedCompliant
Rule-8.5RequiredAn external object or function shall be declared once in one and only one fileCompliant
Rule-8.6RequiredAn identifier with external linkage shall have exactly one external definitionCompliant
Rule-8.7AdvisoryFunctions and objects should not be defined with external linkage if they are referenced in only one translation unitDisapplied
Rule-8.8RequiredThe static storage class specifier shall be used in all declarations of objects and functions that have internal linkageCompliant
Rule-8.9AdvisoryAn object should be defined at block scope if its identifier only appears in a single functionCompliant
Rule-9.1MandatoryThe value of an object with automatic storage duration shall not be read before it has been setCompliant
Rule-9.2RequiredThe initializer for an aggregate or union shall be enclosed in bracesCompliant
Rule-9.3RequiredArrays shall not be partially initializedCompliant
Rule-9.4RequiredAn element of an object shall not be initialized more than onceCompliant
Rule-9.5RequiredWhere designated initializers are used to initialize an array object the size of the array shall be specified explicitlyCompliant
-
-
- -This section targets to provide an overview of Deviation Permits.
-All the rules corresponding to the deviation permits are disabled inside PRQA and will not cause any violation or deviation in the Deviation records section below. -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GuidelineCategoryDescriptionRatioSub RulesCharacteristicsReason
Dir-1.1RequiredAny implementation-defined behaviour on which the output of the program depends shall be documented and understood3/34
- - - - - - - - - - - - - -
QacDescription
0292 [I] Source file '%s' has comments containing one of the characters '$', '@' or '`'.
0315 [I] Implicit conversion from a pointer to object type to a pointer to void.
0380 [L] Number of macro definitions exceeds 4095 - program does not conform strictly to ISO:C99.
-
Maintainability / Analysability0292: Invalid characters in comments: Doxygen comments are used.
-0315: Library string.h functions (memcpy, etc.) are used and trigger this implicit conversion.
-0380: Already CMSIS and STM32HAL trigger this.
-
Dir-4.9AdvisoryA function should be used in preference to a function-like macro where they are interchangeable1/1
- - - - - -
QacDescription
3453 A function could probably be used instead of this function-like macro.
-
Performance / Resource utilizationSuppressed due to code optimization and efficiency.
Rule-11.4AdvisoryA conversion should not be performed between a pointer to object and an integer type1/5
- - - - - -
QacDescription
0306 [I] Cast between a pointer to object and an integral type.
-
Maintainability / ModifiabilityUsing STM32 HAL already creates many violations. Also needed to do pointer arithmetic, calculating offsets inside a buffer.
Rule-11.9RequiredThe macro NULL shall be the only permitted form of integer null pointer constant1/2
- - - - - -
QacDescription
3004 This integral constant expression is being interpreted as a NULL pointer constant.
-
Keil stddef.h: "define NULL 0" causes violations. PRQA acknowledged this as a false positive.
Rule-13.3AdvisoryA full expression containing an increment (++) or decrement (--) operator should have no other potential side effects other than that caused by the increment or decrement operator1/1
- - - - - -
QacDescription
3440 Using the value resulting from a ++ or -- operation.
-
Maintainability / AnalysabilityRFAL uses the increment often for building buffers (array[i++] = 42; ...). Splitting this would decrease readability.
Rule-14.3RequiredControlling expressions shall not be invariant6/11
- - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
3440 Using the value resulting from a ++ or -- operation.
2991 The value of this 'if' controlling expression is always 'true'.
2992 The value of this 'if' controlling expression is always 'false'.
2998 The first operand of this conditional operator is always 'false'.
3493 The first operand of this conditional operator is always constant 'true'.
3494 The first operand of this conditional operator is always constant 'false'.
-
Portability / AdaptabilityRFAL is configurable through compile time switches. This causes some ifs to have invariant conditions at the used configuration. Suppress 14.3 for if statements.
Rule-15.5AdvisoryA function should have a single point of exit at the end1/1
- - - - - -
QacDescription
2889 This function has more than one 'return' path.
-
Maintainability / AnalysabilitySuppressed due to readability and simplicity of code logic.
Rule-17.7RequiredThe value returned by a function having non-void return type shall be used1/1
- - - - - -
QacDescription
3200 '%s' returns a value which is not being used.
-
Maintainability / AnalysabilityTreating the return codes of functions in all places without exception handling would makes the code hard to read and maintain. Error checking has been reduced to the places where needed.
Rule-2.1RequiredA project shall not contain unreachable code1/7
- - - - - -
QacDescription
1503 The function '%1s' is defined but is not used within this project.
-
Maintainability / ModularityRFAL provides many functions - some are not used within the checked project.
Rule-2.2RequiredThere shall be no dead code7/18
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QacDescription
2982 This assignment is redundant. The value of this object is never used before being modified.
2983 This assignment is redundant. The value of this object is never subsequently used.
2985 This operation is redundant. The value of the result is always that of the left-hand operand.
2986 This operation is redundant. The value of the result is always that of the right-hand operand.
2996 The result of this logical operation is always 'false'.
2997 The first operand of this conditional operator is always 'true'.
3112 This statement has no side-effect - it can be removed.
-
Usability / User error protectionAll the violations were checked and fixing the violation would deteriorate robustness: Removing checks which are unnecessary at the given position, removing trailing iterator increment, etc.
Rule-2.3AdvisoryA project should not contain unused type declarations1/1
- - - - - -
QacDescription
3205 The identifier '%s' is not used and could be removed.
-
Compatibility / InteroperabilityRFAL defines enums for all identifiers available in NFC Forum - some are unused.
Rule-2.5AdvisoryA project should not contain unused macro declarations1/1
- - - - - -
QacDescription
3214 The macro '%s' is not used and could be removed.
-
Compatibility / InteroperabilityRFAL defines macros for all identifiers of NFC Forum and RF chip register map - some are not used.
Rule-8.7AdvisoryFunctions and objects should not be defined with external linkage if they are referenced in only one translation unit4/4
- - - - - - - - - - - - - - - - - -
QacDescription
1504 The object '%1s' is only referenced in the translation unit where it is defined.
1505 The function '%1s' is only referenced in the translation unit where it is defined.
1531 The object '%1s' is referenced in only one translation unit - but not the one in which it is defined.
1532 The function '%1s' is only referenced in one translation unit - but not the one in which it is defined.
-
Maintainability / ModularityRFAL defines functions which could be called by the user but are not called in the current project.
-
-
- -This section targets to provide an overview of Deviation Records. -
-
-
- -

File: .../ST25R3916_nucleo/rfal/source/rfal_isoDep.c

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LinesCountSuppressed QacsComment
2266-22671
- - - - -
0310 Casting to different object pointer type.
-
MISRA 11.3 - Intentional safe cast to avoiding buffer duplication
421-4211
- - - - -
0750 A union type specifier has been defined.
-
MISRA 19.2 - Members of the union will not be used concurrently, only one frame at a time
797-7971
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
2519-25191
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Layout of enum rfalBitRate and above clamping of maxTxBR guarantee no invalid enum values to be created
2693-26931
- - - - -
0310 Casting to different object pointer type.
-
MISRA 11.3 - Intentional safe cast to avoiding large buffer duplication
1351-13511
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
1028-10281
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
2756-27561
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
2615-26151
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Layout of enum rfalBitRate and range of loop variable guarantee no invalid enum values to be created
2602-26021
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Layout of enum rfalBitRate and range of loop variable guarantee no invalid enum values to be created
2175-21761
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Layout of enum rfalIsoDepFSxI is guaranteed within 4bit range
2526-25261
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Layout of enum rfalBitRate and above clamping of maxTxBR guarantee no invalid enum values to be created
1391-13932
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Layout of enum rfalBitRate and above masks guarantee no invalid enum values to be created
-

File: .../ST25R3916_nucleo/rfal/source/rfal_nfc.c

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
LinesCountSuppressed QacsComment
1612-16121
- - - - -
0310 Casting to different object pointer type.
-
MISRA 11.3 - Intentional safe cast to avoiding large buffer duplication
81-811
- - - - -
0750 A union type specifier has been defined.
-
MISRA 19.2 - Members of the union will not be used concurrently, only one interface at a time
190-1901
- - - - -
2880 This code is unreachable.
-
MISRA 2.1 - Unreachable code due to configuration option being set/unset
1828-18281
- - - - -
0310 Casting to different object pointer type.
-
MISRA 11.3 - Intentional safe cast to avoiding large buffer duplication
-

File: .../ST25R3916_nucleo/rfal/source/rfal_nfcDep.c

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LinesCountSuppressed QacsComment
1901-19032
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Layout of enum rfalBitRate and definition of rfalNfcDepBRS2DSI guarantee no invalid enum values to be created
2595-25951
- - - - -
0310 Casting to different object pointer type.
-
MISRA 11.3 - Intentional safe cast to avoiding large buffer duplication
1589-15891
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
902-9021
- - - - -
2880 This code is unreachable.
-
MISRA 2.1 - Guard code to prevent unexpected behavior
1661-16611
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
2654-26541
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
1269-12691
- - - - -
2880 This code is unreachable.
-
MISRA 2.1 - Guard code to prevent unexpected behavior
-

File: .../ST25R3916_nucleo/rfal/source/rfal_nfca.c

-
- - - - - - - - - - - - - - - -
LinesCountSuppressed QacsComment
278-2781
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
637-6381
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Guaranteed that no invalid enum values are created: see guard_eq_RFAL_NFCA_T2T, ....
-

File: .../ST25R3916_nucleo/rfal/source/rfal_nfcb.c

-
- - - - - - - - - -
LinesCountSuppressed QacsComment
391-3921
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Layout of rfalNfcbSlots and above loop guarantee that no invalid enum values are created.
-

File: .../ST25R3916_nucleo/rfal/source/st25r3916/rfal_rfst25r3916.c

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
LinesCountSuppressed QacsComment
3344-33441
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
3108-31081
- - - - -
0759 An object of union type has been defined.
-
MISRA 19.2 - Allocating Union where members are of the same type, just different names. Thus no problem can occur.
227-2271
- - - - -
0750 A union type specifier has been defined.
-
MISRA 19.2 - Both members are of the same type, just different names. Thus no problem can occur.
2046-20461
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
3364-33641
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Guaranteed that no invalid enum values may be created. See also equalityGuard_RFAL_BR_106 ff.
2179-21791
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
1867-18671
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
1851-18511
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
2447-24471
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
1972-19721
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
1837-18371
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
2341-23411
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
2254-22541
- - - - -
2003 The preceding 'switch' clause is not empty and does not end with a 'jump' statement. Execution will fall through.
-
MISRA 16.3 - Intentional fall through
3563-35631
- - - - -
4342 An expression of 'essentially unsigned' type (%1s) is being cast to enum type '%2s'.
-
MISRA 10.5 - Guaranteed that no invalid enum values may be created. See also equalityGuard_RFAL_BR_106 ff.
1494-14941
- - - - -
5209 Use of basic type '%s'.
-
MISRA 4.9 - External function (sqrt()) requires double
-
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FileRequiredAdvisoryTotal
.../ST25R3916_nucleo/rfal/include/rfal_nfcv.h011
.../ST25R3916_nucleo/rfal/include/rfal_nfcDep.h011
.../ST25R3916_nucleo/rfal/include/rfal_isoDep.h011
.../ST25R3916_nucleo/rfal/include/rfal_nfc.h033
.../ST25R3916_nucleo/rfal/include/rfal_analogConfig.h101
.../ST25R3916_nucleo/rfal/source/rfal_nfca.c112
.../ST25R3916_nucleo/rfal/source/rfal_nfc.c314
.../ST25R3916_nucleo/rfal/source/rfal_nfcDep.c628
.../ST25R3916_nucleo/rfal/source/rfal_isoDep.c6814
.../ST25R3916_nucleo/rfal/source/st25r3916/rfal_rfst25r3916.c10515
.../ST25R3916_nucleo/rfal/source/st25r3916/rfal_analogConfigTbl.h112
.../ST25R3916_nucleo/rfal/source/rfal_nfcb.c011
Total282553
-
-
- - -There are no duplicated suppressions. - -

File: .../ST25R3916_nucleo/rfal/source/rfal_isoDep.c

-
- - - - - - - -
LineUnused QacsComment
1414
- - - - -
2880 This code is unreachable.
-
MISRA 2.1 - Unreachable code due to configuration option being set/unset above (RFAL_SUPPORT_BR_CE_A_xxx)
-
-
- -There are no continuous suppressions by file. -
-
- -Active Diagnostics refers to diagnostics that are not suppressed (note: no suppressed diagnostics have been taken into account for the calculation of information in this document). -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FilesActive DiagnosticsViolated RulesViolation CountCompliance Index
.../ST25R3916_nucleo/rfal/include/rfal_analogConfig.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_chip.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_isoDep.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_nfc.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_nfcDep.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_nfca.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_nfcb.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_nfcf.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_nfcv.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_rf.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_st25tb.h000100.00
.../ST25R3916_nucleo/rfal/include/rfal_t1t.h000100.00
.../ST25R3916_nucleo/rfal/source/rfal_analogConfig.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_crc.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_crc.h000100.00
.../ST25R3916_nucleo/rfal/source/rfal_iso15693_2.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_iso15693_2.h000100.00
.../ST25R3916_nucleo/rfal/source/rfal_isoDep.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_nfc.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_nfcDep.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_nfca.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_nfcb.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_nfcf.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_nfcv.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_st25tb.c000100.00
.../ST25R3916_nucleo/rfal/source/rfal_t1t.c000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/rfal_analogConfigTbl.h000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/rfal_features.h000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/rfal_rfst25r3916.c000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/st25R3916_irq.h000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/st25r3916.c000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/st25r3916.h000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/st25r3916_com.c000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/st25r3916_com.h000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/st25r3916_irq.c000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/st25r3916_irq.h000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/st25r3916_led.c000100.00
.../ST25R3916_nucleo/rfal/source/st25r3916/st25r3916_led.h000100.00
Total000100.00
- -

-Nota: Calculation of Compliance Index
-The Compliance Index is the percentage of groups which have no messages in them.
-For each file it is calculated as follows:
-
-( Ntotal - Nerror ) / Ntotal x 100
-
-Ntotal is the total number of enforced rules (i.e. the number of rules that have at least one message mapped to it directly).
-Nerror is the number of rules for which messages appear in that file.
-The File Compliance Index is the mean of all the individual file compliances.
- -
-
-
-
- - diff --git a/lib/ST25RFAL002/doc/_htmresc/st_logo.png b/lib/ST25RFAL002/doc/_htmresc/st_logo.png deleted file mode 100755 index 8b80057fd..000000000 Binary files a/lib/ST25RFAL002/doc/_htmresc/st_logo.png and /dev/null differ diff --git a/lib/ST25RFAL002/doc/rfal.chm b/lib/ST25RFAL002/doc/rfal.chm deleted file mode 100755 index d41770989..000000000 Binary files a/lib/ST25RFAL002/doc/rfal.chm and /dev/null differ diff --git a/lib/ST25RFAL002/include/rfal_analogConfig.h b/lib/ST25RFAL002/include/rfal_analogConfig.h deleted file mode 100644 index de9db7be9..000000000 --- a/lib/ST25RFAL002/include/rfal_analogConfig.h +++ /dev/null @@ -1,435 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_AnalogConfig.h - * - * \author bkam - * - * \brief RF Chip Analog Configuration Settings - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-HAL - * \brief RFAL Hardware Abstraction Layer - * @{ - * - * \addtogroup AnalogConfig - * \brief RFAL Analog Config Module - * @{ - * - */ - -#ifndef RFAL_ANALOG_CONFIG_H -#define RFAL_ANALOG_CONFIG_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" - -/* - ****************************************************************************** - * DEFINES - ****************************************************************************** - */ - -#define RFAL_ANALOG_CONFIG_LUT_SIZE \ - (87U) /*!< Maximum number of Configuration IDs in the Loop Up Table */ -#define RFAL_ANALOG_CONFIG_LUT_NOT_FOUND \ - (0xFFU) /*!< Index value indicating no Configuration IDs found */ - -#define RFAL_ANALOG_CONFIG_TBL_SIZE \ - (1024U) /*!< Maximum number of Register-Mask-Value in the Setting List */ - -#define RFAL_ANALOG_CONFIG_POLL_LISTEN_MODE_MASK \ - (0x8000U) /*!< Mask bit of Poll Mode in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_TECH_MASK \ - (0x7F00U) /*!< Mask bits for Technology in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_MASK \ - (0x00F0U) /*!< Mask bits for Bit rate in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_DIRECTION_MASK \ - (0x000FU) /*!< Mask bits for Direction in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_CHIP_SPECIFIC_MASK \ - (0x00FFU) /*!< Mask bits for Chip Specific Technology */ - -#define RFAL_ANALOG_CONFIG_POLL_LISTEN_MODE_SHIFT \ - (15U) /*!< Shift value of Poll Mode in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_TECH_SHIFT \ - (8U) /*!< Shift value for Technology in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_SHIFT \ - (4U) /*!< Shift value for Technology in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_DIRECTION_SHIFT \ - (0U) /*!< Shift value for Direction in Analog Configuration ID */ - -#define RFAL_ANALOG_CONFIG_POLL \ - (0x0000U) /*!< Poll Mode bit setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_LISTEN \ - (0x8000U) /*!< Listen Mode bit setting in Analog Configuration ID */ - -#define RFAL_ANALOG_CONFIG_TECH_CHIP \ - (0x0000U) /*!< Chip-Specific bit setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_TECH_NFCA \ - (0x0100U) /*!< NFC-A Technology bits setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_TECH_NFCB \ - (0x0200U) /*!< NFC-B Technology bits setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_TECH_NFCF \ - (0x0400U) /*!< NFC-F Technology bits setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_TECH_AP2P \ - (0x0800U) /*!< AP2P Technology bits setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_TECH_NFCV \ - (0x1000U) /*!< NFC-V Technology bits setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_TECH_RFU (0x2000U) /*!< RFU for Technology bits */ - -#define RFAL_ANALOG_CONFIG_BITRATE_COMMON \ - (0x0000U) /*!< Common settings for all bit rates in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_106 \ - (0x0010U) /*!< 106kbits/s settings in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_212 \ - (0x0020U) /*!< 212kbits/s settings in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_424 \ - (0x0030U) /*!< 424kbits/s settings in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_848 \ - (0x0040U) /*!< 848kbits/s settings in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_1695 \ - (0x0050U) /*!< 1695kbits/s settings in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_3390 \ - (0x0060U) /*!< 3390kbits/s settings in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_6780 \ - (0x0070U) /*!< 6780kbits/s settings in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_1OF4 \ - (0x00C0U) /*!< 1 out of 4 for NFC-V setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_BITRATE_1OF256 \ - (0x00D0U) /*!< 1 out of 256 for NFC-V setting in Analog Configuration ID */ - -#define RFAL_ANALOG_CONFIG_NO_DIRECTION \ - (0x0000U) /*!< No direction setting in Analog Conf ID (Chip Specific only) */ -#define RFAL_ANALOG_CONFIG_TX \ - (0x0001U) /*!< Transmission bit setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_RX \ - (0x0002U) /*!< Reception bit setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_ANTICOL \ - (0x0003U) /*!< Anticollision setting in Analog Configuration ID */ -#define RFAL_ANALOG_CONFIG_DPO \ - (0x0004U) /*!< DPO setting in Analog Configuration ID */ - -#define RFAL_ANALOG_CONFIG_CHIP_INIT \ - (0x0000U) /*!< Chip-Specific event: Startup;Reset;Initialize */ -#define RFAL_ANALOG_CONFIG_CHIP_DEINIT \ - (0x0001U) /*!< Chip-Specific event: Deinitialize */ -#define RFAL_ANALOG_CONFIG_CHIP_FIELD_ON \ - (0x0002U) /*!< Chip-Specific event: Field On */ -#define RFAL_ANALOG_CONFIG_CHIP_FIELD_OFF \ - (0x0003U) /*!< Chip-Specific event: Field Off */ -#define RFAL_ANALOG_CONFIG_CHIP_WAKEUP_ON \ - (0x0004U) /*!< Chip-Specific event: Wake-up On */ -#define RFAL_ANALOG_CONFIG_CHIP_WAKEUP_OFF \ - (0x0005U) /*!< Chip-Specific event: Wake-up Off */ -#define RFAL_ANALOG_CONFIG_CHIP_LISTEN_ON \ - (0x0006U) /*!< Chip-Specific event: Listen On */ -#define RFAL_ANALOG_CONFIG_CHIP_LISTEN_OFF \ - (0x0007U) /*!< Chip-Specific event: Listen Off */ -#define RFAL_ANALOG_CONFIG_CHIP_POLL_COMMON \ - (0x0008U) /*!< Chip-Specific event: Poll common */ -#define RFAL_ANALOG_CONFIG_CHIP_LISTEN_COMMON \ - (0x0009U) /*!< Chip-Specific event: Listen common */ -#define RFAL_ANALOG_CONFIG_CHIP_LOWPOWER_ON \ - (0x000AU) /*!< Chip-Specific event: Low Power On */ -#define RFAL_ANALOG_CONFIG_CHIP_LOWPOWER_OFF \ - (0x000BU) /*!< Chip-Specific event: Low Power Off */ - -#define RFAL_ANALOG_CONFIG_UPDATE_LAST \ - (0x00U) /*!< Value indicating Last configuration set during update */ -#define RFAL_ANALOG_CONFIG_UPDATE_MORE \ - (0x01U) /*!< Value indicating More configuration set coming during update */ - -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ - -#define RFAL_ANALOG_CONFIG_ID_GET_POLL_LISTEN(id) \ - (RFAL_ANALOG_CONFIG_POLL_LISTEN_MODE_MASK & (id)) /*!< Check if id indicates Listen mode */ - -#define RFAL_ANALOG_CONFIG_ID_GET_TECH(id) \ - (RFAL_ANALOG_CONFIG_TECH_MASK & (id)) /*!< Get the technology of Configuration ID */ -#define RFAL_ANALOG_CONFIG_ID_IS_CHIP(id) \ - (RFAL_ANALOG_CONFIG_TECH_MASK & (id)) /*!< Check if ID indicates Chip-specific */ -#define RFAL_ANALOG_CONFIG_ID_IS_NFCA(id) \ - (RFAL_ANALOG_CONFIG_TECH_NFCA & (id)) /*!< Check if ID indicates NFC-A */ -#define RFAL_ANALOG_CONFIG_ID_IS_NFCB(id) \ - (RFAL_ANALOG_CONFIG_TECH_NFCB & (id)) /*!< Check if ID indicates NFC-B */ -#define RFAL_ANALOG_CONFIG_ID_IS_NFCF(id) \ - (RFAL_ANALOG_CONFIG_TECH_NFCF & (id)) /*!< Check if ID indicates NFC-F */ -#define RFAL_ANALOG_CONFIG_ID_IS_AP2P(id) \ - (RFAL_ANALOG_CONFIG_TECH_AP2P & (id)) /*!< Check if ID indicates AP2P */ -#define RFAL_ANALOG_CONFIG_ID_IS_NFCV(id) \ - (RFAL_ANALOG_CONFIG_TECH_NFCV & (id)) /*!< Check if ID indicates NFC-V */ - -#define RFAL_ANALOG_CONFIG_ID_GET_BITRATE(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_MASK & (id)) /*!< Get Bitrate of Configuration ID */ -#define RFAL_ANALOG_CONFIG_ID_IS_COMMON(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_MASK & (id)) /*!< Check if ID indicates common bitrate */ -#define RFAL_ANALOG_CONFIG_ID_IS_106(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_106 & (id)) /*!< Check if ID indicates 106kbits/s */ -#define RFAL_ANALOG_CONFIG_ID_IS_212(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_212 & (id)) /*!< Check if ID indicates 212kbits/s */ -#define RFAL_ANALOG_CONFIG_ID_IS_424(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_424 & (id)) /*!< Check if ID indicates 424kbits/s */ -#define RFAL_ANALOG_CONFIG_ID_IS_848(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_848 & (id)) /*!< Check if ID indicates 848kbits/s */ -#define RFAL_ANALOG_CONFIG_ID_IS_1695(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_1695 & (id)) /*!< Check if ID indicates 1695kbits/s */ -#define RFAL_ANALOG_CONFIG_ID_IS_3390(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_3390 & (id)) /*!< Check if ID indicates 3390kbits/s */ -#define RFAL_ANALOG_CONFIG_ID_IS_6780(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_6780 & (id)) /*!< Check if ID indicates 6780kbits/s */ -#define RFAL_ANALOG_CONFIG_ID_IS_1OF4(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_1OF4 & (id)) /*!< Check if ID indicates 1 out of 4 bitrate */ -#define RFAL_ANALOG_CONFIG_ID_IS_1OF256(id) \ - (RFAL_ANALOG_CONFIG_BITRATE_1OF256 & (id)) /*!< Check if ID indicates 1 out of 256 bitrate */ - -#define RFAL_ANALOG_CONFIG_ID_GET_DIRECTION(id) \ - (RFAL_ANALOG_CONFIG_DIRECTION_MASK & (id)) /*!< Get Direction of Configuration ID */ -#define RFAL_ANALOG_CONFIG_ID_IS_TX(id) \ - (RFAL_ANALOG_CONFIG_TX & (id)) /*!< Check if id indicates TX */ -#define RFAL_ANALOG_CONFIG_ID_IS_RX(id) \ - (RFAL_ANALOG_CONFIG_RX & (id)) /*!< Check if id indicates RX */ - -#define RFAL_ANALOG_CONFIG_CONFIG_NUM(x) \ - (sizeof(x) / sizeof((x)[0])) /*!< Get Analog Config number */ - -/*! Set Analog Config ID value by: Mode, Technology, Bitrate and Direction */ -#define RFAL_ANALOG_CONFIG_ID_SET(mode, tech, br, direction) \ - (RFAL_ANALOG_CONFIG_ID_GET_POLL_LISTEN(mode) | RFAL_ANALOG_CONFIG_ID_GET_TECH(tech) | \ - RFAL_ANALOG_CONFIG_ID_GET_BITRATE(br) | RFAL_ANALOG_CONFIG_ID_GET_DIRECTION(direction)) - -/* - ****************************************************************************** - * GLOBAL DATA TYPES - ****************************************************************************** - */ - -typedef uint8_t - rfalAnalogConfigMode; /*!< Polling or Listening Mode of Configuration */ -typedef uint8_t - rfalAnalogConfigTech; /*!< Technology of Configuration */ -typedef uint8_t - rfalAnalogConfigBitrate; /*!< Bitrate of Configuration */ -typedef uint8_t - rfalAnalogConfigDirection; /*!< Transmit/Receive direction of Configuration */ - -typedef uint8_t - rfalAnalogConfigRegAddr[2]; /*!< Register Address to ST Chip */ -typedef uint8_t - rfalAnalogConfigRegMask; /*!< Register Mask Value */ -typedef uint8_t - rfalAnalogConfigRegVal; /*!< Register Value */ - -typedef uint16_t - rfalAnalogConfigId; /*!< Analog Configuration ID */ -typedef uint16_t - rfalAnalogConfigOffset; /*!< Analog Configuration offset address in the table */ -typedef uint8_t - rfalAnalogConfigNum; /*!< Number of Analog settings for the respective Configuration ID */ - -/*! Struct that contain the Register-Mask-Value set. Make sure that the whole structure size is even and unaligned! */ -typedef struct { - rfalAnalogConfigRegAddr addr; /*!< Register Address */ - rfalAnalogConfigRegMask mask; /*!< Register Mask Value */ - rfalAnalogConfigRegVal val; /*!< Register Value */ -} rfalAnalogConfigRegAddrMaskVal; - -/*! Struct that represents the Analog Configs */ -typedef struct { - uint8_t id[sizeof(rfalAnalogConfigId)]; /*!< Configuration ID */ - rfalAnalogConfigNum num; /*!< Number of Config Sets to follow */ - rfalAnalogConfigRegAddrMaskVal regSet[]; - /*!< Register-Mask-Value sets */ /* PRQA S 1060 # MISRA 18.7 - Flexible Array Members are the only meaningful way of denoting a variable length input buffer which follows a fixed header structure. */ -} rfalAnalogConfig; - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Initialize the Analog Configuration - * - * Reset the Analog Configuration LUT pointer to reference to default settings. - * - ***************************************************************************** - */ -void rfalAnalogConfigInitialize(void); - -/*! - ***************************************************************************** - * \brief Indicate if the current Analog Configuration Table is complete and ready to be used. - * - * \return true if current Analog Configuration Table is complete and ready to be used. - * \return false if current Analog Configuration Table is incomplete - * - ***************************************************************************** - */ -bool rfalAnalogConfigIsReady(void); - -/*! - ***************************************************************************** - * \brief Write the whole Analog Configuration table in raw format - * - * Writes the Analog Configuration and Look Up Table with the given raw table - * - * NOTE: Function does not check the validity of the given Table contents - * - * \param[in] configTbl: location of config Table to be loaded - * \param[in] configTblSize: size of the config Table to be loaded - * - * \return ERR_NONE : if setting is updated - * \return ERR_PARAM : if configTbl is invalid - * \return ERR_NOMEM : if the given Table is bigger exceeds the max size - * \return ERR_REQUEST : if the update Configuration Id is disabled - * - ***************************************************************************** - */ -ReturnCode rfalAnalogConfigListWriteRaw(const uint8_t* configTbl, uint16_t configTblSize); - -/*! - ***************************************************************************** - * \brief Write the Analog Configuration table with new analog settings. - * - * Writes the Analog Configuration and Look Up Table with the new list of register-mask-value - * and Configuration ID respectively. - * - * NOTE: Function does not check for the validity of the Register Address. - * - * \param[in] more: 0x00 indicates it is last Configuration ID settings; - * 0x01 indicates more Configuration ID setting(s) are coming. - * \param[in] *config: reference to the configuration list of current Configuration ID. - * - * \return ERR_PARAM : if Configuration ID or parameter is invalid - * \return ERR_NOMEM : if LUT is full - * \return ERR_REQUEST : if the update Configuration Id is disabled - * \return ERR_NONE : if setting is updated - * - ***************************************************************************** - */ -ReturnCode rfalAnalogConfigListWrite(uint8_t more, const rfalAnalogConfig* config); - -/*! - ***************************************************************************** - * \brief Read the whole Analog Configuration table in raw format - * - * Reads the whole Analog Configuration Table in raw format - * - * \param[out] tblBuf: location to the buffer to place the Config Table - * \param[in] tblBufLen: length of the buffer to place the Config Table - * \param[out] configTblSize: Config Table size - * - * \return ERR_PARAM : if configTbl or configTblSize is invalid - * \return ERR_NOMEM : if configTblSize is not enough for the whole table - * \return ERR_NONE : if read is successful - * - ***************************************************************************** - */ -ReturnCode - rfalAnalogConfigListReadRaw(uint8_t* tblBuf, uint16_t tblBufLen, uint16_t* configTblSize); - -/*! - ***************************************************************************** - * \brief Read the Analog Configuration table. - * - * Read the Analog Configuration Table - * - * \param[in] configOffset: offset to the next Configuration ID in the List Table to be read. - * \param[out] more: 0x00 indicates it is last Configuration ID settings; - * 0x01 indicates more Configuration ID setting(s) are coming. - * \param[out] config: configuration id, number of configuration sets and register-mask-value sets - * \param[in] numConfig: the remaining configuration settings space available; - * - * \return ERR_NOMEM : if number of Configuration for respective Configuration ID is greater the the remaining configuration setting space available - * \return ERR_NONE : if read is successful - * - ***************************************************************************** - */ -ReturnCode rfalAnalogConfigListRead( - rfalAnalogConfigOffset* configOffset, - uint8_t* more, - rfalAnalogConfig* config, - rfalAnalogConfigNum numConfig); - -/*! - ***************************************************************************** - * \brief Set the Analog settings of indicated Configuration ID. - * - * Update the chip with indicated analog settings of indicated Configuration ID. - * - * \param[in] configId: configuration ID - * - * \return ERR_PARAM if Configuration ID is invalid - * \return ERR_INTERNAL if error updating setting to chip - * \return ERR_NONE if new settings is applied to chip - * - ***************************************************************************** - */ -ReturnCode rfalSetAnalogConfig(rfalAnalogConfigId configId); - -/*! - ***************************************************************************** - * \brief Generates Analog Config mode ID - * - * Converts RFAL mode and bitrate into Analog Config Mode ID. - * - * Update the chip with indicated analog settings of indicated Configuration ID. - * - * \param[in] md: RFAL mode format - * \param[in] br: RFAL bit rate format - * \param[in] dir: Analog Config communication direction - * - * \return Analog Config Mode ID - * - ***************************************************************************** - */ -uint16_t rfalAnalogConfigGenModeID(rfalMode md, rfalBitRate br, uint16_t dir); - -#endif /* RFAL_ANALOG_CONFIG_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_chip.h b/lib/ST25RFAL002/include/rfal_chip.h deleted file mode 100644 index 296136b41..000000000 --- a/lib/ST25RFAL002/include/rfal_chip.h +++ /dev/null @@ -1,287 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_chip.h - * - * \author Gustavo Patricio - * - * \brief RF Chip specific Layer - * - * \warning This layer, which provides direct access to RF chip, should - * only be used for debug purposes and/or advanced features - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-HAL - * \brief RFAL Hardware Abstraction Layer - * @{ - * - * \addtogroup Chip - * \brief RFAL RF Chip Module - * @{ - * - */ - -#ifndef RFAL_CHIP_H -#define RFAL_CHIP_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" - -/***************************************************************************** - * RF Chip * - *****************************************************************************/ - -/*! - ***************************************************************************** - * \brief Writes a register on the RF Chip - * - * Checks if the given register is valid and if so, writes the value(s) - * on the RF Chip register - * - * \param[in] reg: register address to be written, or the first if len > 1 - * \param[in] values: pointer with content to be written on the register(s) - * \param[in] len: number of consecutive registers to be written - * - * - * \return ERR_PARAM : Invalid register or bad request - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : Write done with no error - ***************************************************************************** - */ -ReturnCode rfalChipWriteReg(uint16_t reg, const uint8_t* values, uint8_t len); - -/*! - ***************************************************************************** - * \brief Reads a register on the RF Chip - * - * Checks if the given register is valid and if so, reads the value(s) - * of the RF Chip register(s) - * - * \param[in] reg: register address to be read, or the first if len > 1 - * \param[out] values: pointer where the register(s) read content will be placed - * \param[in] len: number of consecutive registers to be read - * - * \return ERR_PARAM : Invalid register or bad request - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : Read done with no error - ***************************************************************************** - */ -ReturnCode rfalChipReadReg(uint16_t reg, uint8_t* values, uint8_t len); - -/*! - ***************************************************************************** - * \brief Change a register on the RF Chip - * - * Change the value of the register bits on the RF Chip Test set in the valueMask. - * - * \param[in] reg: register address to be modified - * \param[in] valueMask: mask value of the register bits to be changed - * \param[in] value: register value to be set - * - * \return ERR_PARAM : Invalid register or bad request - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_OK : Change done with no error - ***************************************************************************** - */ -ReturnCode rfalChipChangeRegBits(uint16_t reg, uint8_t valueMask, uint8_t value); - -/*! - ***************************************************************************** - * \brief Writes a Test register on the RF Chip - * - * Writes the value on the RF Chip Test register - * - * \param[in] reg: register address to be written - * \param[in] value: value to be written on the register - * - * - * \return ERR_PARAM : Invalid register or bad request - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : Write done with no error - ***************************************************************************** - */ -ReturnCode rfalChipWriteTestReg(uint16_t reg, uint8_t value); - -/*! - ***************************************************************************** - * \brief Reads a Test register on the RF Chip - * - * Reads the value of the RF Chip Test register - * - * \param[in] reg: register address to be read - * \param[out] value: pointer where the register content will be placed - * - * \return ERR_PARAM :Invalid register or bad request - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : Read done with no error - ***************************************************************************** - */ -ReturnCode rfalChipReadTestReg(uint16_t reg, uint8_t* value); - -/*! - ***************************************************************************** - * \brief Change a Test register on the RF Chip - * - * Change the value of the register bits on the RF Chip Test set in the valueMask. - * - * \param[in] reg: test register address to be modified - * \param[in] valueMask: mask value of the register bits to be changed - * \param[in] value: register value to be set - * - * \return ERR_PARAM : Invalid register or bad request - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_OK : Change done with no error - ***************************************************************************** - */ -ReturnCode rfalChipChangeTestRegBits(uint16_t reg, uint8_t valueMask, uint8_t value); - -/*! - ***************************************************************************** - * \brief Execute command on the RF Chip - * - * Checks if the given command is valid and if so, executes it on - * the RF Chip - * - * \param[in] cmd: direct command to be executed - * - * \return ERR_PARAM : Invalid command or bad request - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : Direct command executed with no error - ***************************************************************************** - */ -ReturnCode rfalChipExecCmd(uint16_t cmd); - -/*! - ***************************************************************************** - * \brief Set RFO - * - * Sets the RFO value to be used when the field is on (unmodulated/active) - * - * \param[in] rfo : the RFO value to be used - * - * \return ERR_IO : Internal error - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalChipSetRFO(uint8_t rfo); - -/*! - ***************************************************************************** - * \brief Get RFO - * - * Gets the RFO value used used when the field is on (unmodulated/active) - * - * \param[out] result : the current RFO value - * - * \return ERR_IO : Internal error - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalChipGetRFO(uint8_t* result); - -/*! - ***************************************************************************** - * \brief Measure Amplitude - * - * Measures the RF Amplitude - * - * \param[out] result : result of RF measurement - * - * \return ERR_IO : Internal error - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalChipMeasureAmplitude(uint8_t* result); - -/*! - ***************************************************************************** - * \brief Measure Phase - * - * Measures the Phase - * - * \param[out] result : result of Phase measurement - * - * \return ERR_IO : Internal error - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalChipMeasurePhase(uint8_t* result); - -/*! - ***************************************************************************** - * \brief Measure Capacitance - * - * Measures the Capacitance - * - * \param[out] result : result of Capacitance measurement - * - * \return ERR_IO : Internal error - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalChipMeasureCapacitance(uint8_t* result); - -/*! - ***************************************************************************** - * \brief Measure Power Supply - * - * Measures the Power Supply - * - * \param[in] param : measurement parameter (chip specific) - * \param[out] result : result of the measurement - * - * \return ERR_IO : Internal error - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalChipMeasurePowerSupply(uint8_t param, uint8_t* result); - -#endif /* RFAL_CHIP_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_crc.h b/lib/ST25RFAL002/include/rfal_crc.h deleted file mode 100644 index 134318cd1..000000000 --- a/lib/ST25RFAL002/include/rfal_crc.h +++ /dev/null @@ -1,74 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_crc.h - * - * \author Ulrich Herrmann - * - * \brief CRC calculation module - * - */ -/*! - * - */ - -#ifndef RFAL_CRC_H_ -#define RFAL_CRC_H_ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "platform.h" - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -/*! - ***************************************************************************** - * \brief Calculate CRC according to CCITT standard. - * - * This function takes \a length bytes from \a buf and calculates the CRC - * for this data. The result is returned. - * \note This implementation calculates the CRC with LSB first, i.e. all - * bytes are "read" from right to left. - * - * \param[in] preloadValue : Initial value of CRC calculation. - * \param[in] buf : buffer to calculate the CRC for. - * \param[in] length : size of the buffer. - * - * \return 16 bit long crc value. - * - ***************************************************************************** - */ -extern uint16_t rfalCrcCalculateCcitt(uint16_t preloadValue, const uint8_t* buf, uint16_t length); - -#endif /* RFAL_CRC_H_ */ diff --git a/lib/ST25RFAL002/include/rfal_dpo.h b/lib/ST25RFAL002/include/rfal_dpo.h deleted file mode 100644 index 7dd2cde5e..000000000 --- a/lib/ST25RFAL002/include/rfal_dpo.h +++ /dev/null @@ -1,207 +0,0 @@ - -/****************************************************************************** - * @attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * $Revision: $ - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_dpo.h - * - * \author Martin Zechleitner - * - * \brief Dynamic Power adjustment - * - * This module provides an interface to perform the power adjustment dynamically - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-HAL - * \brief RFAL Hardware Abstraction Layer - * @{ - * - * \addtogroup DPO - * \brief RFAL Dynamic Power Module - * @{ - * - */ - -#ifndef RFAL_DPO_H -#define RFAL_DPO_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_DPO_TABLE_SIZE_MAX 15U /*!< Max DPO table size */ -#define RFAL_DPO_TABLE_PARAMETER 3U /*!< DPO table Parameter length */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! DPO table entry struct */ -typedef struct { - uint8_t rfoRes; /*!< Setting for the resistance level of the RFO */ - uint8_t inc; /*!< Threshold for incrementing the output power */ - uint8_t dec; /*!< Threshold for decrementing the output power */ -} rfalDpoEntry; - -/*! Function pointer to method doing the reference measurement */ -typedef ReturnCode (*rfalDpoMeasureFunc)(uint8_t*); - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Initialize dynamic power table - * - * This function sets the internal dynamic power table to the default - * values stored in rfal_DpoTbl.h - * - ***************************************************************************** - */ -void rfalDpoInitialize(void); - -/*! - ***************************************************************************** - * \brief Set the measurement method - * - * This function sets the measurement method used for reference measurement. - * Based on the measurement the power will then be adjusted - * - * \param[in] dpoMeasureFunc: callback of measurement function - * - ***************************************************************************** - */ -void rfalDpoSetMeasureCallback(rfalDpoMeasureFunc dpoMeasureFunc); - -/*! - ***************************************************************************** - * \brief Write dynamic power table - * - * Load the dynamic power table - * - * \param[in] powerTbl: location of power Table to be loaded - * \param[in] powerTblEntries: number of entries of the power Table to be loaded - * - * \return ERR_NONE : No error - * \return ERR_PARAM : if configTbl is invalid - * \return ERR_NOMEM : if the given Table is bigger exceeds the max size - ***************************************************************************** - */ -ReturnCode rfalDpoTableWrite(rfalDpoEntry* powerTbl, uint8_t powerTblEntries); - -/*! - ***************************************************************************** - * \brief Dynamic power table Read - * - * Read the dynamic power table - * - * \param[out] tblBuf: location to the rfalDpoEntry[] to place the Table - * \param[in] tblBufEntries: number of entries available in tblBuf to place the power Table - * \param[out] tableEntries: returned number of entries actually written into tblBuf - * - * \return ERR_NONE : No error - * \return ERR_PARAM : if configTbl is invalid or parameters are invalid - ***************************************************************************** - */ -ReturnCode rfalDpoTableRead(rfalDpoEntry* tblBuf, uint8_t tblBufEntries, uint8_t* tableEntries); - -/*! - ***************************************************************************** - * \brief Dynamic power adjust - * - * It measures the current output and adjusts the power accordingly to - * the dynamic power table - * - * \return ERR_NONE : No error - * \return ERR_PARAM : if configTbl is invalid or parameters are invalid - * \return ERR_WRONG_STATE : if the current state is valid for DPO Adjustment - ***************************************************************************** - */ -ReturnCode rfalDpoAdjust(void); - -/*! - ***************************************************************************** - * \brief Get Current Dynamic power table entry - * - * Return current used DPO power table entry settings - * - * \return ERR_NONE : Current DpoEntry. This includes d_res, inc and dec - * - ***************************************************************************** - */ -rfalDpoEntry* rfalDpoGetCurrentTableEntry(void); - -/*! - ***************************************************************************** - * \brief Dynamic power set enabled state - * - * \param[in] enable: new active state - * - * Set state to enable or disable the Dynamic power adjustment - * - ***************************************************************************** - */ -void rfalDpoSetEnabled(bool enable); - -/*! - ***************************************************************************** - * \brief Get the Dynamic power enabled state - * - * Get state of the Dynamic power adjustment - * - * \return true : enabled - * \return false : disabled - ***************************************************************************** - */ -bool rfalDpoIsEnabled(void); - -#endif /* RFAL_DPO_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_iso15693_2.h b/lib/ST25RFAL002/include/rfal_iso15693_2.h deleted file mode 100644 index 994981205..000000000 --- a/lib/ST25RFAL002/include/rfal_iso15693_2.h +++ /dev/null @@ -1,206 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_iso15693_2.h - * - * \author Ulrich Herrmann - * - * \brief Implementation of ISO-15693-2 - * - */ -/*! - * - */ - -#ifndef RFAL_ISO_15693_2_H -#define RFAL_ISO_15693_2_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "platform.h" -#include "st_errno.h" - -/* -****************************************************************************** -* GLOBAL DATATYPES -****************************************************************************** -*/ -/*! Enum holding possible VCD codings */ -typedef enum { ISO15693_VCD_CODING_1_4, ISO15693_VCD_CODING_1_256 } iso15693VcdCoding_t; - -/*! Enum holding possible VICC datarates */ - -/*! Configuration parameter used by #iso15693PhyConfigure */ -typedef struct { - iso15693VcdCoding_t coding; /*!< desired VCD coding */ - uint32_t - speedMode; /*!< 0: normal mode, 1: 2^1 = x2 Fast mode, 2 : 2^2 = x4 mode, 3 : 2^3 = x8 mode - all rx pulse numbers and times are divided by 1,2,4,8 */ -} iso15693PhyConfig_t; - -/*! Parameters how the stream mode should work */ -struct iso15693StreamConfig { - uint8_t useBPSK; /*!< 0: subcarrier, 1:BPSK */ - uint8_t din; /*!< the divider for the in subcarrier frequency: fc/2^din */ - uint8_t dout; /*!< the divider for the in subcarrier frequency fc/2^dout */ - uint8_t report_period_length; /*!< the length of the reporting period 2^report_period_length*/ -}; -/* -****************************************************************************** -* GLOBAL CONSTANTS -****************************************************************************** -*/ - -#define ISO15693_REQ_FLAG_TWO_SUBCARRIERS \ - 0x01U /*!< Flag indication that communication uses two subcarriers */ -#define ISO15693_REQ_FLAG_HIGH_DATARATE \ - 0x02U /*!< Flag indication that communication uses high bitrate */ -#define ISO15693_MASK_FDT_LISTEN \ - (65) /*!< t1min = 308,2us = 4192/fc = 65.5 * 64/fc */ - -/*! t1max = 323,3us = 4384/fc = 68.5 * 64/fc - * 12 = 768/fc unmodulated time of single subcarrior SoF */ -#define ISO15693_FWT (69 + 12) - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -/*! - ***************************************************************************** - * \brief Initialize the ISO15693 phy - * - * \param[in] config : ISO15693 phy related configuration (See #iso15693PhyConfig_t) - * \param[out] needed_stream_config : return a pointer to the stream config - * needed for this iso15693 config. To be used for configure RF chip. - * - * \return ERR_IO : Error during communication. - * \return ERR_NONE : No error. - * - ***************************************************************************** - */ -extern ReturnCode iso15693PhyConfigure( - const iso15693PhyConfig_t* config, - const struct iso15693StreamConfig** needed_stream_config); - -/*! - ***************************************************************************** - * \brief Return current phy configuration - * - * This function returns current Phy configuration previously - * set by #iso15693PhyConfigure - * - * \param[out] config : ISO15693 phy configuration. - * - * \return ERR_NONE : No error. - * - ***************************************************************************** - */ -extern ReturnCode iso15693PhyGetConfiguration(iso15693PhyConfig_t* config); - -/*! - ***************************************************************************** - * \brief Code an ISO15693 compatible frame - * - * This function takes \a length bytes from \a buffer, perform proper - * encoding and sends out the frame to the ST25R391x. - * - * \param[in] buffer : data to send, modified to adapt flags. - * \param[in] length : number of bytes to send. - * \param[in] sendCrc : If set to true, CRC is appended to the frame - * \param[in] sendFlags: If set to true, flag field is sent according to - * ISO15693. - * \param[in] picopassMode : If set to true, the coding will be according to Picopass - * \param[out] subbit_total_length : Return the complete bytes which need to - * be send for the current coding - * \param[in,out] offset : Set to 0 for first transfer, function will update it to - point to next byte to be coded - * \param[out] outbuf : buffer where the function will store the coded subbit stream - * \param[out] outBufSize : the size of the output buffer - * \param[out] actOutBufSize : the amount of data stored into the buffer at this call - * - * \return ERR_IO : Error during communication. - * \return ERR_AGAIN : Data was not coded all the way. Call function again with a new/emptied buffer - * \return ERR_NO_MEM : In case outBuf is not big enough. Needs to have at - least 5 bytes for 1of4 coding and 65 bytes for 1of256 coding - * \return ERR_NONE : No error. - * - ***************************************************************************** - */ -extern ReturnCode iso15693VCDCode( - uint8_t* buffer, - uint16_t length, - bool sendCrc, - bool sendFlags, - bool picopassMode, - uint16_t* subbit_total_length, - uint16_t* offset, - uint8_t* outbuf, - uint16_t outBufSize, - uint16_t* actOutBufSize); - -/*! - ***************************************************************************** - * \brief Receive an ISO15693 compatible frame - * - * This function receives an ISO15693 frame from the ST25R391x, decodes the frame - * and writes the raw data to \a buffer. - * \note Buffer needs to be big enough to hold CRC also (+2 bytes) - * - * \param[in] inBuf : buffer with the hamming coded stream to be decoded - * \param[in] inBufLen : number of bytes to decode (=length of buffer). - * \param[out] outBuf : buffer where received data shall be written to. - * \param[in] outBufLen : Length of output buffer, should be approx twice the size of inBuf - * \param[out] outBufPos : The number of decoded bytes. Could be used in - * extended implementation to allow multiple calls - * \param[out] bitsBeforeCol : in case of ERR_COLLISION this value holds the - * number of bits in the current byte where the collision happened. - * \param[in] ignoreBits : number of bits in the beginning where collisions will be ignored - * \param[in] picopassMode : if set to true, the decoding will be according to Picopass - * - * \return ERR_COLLISION : collision occurred, data incorrect - * \return ERR_CRC : CRC error, data incorrect - * \return ERR_TIMEOUT : timeout waiting for data. - * \return ERR_NONE : No error. - * - ***************************************************************************** - */ -extern ReturnCode iso15693VICCDecode( - const uint8_t* inBuf, - uint16_t inBufLen, - uint8_t* outBuf, - uint16_t outBufLen, - uint16_t* outBufPos, - uint16_t* bitsBeforeCol, - uint16_t ignoreBits, - bool picopassMode); - -#endif /* RFAL_ISO_15693_2_H */ diff --git a/lib/ST25RFAL002/include/rfal_isoDep.h b/lib/ST25RFAL002/include/rfal_isoDep.h deleted file mode 100644 index 9b2d32c64..000000000 --- a/lib/ST25RFAL002/include/rfal_isoDep.h +++ /dev/null @@ -1,1092 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_isoDep.h - * - * \author Gustavo Patricio - * - * \brief Implementation of ISO-DEP protocol - * - * This implementation was based on the following specs: - * - ISO/IEC 14443-4 2nd Edition 2008-07-15 - * - NFC Forum Digital Protocol 1.1 2014-01-14 - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup ISO-DEP - * \brief RFAL ISO-DEP Module - * @{ - * - */ - -#ifndef RFAL_ISODEP_H_ -#define RFAL_ISODEP_H_ -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "rfal_nfcb.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_ISO_DEP -#define RFAL_FEATURE_ISO_DEP \ - false /*!< ISO-DEP module configuration missing. Disabled by default */ -#endif - -/* If module is disabled remove the need for the user to set lengths */ -#if !RFAL_FEATURE_ISO_DEP -#undef RFAL_FEATURE_ISO_DEP_IBLOCK_MAX_LEN -#undef RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN - -#define RFAL_FEATURE_ISO_DEP_IBLOCK_MAX_LEN (1U) /*!< ISO-DEP I-Block max length, set to "none" */ -#define RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN (1U) /*!< ISO-DEP APDU max length, set to "none" */ -#endif /* !RFAL_FEATURE_NFC_DEP */ - -/* - ****************************************************************************** - * DEFINES - ****************************************************************************** - */ - -#define RFAL_ISODEP_PROLOGUE_SIZE \ - (3U) /*!< Length of Prologue Field for I-Block Format */ - -#define RFAL_ISODEP_PCB_LEN \ - (1U) /*!< PCB length */ -#define RFAL_ISODEP_DID_LEN \ - (1U) /*!< DID length */ -#define RFAL_ISODEP_NAD_LEN \ - (1U) /*!< NAD length */ -#define RFAL_ISODEP_NO_DID \ - (0x00U) /*!< DID value indicating the ISO-DEP layer not to use DID */ -#define RFAL_ISODEP_NO_NAD \ - (0xFFU) /*!< NAD value indicating the ISO-DEP layer not to use NAD */ - -#define RFAL_ISODEP_FWI_MASK \ - (0xF0U) /*!< Mask bits of FWI */ -#define RFAL_ISODEP_FWI_SHIFT \ - (4U) /*!< Shift val of FWI */ -#define RFAL_ISODEP_FWI_DEFAULT \ - (4U) /*!< Default value for FWI Digital 1.0 11.6.2.17 */ -#define RFAL_ISODEP_ADV_FEATURE \ - (0x0FU) /*!< Indicate 256 Bytes FSD and Advanc Proto Feature support:NAD & DID */ - -#define RFAL_ISODEP_DID_MAX \ - (14U) /*!< Maximum DID value */ - -#define RFAL_ISODEP_BRI_MASK \ - (0x07U) /*!< Mask bits for Poll to Listen Send bitrate */ -#define RFAL_ISODEP_BSI_MASK \ - (0x70U) /*!< Mask bits for Listen to Poll Send bitrate */ -#define RFAL_ISODEP_SAME_BITRATE_MASK \ - (0x80U) /*!< Mask bit indicate only same bit rate D for both direction support */ -#define RFAL_ISODEP_BITRATE_RFU_MASK \ - (0x08U) /*!< Mask bit for RFU */ - -/*! Maximum Frame Waiting Time = ((256 * 16/fc) * 2^FWImax) = ((256*16/fc)*2^14) = (67108864)/fc = 2^26 (1/fc) */ -#define RFAL_ISODEP_MAX_FWT ((uint32_t)1U << 26) - -#define RFAL_ISODEP_FSDI_DEFAULT \ - RFAL_ISODEP_FSXI_256 /*!< Default Frame Size Integer in Poll mode */ -#define RFAL_ISODEP_FSX_KEEP (0xFFU) /*!< Flag to keep FSX from activation */ -#define RFAL_ISODEP_DEFAULT_FSCI \ - RFAL_ISODEP_FSXI_256 /*!< FSCI default value to be used in Listen Mode */ -#define RFAL_ISODEP_DEFAULT_FSC \ - RFAL_ISODEP_FSX_256 /*!< FSC default value (aligned RFAL_ISODEP_DEFAULT_FSCI) */ -#define RFAL_ISODEP_DEFAULT_SFGI (0U) /*!< SFGI Default value to be used in Listen Mode */ -#define RFAL_ISODEP_DEFAULT_FWI (8U) /*!< Default Listener FWI (Max) Digital 2.0 B7 & B3 */ - -#define RFAL_ISODEP_APDU_MAX_LEN \ - RFAL_ISODEP_FSX_1024 /*!< Max APDU length */ - -#define RFAL_ISODEP_ATTRIB_RES_MBLI_NO_INFO \ - (0x00U) /*!< MBLI indicating no information on its internal input buffer size */ -#define RFAL_ISODEP_ATTRIB_REQ_PARAM1_DEFAULT \ - (0x00U) /*!< Default values of Param 1 of ATTRIB_REQ Digital 1.0 12.6.1.3-5 */ -#define RFAL_ISODEP_ATTRIB_HLINFO_LEN \ - (32U) /*!< Maximum Size of Higher Layer Information */ -#define RFAL_ISODEP_ATS_HB_MAX_LEN \ - (15U) /*!< Maximum length of Historical Bytes Digital 1.1 13.6.2.23 */ -#define RFAL_ISODEP_ATTRIB_REQ_MIN_LEN \ - (9U) /*!< Minimum Length of ATTRIB_REQ command */ -#define RFAL_ISODEP_ATTRIB_RES_MIN_LEN \ - (1U) /*!< Minimum Length of ATTRIB_RES response */ - -#define RFAL_ISODEP_SPARAM_VALUES_MAX_LEN \ - (16U) /*!< Maximum Length of the value field on S(PARAMETERS) */ -#define RFAL_ISODEP_SPARAM_TAG_BLOCKINFO \ - (0xA0U) /*!< S(PARAMETERS) tag Block information */ -#define RFAL_ISODEP_SPARAM_TAG_BRREQ \ - (0xA1U) /*!< S(PARAMETERS) tag Bit rates Request */ -#define RFAL_ISODEP_SPARAM_TAG_BRIND \ - (0xA2U) /*!< S(PARAMETERS) tag Bit rates Indication */ -#define RFAL_ISODEP_SPARAM_TAG_BRACT \ - (0xA3U) /*!< S(PARAMETERS) tag Bit rates Activation */ -#define RFAL_ISODEP_SPARAM_TAG_BRACK \ - (0xA4U) /*!< S(PARAMETERS) tag Bit rates Acknowledgement */ - -#define RFAL_ISODEP_SPARAM_TAG_SUP_PCD2PICC \ - (0x80U) /*!< S(PARAMETERS) tag Supported bit rates from PCD to PICC */ -#define RFAL_ISODEP_SPARAM_TAG_SUP_PICC2PCD \ - (0x81U) /*!< S(PARAMETERS) tag Supported bit rates from PICC to PCD */ -#define RFAL_ISODEP_SPARAM_TAG_SUP_FRAME \ - (0x82U) /*!< S(PARAMETERS) tag Supported framing options PICC to PCD */ -#define RFAL_ISODEP_SPARAM_TAG_SEL_PCD2PICC \ - (0x83U) /*!< S(PARAMETERS) tag Selected bit rate from PCD to PICC */ -#define RFAL_ISODEP_SPARAM_TAG_SEL_PICC2PCD \ - (0x84U) /*!< S(PARAMETERS) tag Selected bit rate from PICC to PCD */ -#define RFAL_ISODEP_SPARAM_TAG_SEL_FRAME \ - (0x85U) /*!< S(PARAMETERS) tag Selected framing options PICC to PCD */ - -#define RFAL_ISODEP_SPARAM_TAG_LEN \ - (1) /*!< S(PARAMETERS) Tag Length */ -#define RFAL_ISODEP_SPARAM_TAG_BRREQ_LEN \ - (0U) /*!< S(PARAMETERS) tag Bit rates Request Length */ -#define RFAL_ISODEP_SPARAM_TAG_PICC2PCD_LEN \ - (2U) /*!< S(PARAMETERS) bit rates from PCD to PICC Length */ -#define RFAL_ISODEP_SPARAM_TAG_PCD2PICC_LEN \ - (2U) /*!< S(PARAMETERS) bit rates from PICC to PCD Length */ -#define RFAL_ISODEP_SPARAM_TAG_BRACK_LEN \ - (0U) /*!< S(PARAMETERS) tag Bit rates Acknowledgement Length */ - -#define RFAL_ISODEP_ATS_TA_DPL_212 \ - (0x01U) /*!< ATS TA DSI 212 kbps support bit mask */ -#define RFAL_ISODEP_ATS_TA_DPL_424 \ - (0x02U) /*!< ATS TA DSI 424 kbps support bit mask */ -#define RFAL_ISODEP_ATS_TA_DPL_848 \ - (0x04U) /*!< ATS TA DSI 848 kbps support bit mask */ -#define RFAL_ISODEP_ATS_TA_DLP_212 \ - (0x10U) /*!< ATS TA DSI 212 kbps support bit mask */ -#define RFAL_ISODEP_ATS_TA_DLP_424 \ - (0x20U) /*!< ATS TA DRI 424 kbps support bit mask */ -#define RFAL_ISODEP_ATS_TA_DLP_848 \ - (0x40U) /*!< ATS TA DRI 848 kbps support bit mask */ -#define RFAL_ISODEP_ATS_TA_SAME_D \ - (0x80U) /*!< ATS TA same bit both directions bit mask */ -#define RFAL_ISODEP_ATS_TB_FWI_MASK \ - (0xF0U) /*!< Mask bits for FWI (Frame Waiting Integer) in TB byte */ -#define RFAL_ISODEP_ATS_TB_SFGI_MASK \ - (0x0FU) /*!< Mask bits for SFGI (Start-Up Frame Guard Integer) in TB byte */ - -#define RFAL_ISODEP_ATS_T0_TA_PRESENCE_MASK \ - (0x10U) /*!< Mask bit for TA presence */ -#define RFAL_ISODEP_ATS_T0_TB_PRESENCE_MASK \ - (0x20U) /*!< Mask bit for TB presence */ -#define RFAL_ISODEP_ATS_T0_TC_PRESENCE_MASK \ - (0x40U) /*!< Mask bit for TC presence */ -#define RFAL_ISODEP_ATS_T0_FSCI_MASK \ - (0x0FU) /*!< Mask bit for FSCI presence */ -#define RFAL_ISODEP_ATS_T0_OFFSET \ - (0x01U) /*!< Offset of T0 in ATS Response */ - -#define RFAL_ISODEP_MAX_I_RETRYS \ - (2U) /*!< Number of retries for a I-Block Digital 2.0 16.2.5.4 */ -#define RFAL_ISODEP_MAX_R_RETRYS \ - (3U) /*!< Number of retries for a R-Block Digital 2.0 B9 - nRETRY ACK/NAK: [2,5] */ -#define RFAL_ISODEP_MAX_WTX_NACK_RETRYS \ - (3U) /*!< Number of S(WTX) replied with NACK Digital 2.0 B9 - nRETRY WTX[2,5] */ -#define RFAL_ISODEP_MAX_WTX_RETRYS \ - (20U) /*!< Number of overall S(WTX) retries Digital 2.0 16.2.5.2 */ -#define RFAL_ISODEP_MAX_WTX_RETRYS_ULTD \ - (255U) /*!< Use unlimited number of overall S(WTX) */ -#define RFAL_ISODEP_MAX_DSL_RETRYS \ - (0U) /*!< Number of retries for a S(DESELECT) Digital 2.0 B9 - nRETRY DESELECT: [0,5] */ -#define RFAL_ISODEP_RATS_RETRIES \ - (1U) /*!< RATS retries upon fail Digital 2.0 B7 - nRETRY RATS [0,1] */ - -/*! Frame Size for Proximity Card Integer definitions */ -typedef enum { - RFAL_ISODEP_FSXI_16 = - 0, /*!< Frame Size for Proximity Card Integer with 16 bytes */ - RFAL_ISODEP_FSXI_24 = - 1, /*!< Frame Size for Proximity Card Integer with 24 bytes */ - RFAL_ISODEP_FSXI_32 = - 2, /*!< Frame Size for Proximity Card Integer with 32 bytes */ - RFAL_ISODEP_FSXI_40 = - 3, /*!< Frame Size for Proximity Card Integer with 40 bytes */ - RFAL_ISODEP_FSXI_48 = - 4, /*!< Frame Size for Proximity Card Integer with 48 bytes */ - RFAL_ISODEP_FSXI_64 = - 5, /*!< Frame Size for Proximity Card Integer with 64 bytes */ - RFAL_ISODEP_FSXI_96 = - 6, /*!< Frame Size for Proximity Card Integer with 96 bytes */ - RFAL_ISODEP_FSXI_128 = - 7, /*!< Frame Size for Proximity Card Integer with 128 bytes */ - RFAL_ISODEP_FSXI_256 = - 8, /*!< Frame Size for Proximity Card Integer with 256 bytes */ - RFAL_ISODEP_FSXI_512 = - 9, /*!< Frame Size for Proximity Card Integer with 512 bytes ISO14443-3 Amd2 2012 */ - RFAL_ISODEP_FSXI_1024 = - 10, /*!< Frame Size for Proximity Card Integer with 1024 bytes ISO14443-3 Amd2 2012 */ - RFAL_ISODEP_FSXI_2048 = - 11, /*!< Frame Size for Proximity Card Integer with 2048 bytes ISO14443-3 Amd2 2012 */ - RFAL_ISODEP_FSXI_4096 = - 12 /*!< Frame Size for Proximity Card Integer with 4096 bytes ISO14443-3 Amd2 2012 */ -} rfalIsoDepFSxI; - -/*! Frame Size for Proximity Card definitions */ -typedef enum { - RFAL_ISODEP_FSX_16 = - 16, /*!< Frame Size for Proximity Card with 16 bytes */ - RFAL_ISODEP_FSX_24 = - 24, /*!< Frame Size for Proximity Card with 24 bytes */ - RFAL_ISODEP_FSX_32 = - 32, /*!< Frame Size for Proximity Card with 32 bytes */ - RFAL_ISODEP_FSX_40 = - 40, /*!< Frame Size for Proximity Card with 40 bytes */ - RFAL_ISODEP_FSX_48 = - 48, /*!< Frame Size for Proximity Card with 48 bytes */ - RFAL_ISODEP_FSX_64 = - 64, /*!< Frame Size for Proximity Card with 64 bytes */ - RFAL_ISODEP_FSX_96 = - 96, /*!< Frame Size for Proximity Card with 96 bytes */ - RFAL_ISODEP_FSX_128 = - 128, /*!< Frame Size for Proximity Card with 128 bytes */ - RFAL_ISODEP_FSX_256 = - 256, /*!< Frame Size for Proximity Card with 256 bytes */ - RFAL_ISODEP_FSX_512 = - 512, /*!< Frame Size for Proximity Card with 512 bytes ISO14443-3 Amd2 2012 */ - RFAL_ISODEP_FSX_1024 = - 1024, /*!< Frame Size for Proximity Card with 1024 bytes ISO14443-3 Amd2 2012 */ - RFAL_ISODEP_FSX_2048 = - 2048, /*!< Frame Size for Proximity Card with 2048 bytes ISO14443-3 Amd2 2012 */ - RFAL_ISODEP_FSX_4096 = - 4096, /*!< Frame Size for Proximity Card with 4096 bytes ISO14443-3 Amd2 2012 */ -} rfalIsoDepFSx; - -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ - -/* - ****************************************************************************** - * GLOBAL DATA TYPES - ****************************************************************************** - */ - -/*! RATS format Digital 1.1 13.6.1 */ -typedef struct { - uint8_t CMD; /*!< RATS command byte: 0xE0 */ - uint8_t PARAM; /*!< Param indicating FSDI and DID */ -} rfalIsoDepRats; - -/*! ATS response format Digital 1.1 13.6.2 */ -typedef struct { - uint8_t TL; /*!< Length Byte, including TL byte itself */ - uint8_t T0; /*!< Format Byte T0 indicating if TA, TB, TC */ - uint8_t TA; /*!< Interface Byte TA(1) */ - uint8_t TB; /*!< Interface Byte TB(1) */ - uint8_t TC; /*!< Interface Byte TC(1) */ - uint8_t HB[RFAL_ISODEP_ATS_HB_MAX_LEN]; /*!< Historical Bytes */ -} rfalIsoDepAts; - -/*! PPS Request format (Protocol and Parameter Selection) ISO14443-4 5.3 */ -typedef struct { - uint8_t PPSS; /*!< Start Byte: [ 1101b | CID[4b] ] */ - uint8_t PPS0; /*!< Parameter 0:[ 000b | PPS1[1n] | 0001b ] */ - uint8_t PPS1; /*!< Parameter 1:[ 0000b | DSI[2b] | DRI[2b] ]*/ -} rfalIsoDepPpsReq; - -/*! PPS Response format (Protocol and Parameter Selection) ISO14443-4 5.4 */ -typedef struct { - uint8_t PPSS; /*!< Start Byte: [ 1101b | CID[4b] ] */ -} rfalIsoDepPpsRes; - -/*! ATTRIB Command Format Digital 1.1 15.6.1 */ -typedef struct { - uint8_t cmd; /*!< ATTRIB_REQ command byte */ - uint8_t nfcid0[RFAL_NFCB_NFCID0_LEN]; /*!< NFCID0 of the card to be selected */ - struct { - uint8_t PARAM1; /*!< PARAM1 of ATTRIB command */ - uint8_t PARAM2; /*!< PARAM2 of ATTRIB command */ - uint8_t PARAM3; /*!< PARAM3 of ATTRIB command */ - uint8_t PARAM4; /*!< PARAM4 of ATTRIB command */ - } Param; /*!< Parameter of ATTRIB command */ - uint8_t HLInfo[RFAL_ISODEP_ATTRIB_HLINFO_LEN]; /*!< Higher Layer Information */ -} rfalIsoDepAttribCmd; - -/*! ATTRIB Response Format Digital 1.1 15.6.2 */ -typedef struct { - uint8_t mbliDid; /*!< Contains MBLI and DID */ - uint8_t HLInfo[RFAL_ISODEP_ATTRIB_HLINFO_LEN]; /*!< Higher Layer Information */ -} rfalIsoDepAttribRes; - -/*! S(Parameters) Command Format ISO14443-4 (2016) Table 4 */ -typedef struct { - uint8_t tag; /*!< S(PARAMETERS) Tag field */ - uint8_t length; /*!< S(PARAMETERS) Length field */ - uint8_t value[RFAL_ISODEP_SPARAM_VALUES_MAX_LEN]; /*!< S(PARAMETERS) Value field */ -} rfalIsoDepSParameter; - -/*! Activation info as Poller and Listener for NFC-A and NFC-B */ -typedef union { /* PRQA S 0750 # MISRA 19.2 - Both members of the union will not be used concurrently, device is only of type A or B at a time. Thus no problem can occur. */ - - /*! NFC-A information */ - union { /* PRQA S 0750 # MISRA 19.2 - Both members of the union will not be used concurrently, device is only PCD or PICC at a time. Thus no problem can occur. */ - struct { - rfalIsoDepAts ATS; /*!< ATS response (Poller mode) */ - uint8_t ATSLen; /*!< ATS response length (Poller mode) */ - } Listener; - struct { - rfalIsoDepRats RATS; /*!< RATS request (Listener mode) */ - } Poller; - } A; - - /*! NFC-B information */ - union { /* PRQA S 0750 # MISRA 19.2 - Both members of the union will not be used concurrently, device is only PCD or PICC at a time. Thus no problem can occur. */ - struct { - rfalIsoDepAttribRes ATTRIB_RES; /*!< ATTRIB_RES (Poller mode) */ - uint8_t ATTRIB_RESLen; /*!< ATTRIB_RES length (Poller mode) */ - } Listener; - struct { - rfalIsoDepAttribCmd ATTRIB; /*!< ATTRIB request (Listener mode) */ - uint8_t ATTRIBLen; /*!< ATTRIB request length (Listener mode) */ - } Poller; - } B; -} rfalIsoDepActivation; - -/*! ISO-DEP device Info */ -typedef struct { - uint8_t FWI; /*!< Frame Waiting Integer */ - uint32_t FWT; /*!< Frame Waiting Time (1/fc) */ - uint32_t dFWT; /*!< Delta Frame Waiting Time (1/fc) */ - uint32_t SFGI; /*!< Start-up Frame Guard time Integer */ - uint32_t SFGT; /*!< Start-up Frame Guard Time (ms) */ - uint8_t FSxI; /*!< Frame Size Device/Card Integer (FSDI or FSCI) */ - uint16_t FSx; /*!< Frame Size Device/Card (FSD or FSC) */ - uint32_t MBL; /*!< Maximum Buffer Length (optional for NFC-B) */ - rfalBitRate DSI; /*!< Bit Rate coding from Listener (PICC) to Poller (PCD) */ - rfalBitRate DRI; /*!< Bit Rate coding from Poller (PCD) to Listener (PICC) */ - uint8_t DID; /*!< Device ID */ - uint8_t NAD; /*!< Node ADdress */ - bool supDID; /*!< DID supported flag */ - bool supNAD; /*!< NAD supported flag */ - bool supAdFt; /*!< Advanced Features supported flag */ -} rfalIsoDepInfo; - -/*! ISO-DEP Device structure */ -typedef struct { - rfalIsoDepActivation activation; /*!< Activation Info */ - rfalIsoDepInfo info; /*!< ISO-DEP (ISO14443-4) device Info */ -} rfalIsoDepDevice; - -/*! ATTRIB Response parameters */ -typedef struct { - uint8_t mbli; /*!< MBLI */ - uint8_t HLInfo[RFAL_ISODEP_ATTRIB_HLINFO_LEN]; /*!< Hi Layer Information */ - uint8_t HLInfoLen; /*!< Hi Layer Information Length */ -} rfalIsoDepAttribResParam; - -/*! ATS Response parameter */ -typedef struct { - uint8_t fsci; /*!< Frame Size of Proximity Card Integer */ - uint8_t fwi; /*!< Frame Waiting Time Integer */ - uint8_t sfgi; /*!< Start-Up Frame Guard Time Integer */ - bool didSupport; /*!< DID Supported */ - uint8_t ta; /*!< Max supported bitrate both direction */ - uint8_t* hb; /*!< Historical Bytes data */ - uint8_t hbLen; /*!< Historical Bytes Length */ -} rfalIsoDepAtsParam; - -/*! Structure of I-Block Buffer format from caller */ -typedef struct { - uint8_t prologue[RFAL_ISODEP_PROLOGUE_SIZE]; /*!< Prologue/SoD buffer */ - uint8_t - inf[RFAL_FEATURE_ISO_DEP_IBLOCK_MAX_LEN]; /*!< INF/Payload buffer */ -} rfalIsoDepBufFormat; - -/*! Structure of APDU Buffer format from caller */ -typedef struct { - uint8_t prologue[RFAL_ISODEP_PROLOGUE_SIZE]; /*!< Prologue/SoD buffer */ - uint8_t apdu[RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN]; /*!< APDU/Payload buffer */ -} rfalIsoDepApduBufFormat; - -/*! Listen Activation Parameters Structure */ -typedef struct { - rfalIsoDepBufFormat* rxBuf; /*!< Receive Buffer struct reference */ - uint16_t* rxLen; /*!< Received INF data length in Bytes */ - bool* isRxChaining; /*!< Received data is not complete */ - rfalIsoDepDevice* isoDepDev; /*!< ISO-DEP device info */ -} rfalIsoDepListenActvParam; - -/*! Structure of parameters used on ISO DEP Transceive */ -typedef struct { - rfalIsoDepBufFormat* txBuf; /*!< Transmit Buffer struct reference */ - uint16_t txBufLen; /*!< Transmit Buffer INF field length in Bytes*/ - bool isTxChaining; /*!< Transmit data is not complete */ - rfalIsoDepBufFormat* rxBuf; /*!< Receive Buffer struct reference in Bytes */ - uint16_t* rxLen; /*!< Received INF data length in Bytes */ - bool* isRxChaining; /*!< Received data is not complete */ - uint32_t FWT; /*!< FWT to be used (ignored in Listen Mode) */ - uint32_t dFWT; /*!< Delta FWT to be used */ - uint16_t ourFSx; /*!< Our device Frame Size (FSD or FSC) */ - uint16_t FSx; /*!< Other device Frame Size (FSD or FSC) */ - uint8_t DID; /*!< Device ID (RFAL_ISODEP_NO_DID if no DID) */ -} rfalIsoDepTxRxParam; - -/*! Structure of parameters used on ISO DEP APDU Transceive */ -typedef struct { - rfalIsoDepApduBufFormat* txBuf; /*!< Transmit Buffer struct reference */ - uint16_t txBufLen; /*!< Transmit Buffer INF field length in Bytes*/ - rfalIsoDepApduBufFormat* rxBuf; /*!< Receive Buffer struct reference in Bytes */ - uint16_t* rxLen; /*!< Received INF data length in Bytes */ - rfalIsoDepBufFormat* tmpBuf; /*!< Temp buffer for Rx I-Blocks (internal) */ - uint32_t FWT; /*!< FWT to be used (ignored in Listen Mode) */ - uint32_t dFWT; /*!< Delta FWT to be used */ - uint16_t FSx; /*!< Other device Frame Size (FSD or FSC) */ - uint16_t ourFSx; /*!< Our device Frame Size (FSD or FSC) */ - uint8_t DID; /*!< Device ID (RFAL_ISODEP_NO_DID if no DID) */ -} rfalIsoDepApduTxRxParam; - -/* - ****************************************************************************** - * GLOBAL FUNCTION PROTOTYPES - ****************************************************************************** - */ - -/*! - ****************************************************************************** - * \brief Initialize the ISO-DEP protocol - * - * Initialize the ISO-DEP protocol layer with default config - ****************************************************************************** - */ -void rfalIsoDepInitialize(void); - -/*! - ****************************************************************************** - * \brief Initialize the ISO-DEP protocol - * - * Initialize the ISO-DEP protocol layer with additional parameters allowing - * to customise the protocol layer for specific behaviours - * - - * \param[in] compMode : Compliance mode to be performed - * \param[in] maxRetriesR : Number of retries for a R-Block - * Digital 2.0 B9 - nRETRY ACK/NAK: [2,5] - * \param[in] maxRetriesSnWTX : Number of retries for a S(WTX) (only in case - * of NAKs) Digital 2.0 B9 - nRETRY WTX[2,5] - * \param[in] maxRetriesSWTX : Number of overall S(WTX) retries. - * Use RFAL_ISODEP_MAX_WTX_RETRYS_ULTD for disabling - * this limit check Digital 2.0 16.2.5.2 - * \param[in] maxRetriesSDSL : Number of retries for a S(DESELECT) - * Digital 2.0 B9 - nRETRY DESELECT: [0,5] - * \param[in] maxRetriesI : Number of retries for a I-Block - * Digital 2.0 16.2.5.4 - * \param[in] maxRetriesRATS : Number of retries for RATS - * Digital 2.0 B7 - nRETRY RATS [0,1] - * - ****************************************************************************** - */ -void rfalIsoDepInitializeWithParams( - rfalComplianceMode compMode, - uint8_t maxRetriesR, - uint8_t maxRetriesSnWTX, - uint8_t maxRetriesSWTX, - uint8_t maxRetriesSDSL, - uint8_t maxRetriesI, - uint8_t maxRetriesRATS); - -/*! - ***************************************************************************** - * \brief FSxI to FSx - * - * Convert Frame Size for proximity coupling Device Integer (FSxI) to - * Frame Size for proximity coupling Device (FSx) - * - * FSD - maximum frame size for NFC Forum Device in Poll Mode - * FSC - maximum frame size for NFC Forum Device in Listen Mode - * - * FSxI = FSDI or FSCI - * FSx = FSD or FSC - * - * The FSD/FSC value includes the header and CRC - * - * \param[in] FSxI : Frame Size for proximity coupling Device Integer - * - * \return fsx : Frame Size for proximity coupling Device (FSD or FSC) - * - ***************************************************************************** - */ -uint16_t rfalIsoDepFSxI2FSx(uint8_t FSxI); - -/*! - ***************************************************************************** - * \brief FWI to FWT - * - * Convert Frame Waiting time Integer (FWI) to Frame Waiting Time (FWT) in - * 1/fc units - * - * \param[in] fwi : Frame Waiting time Integer - * - * \return fwt : Frame Waiting Time in 1/fc units - * - ***************************************************************************** - */ -uint32_t rfalIsoDepFWI2FWT(uint8_t fwi); - -/*! - ***************************************************************************** - * \brief Check if the buffer data contains a valid RATS command - * - * Check if it is a well formed RATS command with 2 bytes - * This function does not check the validity of FSDI and DID - * - * \param[in] buf : reference to buffer containing the data to be checked - * \param[in] bufLen : length of data in the buffer in bytes - * - * \return true if the data indicates a RATS command; false otherwise - ***************************************************************************** - */ -bool rfalIsoDepIsRats(const uint8_t* buf, uint8_t bufLen); - -/*! - ***************************************************************************** - * \brief Check if the buffer data contains a valid ATTRIB command - * - * Check if it is a well formed ATTRIB command, but does not check the - * validity of the information inside - * - * \param[in] buf : reference to buffer containing the data to be checked - * \param[in] bufLen : length of data in the buffer in bytes - * - * \return true if the data indicates a ATTRIB command; false otherwise - ***************************************************************************** - */ -bool rfalIsoDepIsAttrib(const uint8_t* buf, uint8_t bufLen); - -/*! - ***************************************************************************** - * \brief Start Listen Activation Handling - * - * Start Listen Activation Handling and setup to receive first I-block which may - * contain complete or partial APDU after activation is completed - * - * Pass in RATS for T4AT, or ATTRIB for T4BT, to handle ATS or ATTRIB Response respectively - * The Activation Handling handles ATS and ATTRIB Response; and additionally PPS Response - * if a PPS is received for T4AT. - * The method uses the current RFAL state machine to determine if it is expecting RATS or ATTRIB - * - * Activation is completed if PPS Response is sent or if first PDU is received in T4T-A - * Activation is completed if ATTRIB Response is sent in T4T-B - * - * \ref rfalIsoDepListenGetActivationStatus provide status if activation is completed. - * \ref rfalIsoDepStartTransceive shall be called right after activation is completed - * - * \param[in] atsParam : reference to ATS parameters - * \param[in] attribResParam : reference to ATTRIB_RES parameters - * \param[in] buf : reference to buffer containing RATS or ATTRIB - * \param[in] bufLen : length in bytes of the given buffer - * \param[in] actParam : reference to incoming reception information will be placed - * - * - * \warning Once the Activation has been completed the method - * rfalIsoDepGetTransceiveStatus() must be called. - * If activation has completed due to reception of a data block (not PPS) the - * buffer owned by the caller and passed on actParam must still contain this data. - * The first data will be processed (I-Block or S-DSL) by rfalIsoDepGetTransceiveStatus() - * inform the caller and then for the next transaction use rfalIsoDepStartTransceive() - * - * \return ERR_NONE : RATS/ATTRIB is valid and activation has started - * \return ERR_PARAM : Invalid parameters - * \return ERR_PROTO : Invalid request - * \return ERR_NOTSUPP : Feature not supported - ***************************************************************************** - */ -ReturnCode rfalIsoDepListenStartActivation( - rfalIsoDepAtsParam* atsParam, - const rfalIsoDepAttribResParam* attribResParam, - const uint8_t* buf, - uint16_t bufLen, - rfalIsoDepListenActvParam actParam); - -/*! - ***************************************************************************** - * \brief Get the current Activation Status - * - * \return ERR_NONE if Activation is already completed - * \return ERR_BUSY if Activation is ongoing - * \return ERR_LINK_LOSS if Remote Field is turned off - ***************************************************************************** - */ -ReturnCode rfalIsoDepListenGetActivationStatus(void); - -/*! - ***************************************************************************** - * \brief Get the ISO-DEP Communication Information - * - * Gets the maximum INF length in bytes based on current Frame Size - * for proximity coupling Device (FSD or FSC) excluding the header and CRC - * - * \return maximum INF length in bytes - ***************************************************************************** - */ -uint16_t rfalIsoDepGetMaxInfLen(void); - -/*! - ***************************************************************************** - * \brief ISO-DEP Start Transceive - * - * This method triggers a ISO-DEP Transceive containing a complete or - * partial APDU - * It transmits the given message and handles all protocol retransmitions, - * error handling and control messages - * - * The txBuf contains a complete or partial APDU (INF) to be transmitted - * The Prologue field will be manipulated by the Transceive - * - * If the buffer contains a partial APDU and is not the last block, - * then isTxChaining must be set to true - * - * \param[in] param: reference parameters to be used for the Transceive - * - * \return ERR_PARAM : Bad request - * \return ERR_WRONG_STATE : The module is not in a proper state - * \return ERR_NONE : The Transceive request has been started - ***************************************************************************** - */ -ReturnCode rfalIsoDepStartTransceive(rfalIsoDepTxRxParam param); - -/*! - ***************************************************************************** - * \brief Get the Transceive status - * - * Returns the status of the ISO-DEP Transceive - * - * \warning When the other device is performing chaining once a chained - * block is received the error ERR_AGAIN is sent. At this point - * caller must handle the received data immediately. - * When ERR_AGAIN is returned an ACK has already been sent to - * the other device and the next block might be incoming. - * If rfalWorker() is called frequently it will place the next - * block on the given buffer - * - * - * \return ERR_NONE : Transceive has been completed successfully - * \return ERR_BUSY : Transceive is ongoing - * \return ERR_PROTO : Protocol error occurred - * \return ERR_TIMEOUT : Timeout error occurred - * \return ERR_SLEEP_REQ : Deselect has been received and responded - * \return ERR_NOMEM : The received INF does not fit into the - * receive buffer - * \return ERR_LINK_LOSS : Communication is lost because Reader/Writer - * has turned off its field - * \return ERR_AGAIN : received one chaining block, continue to call - * this method to retrieve the remaining blocks - ***************************************************************************** - */ -ReturnCode rfalIsoDepGetTransceiveStatus(void); - -/*! - ***************************************************************************** - * \brief ISO-DEP Start APDU Transceive - * - * This method triggers a ISO-DEP Transceive containing a complete APDU - * It transmits the given message and handles all protocol retransmitions, - * error handling and control messages - * - * The txBuf contains a complete APDU to be transmitted - * The Prologue field will be manipulated by the Transceive - * - * \warning the txBuf will be modified during the transmission - * \warning the maximum RF frame which can be received is limited by param.tmpBuf - * - * \param[in] param: reference parameters to be used for the Transceive - * - * \return ERR_PARAM : Bad request - * \return ERR_WRONG_STATE : The module is not in a proper state - * \return ERR_NONE : The Transceive request has been started - ***************************************************************************** - */ -ReturnCode rfalIsoDepStartApduTransceive(rfalIsoDepApduTxRxParam param); - -/*! - ***************************************************************************** - * \brief Get the APDU Transceive status - * - * \return ERR_NONE : if Transceive has been completed successfully - * \return ERR_BUSY : if Transceive is ongoing - * \return ERR_PROTO : if a protocol error occurred - * \return ERR_TIMEOUT : if a timeout error occurred - * \return ERR_SLEEP_REQ : if Deselect is received and responded - * \return ERR_NOMEM : if the received INF does not fit into the - * receive buffer - * \return ERR_LINK_LOSS : if communication is lost because Reader/Writer - * has turned off its field - ***************************************************************************** - */ -ReturnCode rfalIsoDepGetApduTransceiveStatus(void); - -/*! - ***************************************************************************** - * \brief ISO-DEP Send RATS - * - * This sends a RATS to make a NFC-A Listen Device to enter - * ISO-DEP layer (ISO14443-4) and checks if the received ATS is valid - * - * \param[in] FSDI : Frame Size Device Integer to be used - * \param[in] DID : Device ID to be used or RFAL_ISODEP_NO_DID for not use DID - * \param[out] ats : pointer to place the ATS Response - * \param[out] atsLen : pointer to place the ATS length - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, ATS received - ***************************************************************************** - */ -ReturnCode rfalIsoDepRATS(rfalIsoDepFSxI FSDI, uint8_t DID, rfalIsoDepAts* ats, uint8_t* atsLen); - -/*! - ***************************************************************************** - * \brief ISO-DEP Send PPS - * - * This sends a PPS to make a NFC-A Listen Device change the communications - * bit rate from 106kbps to one of the supported bit rates - * Additionally checks if the received PPS response is valid - * - * \param[in] DID : Device ID - * \param[in] DSI : DSI code the divisor from Listener (PICC) to Poller (PCD) - * \param[in] DRI : DRI code the divisor from Poller (PCD) to Listener (PICC) - * \param[out] ppsRes : pointer to place the PPS Response - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, PPS Response received - ***************************************************************************** - */ -ReturnCode rfalIsoDepPPS(uint8_t DID, rfalBitRate DSI, rfalBitRate DRI, rfalIsoDepPpsRes* ppsRes); - -/*! - ***************************************************************************** - * \brief ISO-DEP Send ATTRIB - * - * This sends a ATTRIB to make a NFC-B Listen Device to enter - * ISO-DEP layer (ISO14443-4) and checks if the received ATTRIB Response is valid - * - * \param[in] nfcid0 : NFCID0 to be used for the ATTRIB - * \param[in] PARAM1 : ATTRIB PARAM1 byte (communication parameters) - * \param[in] DSI : DSI code the divisor from Listener (PICC) to Poller (PCD) - * \param[in] DRI : DRI code the divisor from Poller (PCD) to Listener (PICC) - * \param[in] FSDI : PCD's Frame Size to be announced on the ATTRIB - * \param[in] PARAM3 : ATTRIB PARAM1 byte (protocol type) - * \param[in] DID : Device ID to be used or RFAL_ISODEP_NO_DID for not use DID - * \param[in] HLInfo : pointer to Higher layer INF (NULL if none) - * \param[in] HLInfoLen : Length HLInfo - * \param[in] fwt : Frame Waiting Time to be used (from SENSB_RES) - * \param[out] attribRes : pointer to place the ATTRIB Response - * \param[out] attribResLen : pointer to place the ATTRIB Response length - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, ATTRIB Response received - ***************************************************************************** - */ -ReturnCode rfalIsoDepATTRIB( - const uint8_t* nfcid0, - uint8_t PARAM1, - rfalBitRate DSI, - rfalBitRate DRI, - rfalIsoDepFSxI FSDI, - uint8_t PARAM3, - uint8_t DID, - const uint8_t* HLInfo, - uint8_t HLInfoLen, - uint32_t fwt, - rfalIsoDepAttribRes* attribRes, - uint8_t* attribResLen); - -/*! - ***************************************************************************** - * \brief Deselects PICC - * - * This function sends a deselect command to PICC and waits for it`s - * response in a blocking way - * - * \return ERR_NONE : Deselect successfully sent and acknowledged by PICC - * \return ERR_TIMEOUT: No response rcvd from PICC - * - ***************************************************************************** - */ -ReturnCode rfalIsoDepDeselect(void); - -/*! - ***************************************************************************** - * \brief ISO-DEP Poller Handle NFC-A Activation - * - * This performs a NFC-A Activation into ISO-DEP layer (ISO14443-4) with the given - * parameters. It sends RATS and if the higher bit rates are supported by - * both devices it additionally sends PPS - * Once Activated all details of the device are provided on isoDepDev - * - * \param[in] FSDI : Frame Size Device Integer to be used - * \param[in] DID : Device ID to be used or RFAL_ISODEP_NO_DID for not use DID - * \param[in] maxBR : Max bit rate supported by the Poller - * \param[out] isoDepDev : ISO-DEP information of the activated Listen device - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, activation successful - ***************************************************************************** - */ -ReturnCode rfalIsoDepPollAHandleActivation( - rfalIsoDepFSxI FSDI, - uint8_t DID, - rfalBitRate maxBR, - rfalIsoDepDevice* isoDepDev); - -/*! - ***************************************************************************** - * \brief ISO-DEP Poller Handle NFC-B Activation - * - * This performs a NFC-B Activation into ISO-DEP layer (ISO14443-4) with the given - * parameters. It sends ATTRIB and calculates supported higher bit rates of both - * devices and performs activation. - * Once Activated all details of the device are provided on isoDepDev - * - * \param[in] FSDI : Frame Size Device Integer to be used - * \param[in] DID : Device ID to be used or RFAL_ISODEP_NO_DID for not use DID - * \param[in] maxBR : Max bit rate supported by the Poller - * \param[in] PARAM1 : ATTRIB PARAM1 byte (communication parameters) - * \param[in] nfcbDev : pointer to the NFC-B Device containing the SENSB_RES - * \param[in] HLInfo : pointer to Higher layer INF (NULL if none) - * \param[in] HLInfoLen : Length HLInfo - * \param[out] isoDepDev : ISO-DEP information of the activated Listen device - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, activation successful - ***************************************************************************** - */ -ReturnCode rfalIsoDepPollBHandleActivation( - rfalIsoDepFSxI FSDI, - uint8_t DID, - rfalBitRate maxBR, - uint8_t PARAM1, - const rfalNfcbListenDevice* nfcbDev, - const uint8_t* HLInfo, - uint8_t HLInfoLen, - rfalIsoDepDevice* isoDepDev); - -/*! - ***************************************************************************** - * \brief ISO-DEP Poller Handle S(Parameters) - * - * This checks if PICC supports S(PARAMETERS), retrieves PICC's - * capabilities and sets the Bit Rate at the highest supported by both - * devices - * - * \param[out] isoDepDev : ISO-DEP information of the activated Listen device - * \param[in] maxTxBR : Maximum Tx bit rate supported by PCD - * \param[in] maxRxBR : Maximum Rx bit rate supported by PCD - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, S(PARAMETERS) selection successful - ***************************************************************************** - */ -ReturnCode rfalIsoDepPollHandleSParameters( - rfalIsoDepDevice* isoDepDev, - rfalBitRate maxTxBR, - rfalBitRate maxRxBR); - -/*! - ***************************************************************************** - * \brief ISO-DEP Poller Start NFC-A Activation - * - * This starts a NFC-A Activation into ISO-DEP layer (ISO14443-4) with the given - * parameters. It sends RATS and if the higher bit rates are supported by - * both devices it additionally sends PPS - * Once Activated all details of the device are provided on isoDepDev - * - * - * \see rfalIsoDepPollAGetActivationStatus - * - * \param[in] FSDI : Frame Size Device Integer to be used - * \param[in] DID : Device ID to be used or RFAL_ISODEP_NO_DID for not use DID - * \param[in] maxBR : Max bit rate supported by the Poller - * \param[out] isoDepDev : ISO-DEP information of the activated Listen device - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, start of asynchronous operation successful - ***************************************************************************** - */ -ReturnCode rfalIsoDepPollAStartActivation( - rfalIsoDepFSxI FSDI, - uint8_t DID, - rfalBitRate maxBR, - rfalIsoDepDevice* isoDepDev); - -/*! - ***************************************************************************** - * \brief ISO-DEP Poller Get NFC-A Activation Status - * - * Returns the activation status started by rfalIsoDepPollAStartActivation - * - * \see rfalIsoDepPollAStartActivation - * - * \return ERR_BUSY : Operation is ongoing - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, activation successful - ***************************************************************************** - */ -ReturnCode rfalIsoDepPollAGetActivationStatus(void); - -/*! - ***************************************************************************** - * \brief ISO-DEP Poller Start NFC-B Activation - * - * This starts a NFC-B Activation into ISO-DEP layer (ISO14443-4) with the given - * parameters. It will send ATTRIB and calculate supported higher bit rates of both - * devices and perform activation. - * Once Activated all details of the device are provided on isoDepDev - * - * \see rfalIsoDepPollBGetActivationStatus - * - * \param[in] FSDI : Frame Size Device Integer to be used - * \param[in] DID : Device ID to be used or RFAL_ISODEP_NO_DID for not use DID - * \param[in] maxBR : Max bit rate supported by the Poller - * \param[in] PARAM1 : ATTRIB PARAM1 byte (communication parameters) - * \param[in] nfcbDev : pointer to the NFC-B Device containing the SENSB_RES - * \param[in] HLInfo : pointer to Higher layer INF (NULL if none) - * \param[in] HLInfoLen : Length HLInfo - * \param[out] isoDepDev : ISO-DEP information of the activated Listen device - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, start of asynchronous operation successful - ***************************************************************************** - */ -ReturnCode rfalIsoDepPollBStartActivation( - rfalIsoDepFSxI FSDI, - uint8_t DID, - rfalBitRate maxBR, - uint8_t PARAM1, - const rfalNfcbListenDevice* nfcbDev, - const uint8_t* HLInfo, - uint8_t HLInfoLen, - rfalIsoDepDevice* isoDepDev); - -/*! - ***************************************************************************** - * \brief ISO-DEP Poller Get NFC-B Activation Status - * - * Returns the activation status started by rfalIsoDepPollBStartActivation - * - * \see rfalIsoDepPollBStartActivation - * - * \return ERR_BUSY : Operation is ongoing - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, activation successful - ***************************************************************************** - */ -ReturnCode rfalIsoDepPollBGetActivationStatus(void); - -#endif /* RFAL_ISODEP_H_ */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_nfc.h b/lib/ST25RFAL002/include/rfal_nfc.h deleted file mode 100644 index 88a740a0a..000000000 --- a/lib/ST25RFAL002/include/rfal_nfc.h +++ /dev/null @@ -1,425 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfc.h - * - * \brief RFAL NFC device - * - * This module provides the required features to behave as an NFC Poller - * or Listener device. It grants an easy to use interface for the following - * activities: Technology Detection, Collision Resolution, Activation, - * Data Exchange, and Deactivation - * - * This layer is influenced by (but not fully aligned with) the NFC Forum - * specifications, in particular: Activity 2.0 and NCI 2.0 - * - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-HL - * \brief RFAL Higher Layer - * @{ - * - * \addtogroup NFC - * \brief RFAL NFC Device - * @{ - * - */ - -#ifndef RFAL_NFC_H -#define RFAL_NFC_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" -#include "rfal_nfca.h" -#include "rfal_nfcb.h" -#include "rfal_nfcf.h" -#include "rfal_nfcv.h" -#include "rfal_st25tb.h" -#include "rfal_nfcDep.h" -#include "rfal_isoDep.h" - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ - -#define RFAL_NFC_TECH_NONE 0x0000U /*!< No technology */ -#define RFAL_NFC_POLL_TECH_A 0x0001U /*!< NFC-A technology Flag */ -#define RFAL_NFC_POLL_TECH_B 0x0002U /*!< NFC-B technology Flag */ -#define RFAL_NFC_POLL_TECH_F 0x0004U /*!< NFC-F technology Flag */ -#define RFAL_NFC_POLL_TECH_V 0x0008U /*!< NFC-V technology Flag */ -#define RFAL_NFC_POLL_TECH_AP2P 0x0010U /*!< AP2P technology Flag */ -#define RFAL_NFC_POLL_TECH_ST25TB 0x0020U /*!< ST25TB technology Flag */ -#define RFAL_NFC_LISTEN_TECH_A 0x1000U /*!< NFC-V technology Flag */ -#define RFAL_NFC_LISTEN_TECH_B 0x2000U /*!< NFC-V technology Flag */ -#define RFAL_NFC_LISTEN_TECH_F 0x4000U /*!< NFC-V technology Flag */ -#define RFAL_NFC_LISTEN_TECH_AP2P 0x8000U /*!< NFC-V technology Flag */ - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ - -/*! Checks if a device is currently activated */ -#define rfalNfcIsDevActivated(st) \ - (((st) >= RFAL_NFC_STATE_ACTIVATED) && ((st) < RFAL_NFC_STATE_DEACTIVATION)) - -/*! Checks if a device is in discovery */ -#define rfalNfcIsInDiscovery(st) \ - (((st) >= RFAL_NFC_STATE_START_DISCOVERY) && ((st) < RFAL_NFC_STATE_ACTIVATED)) - -/*! Checks if remote device is in Poll mode */ -#define rfalNfcIsRemDevPoller(tp) \ - (((tp) >= RFAL_NFC_POLL_TYPE_NFCA) && ((tp) <= RFAL_NFC_POLL_TYPE_AP2P)) - -/*! Checks if remote device is in Listen mode */ -#define rfalNfcIsRemDevListener(tp) \ - (((int16_t)(tp) >= (int16_t)RFAL_NFC_LISTEN_TYPE_NFCA) && ((tp) <= RFAL_NFC_LISTEN_TYPE_AP2P)) - -/* -****************************************************************************** -* GLOBAL ENUMS -****************************************************************************** -*/ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! Main state */ -typedef enum { - RFAL_NFC_STATE_NOTINIT = 0, /*!< Not Initialized state */ - RFAL_NFC_STATE_IDLE = 1, /*!< Initialize state */ - RFAL_NFC_STATE_START_DISCOVERY = 2, /*!< Start Discovery loop state */ - RFAL_NFC_STATE_WAKEUP_MODE = 3, /*!< Wake-Up state */ - RFAL_NFC_STATE_POLL_TECHDETECT = 10, /*!< Technology Detection state */ - RFAL_NFC_STATE_POLL_COLAVOIDANCE = 11, /*!< Collision Avoidance state */ - RFAL_NFC_STATE_POLL_SELECT = 12, /*!< Wait for Selection state */ - RFAL_NFC_STATE_POLL_ACTIVATION = 13, /*!< Activation state */ - RFAL_NFC_STATE_LISTEN_TECHDETECT = 20, /*!< Listen Tech Detect */ - RFAL_NFC_STATE_LISTEN_COLAVOIDANCE = 21, /*!< Listen Collision Avoidance */ - RFAL_NFC_STATE_LISTEN_ACTIVATION = 22, /*!< Listen Activation state */ - RFAL_NFC_STATE_LISTEN_SLEEP = 23, /*!< Listen Sleep state */ - RFAL_NFC_STATE_ACTIVATED = 30, /*!< Activated state */ - RFAL_NFC_STATE_DATAEXCHANGE = 31, /*!< Data Exchange Start state */ - RFAL_NFC_STATE_DATAEXCHANGE_DONE = 33, /*!< Data Exchange terminated */ - RFAL_NFC_STATE_DEACTIVATION = 34 /*!< Deactivation state */ -} rfalNfcState; - -/*! Device type */ -typedef enum { - RFAL_NFC_LISTEN_TYPE_NFCA = 0, /*!< NFC-A Listener device type */ - RFAL_NFC_LISTEN_TYPE_NFCB = 1, /*!< NFC-B Listener device type */ - RFAL_NFC_LISTEN_TYPE_NFCF = 2, /*!< NFC-F Listener device type */ - RFAL_NFC_LISTEN_TYPE_NFCV = 3, /*!< NFC-V Listener device type */ - RFAL_NFC_LISTEN_TYPE_ST25TB = 4, /*!< ST25TB Listener device type */ - RFAL_NFC_LISTEN_TYPE_AP2P = 5, /*!< AP2P Listener device type */ - RFAL_NFC_POLL_TYPE_NFCA = 10, /*!< NFC-A Poller device type */ - RFAL_NFC_POLL_TYPE_NFCB = 11, /*!< NFC-B Poller device type */ - RFAL_NFC_POLL_TYPE_NFCF = 12, /*!< NFC-F Poller device type */ - RFAL_NFC_POLL_TYPE_NFCV = 13, /*!< NFC-V Poller device type */ - RFAL_NFC_POLL_TYPE_AP2P = 15 /*!< AP2P Poller device type */ -} rfalNfcDevType; - -/*! Device interface */ -typedef enum { - RFAL_NFC_INTERFACE_RF = 0, /*!< RF Frame interface */ - RFAL_NFC_INTERFACE_ISODEP = 1, /*!< ISO-DEP interface */ - RFAL_NFC_INTERFACE_NFCDEP = 2 /*!< NFC-DEP interface */ -} rfalNfcRfInterface; - -/*! Device struct containing all its details */ -typedef struct { - rfalNfcDevType type; /*!< Device's type */ - union { /* PRQA S 0750 # MISRA 19.2 - Members of the union will not be used concurrently, only one technology at a time */ - rfalNfcaListenDevice nfca; /*!< NFC-A Listen Device instance */ - rfalNfcbListenDevice nfcb; /*!< NFC-B Listen Device instance */ - rfalNfcfListenDevice nfcf; /*!< NFC-F Listen Device instance */ - rfalNfcvListenDevice nfcv; /*!< NFC-V Listen Device instance */ - rfalSt25tbListenDevice st25tb; /*!< ST25TB Listen Device instance*/ - } dev; /*!< Device's instance */ - - uint8_t* nfcid; /*!< Device's NFCID */ - uint8_t nfcidLen; /*!< Device's NFCID length */ - rfalNfcRfInterface rfInterface; /*!< Device's interface */ - - union { /* PRQA S 0750 # MISRA 19.2 - Members of the union will not be used concurrently, only one protocol at a time */ - rfalIsoDepDevice isoDep; /*!< ISO-DEP instance */ - rfalNfcDepDevice nfcDep; /*!< NFC-DEP instance */ - } proto; /*!< Device's protocol */ -} rfalNfcDevice; - -/*! Discovery parameters */ -typedef struct { - rfalComplianceMode compMode; /*!< Compliance mode to be used */ - uint16_t techs2Find; /*!< Technologies to search for */ - uint16_t totalDuration; /*!< Duration of a whole Poll + Listen cycle */ - uint8_t devLimit; /*!< Max number of devices */ - rfalBitRate maxBR; /*!< Max Bit rate to be used for communications */ - - rfalBitRate nfcfBR; /*!< Bit rate to poll for NFC-F */ - uint8_t - nfcid3[RFAL_NFCDEP_NFCID3_LEN]; /*!< NFCID3 to be used on the ATR_REQ/ATR_RES */ - uint8_t GB[RFAL_NFCDEP_GB_MAX_LEN]; /*!< General bytes to be used on the ATR-REQ */ - uint8_t GBLen; /*!< Length of the General Bytes */ - rfalBitRate ap2pBR; /*!< Bit rate to poll for AP2P */ - - rfalLmConfPA lmConfigPA; /*!< Configuration for Passive Listen mode NFC-A */ - rfalLmConfPF lmConfigPF; /*!< Configuration for Passive Listen mode NFC-A */ - - void (*notifyCb)(rfalNfcState st); /*!< Callback to Notify upper layer */ - - bool wakeupEnabled; /*!< Enable Wake-Up mode before polling */ - bool wakeupConfigDefault; /*!< Wake-Up mode default configuration */ - rfalWakeUpConfig wakeupConfig; /*!< Wake-Up mode configuration */ - - bool activate_after_sak; // Set device to Active mode after SAK response -} rfalNfcDiscoverParam; - -/*! Buffer union, only one interface is used at a time */ -typedef union { /* PRQA S 0750 # MISRA 19.2 - Members of the union will not be used concurrently, only one interface at a time */ - uint8_t rfBuf[RFAL_FEATURE_NFC_RF_BUF_LEN]; /*!< RF buffer */ - rfalIsoDepApduBufFormat isoDepBuf; /*!< ISO-DEP buffer format (with header/prologue) */ - rfalNfcDepPduBufFormat nfcDepBuf; /*!< NFC-DEP buffer format (with header/prologue) */ -} rfalNfcBuffer; - -/*******************************************************************************/ - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief RFAL NFC Worker - * - * It runs the internal state machine and runs the RFAL RF worker. - ***************************************************************************** - */ -void rfalNfcWorker(void); - -/*! - ***************************************************************************** - * \brief RFAL NFC Initialize - * - * It initializes this module and its dependencies - * - * \return ERR_WRONG_STATE : Incorrect state for this operation - * \return ERR_IO : Generic internal error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcInitialize(void); - -/*! - ***************************************************************************** - * \brief RFAL NFC Discovery - * - * It set the device in Discovery state. - * In discovery it will Poll and/or Listen for the technologies configured, - * and perform Wake-up mode if configured to do so. - * - * The device list passed on disParams must not be empty. - * The number of devices on the list is indicated by the devLimit and shall - * be at >= 1. - * - * \param[in] disParams : discovery configuration parameters - * - * \return ERR_WRONG_STATE : Incorrect state for this operation - * \return ERR_PARAM : Invalid parameters - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcDiscover(const rfalNfcDiscoverParam* disParams); - -/*! - ***************************************************************************** - * \brief RFAL NFC Get State - * - * It returns the current state - * - * \return rfalNfcState : the current state - ***************************************************************************** - */ -rfalNfcState rfalNfcGetState(void); - -/*! - ***************************************************************************** - * \brief RFAL NFC Get Devices Found - * - * It returns the location of the device list and the number of - * devices found. - * - * \param[out] devList : device list location - * \param[out] devCnt : number of devices found - * - * \return ERR_WRONG_STATE : Incorrect state for this operation - * Discovery still ongoing - * \return ERR_PARAM : Invalid parameters - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcGetDevicesFound(rfalNfcDevice** devList, uint8_t* devCnt); - -/*! - ***************************************************************************** - * \brief RFAL NFC Get Active Device - * - * It returns the location of the device current Active device - * - * \param[out] dev : device info location - * - * \return ERR_WRONG_STATE : Incorrect state for this operation - * No device activated - * \return ERR_PARAM : Invalid parameters - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcGetActiveDevice(rfalNfcDevice** dev); - -/*! - ***************************************************************************** - * \brief RFAL NFC Select Device - * - * It selects the device to be activated. - * It shall be called when more than one device has been identified to - * indiacte which device shall be active - * - * \param[in] devIdx : device index to be activated - * - * \return ERR_WRONG_STATE : Incorrect state for this operation - * Not in select state - * \return ERR_PARAM : Invalid parameters - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcSelect(uint8_t devIdx); - -/*! - ***************************************************************************** - * \brief RFAL NFC Start Data Exchange - * - * After a device has been activated, it starts a data exchange. - * It handles automatically which interface/protocol to be used and acts accordingly. - * - * In Listen mode the first frame/data shall be sent by the Reader/Initiator - * therefore this method must be called first with txDataLen set to zero - * to retrieve the rxData and rcvLen locations. - * - * - * \param[in] txData : data to be transmitted - * \param[in] txDataLen : size of the data to be transmitted - * \param[out] rxData : location of the received data after operation is completed - * \param[out] rvdLen : location of thelength of the received data - * \param[in] fwt : FWT to be used in case of RF interface. - * If ISO-DEP or NFC-DEP interface is used, this will be ignored - * - * \return ERR_WRONG_STATE : Incorrect state for this operation - * \return ERR_PARAM : Invalid parameters - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcDataExchangeStart( - uint8_t* txData, - uint16_t txDataLen, - uint8_t** rxData, - uint16_t** rvdLen, - uint32_t fwt, - uint32_t tx_flag); - -ReturnCode rfalNfcDataExchangeCustomStart( - uint8_t* txData, - uint16_t txDataLen, - uint8_t** rxData, - uint16_t** rvdLen, - uint32_t fwt, - uint32_t flags); - -/*! - ***************************************************************************** - * \brief RFAL NFC Get Data Exchange Status - * - * Gets current Data Exchange status - * - * \return ERR_NONE : Transceive done with no error - * \return ERR_BUSY : Transceive ongoing - * \return ERR_AGAIN : received one chaining block, copy received data - * and continue to call this method to retrieve the - * remaining blocks - * \return ERR_XXXX : Error occurred - * \return ERR_TIMEOUT : No response - * \return ERR_FRAMING : Framing error detected - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_LINK_LOSS : Link Loss - External Field is Off - * \return ERR_RF_COLLISION : Collision detected - * \return ERR_IO : Internal error - ***************************************************************************** - */ -ReturnCode rfalNfcDataExchangeGetStatus(void); - -/*! - ***************************************************************************** - * \brief RFAL NFC Deactivate - * - * It triggers the deactivation procedure to terminate communications with - * remote device. At the end the field will be turned off. - * - * \param[in] discovery : TRUE if after deactivation go back into discovery - * : FALSE if after deactivation remain in idle - * - * \return ERR_WRONG_STATE : Incorrect state for this operation - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcDeactivate(bool discovery); - -#endif /* RFAL_NFC_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_nfcDep.h b/lib/ST25RFAL002/include/rfal_nfcDep.h deleted file mode 100644 index 9cf770e53..000000000 --- a/lib/ST25RFAL002/include/rfal_nfcDep.h +++ /dev/null @@ -1,830 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfcDep.h - * - * \author Gustavo Patricio - * - * \brief Implementation of NFC-DEP protocol - * - * NFC-DEP is also known as NFCIP - Near Field Communication - * Interface and Protocol - * - * This implementation was based on the following specs: - * - NFC Forum Digital 1.1 - * - ECMA 340 3rd Edition 2013 - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup NFC-DEP - * \brief RFAL NFC-DEP Module - * @{ - */ - -#ifndef RFAL_NFCDEP_H_ -#define RFAL_NFCDEP_H_ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_NFC_DEP -#define RFAL_FEATURE_NFC_DEP \ - false /*!< NFC-DEP module configuration missing. Disabled by default */ -#endif - -/* If module is disabled remove the need for the user to set lengths */ -#if !RFAL_FEATURE_NFC_DEP -#undef RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN -#undef RFAL_FEATURE_NFC_DEP_PDU_MAX_LEN - -#define RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN 1U /*!< NFC-DEP Block/Payload length, set to "none" */ -#define RFAL_FEATURE_NFC_DEP_PDU_MAX_LEN 1U /*!< NFC-DEP PDU length, set to "none" */ -#endif /* !RFAL_FEATURE_NFC_DEP */ - -/* - ****************************************************************************** - * DEFINES - ****************************************************************************** - */ -#define RFAL_NFCDEP_FRAME_SIZE_MAX_LEN \ - 254U /*!< Maximum Frame Size Digital 2.0 Table 90 */ -#define RFAL_NFCDEP_DEPREQ_HEADER_LEN \ - 5U /*!< DEP_REQ header length: CMD_TYPE + CMD_CMD + PBF + DID + NAD */ - -/*! Length NFCIP DEP REQ or RES header (incl LEN) */ -#define RFAL_NFCDEP_DEP_HEADER \ - (RFAL_NFCDEP_LEN_LEN + RFAL_NFCDEP_CMDTYPE_LEN + RFAL_NFCDEP_CMD_LEN + RFAL_NFCDEP_DEP_PFB_LEN) -#define RFAL_NFCDEP_HEADER \ - (RFAL_NFCDEP_CMDTYPE_LEN + RFAL_NFCDEP_CMD_LEN) /*!< NFCIP header length */ -#define RFAL_NFCDEP_SB_LEN \ - 1U /*!< SB length on NFCIP fram for NFC-A */ -#define RFAL_NFCDEP_LEN_LEN \ - 1U /*!< LEN length on NFCIP frame */ -#define RFAL_NFCDEP_CMDTYPE_LEN \ - 1U /*!< Length of the cmd type (REQ | RES) on NFCIP frame */ -#define RFAL_NFCDEP_CMD_LEN \ - 1U /*!< Length of the cmd on NFCIP frame */ -#define RFAL_NFCDEP_DID_LEN \ - 1U /*!< Length of did on NFCIP frame */ -#define RFAL_NFCDEP_DEP_PFB_LEN \ - 1U /*!< Length of the PFB field on NFCIP frame */ - -#define RFAL_NFCDEP_DSL_RLS_LEN_NO_DID \ - (RFAL_NFCDEP_LEN_LEN + RFAL_NFCDEP_CMDTYPE_LEN + \ - RFAL_NFCDEP_CMD_LEN) /*!< Length of DSL_REQ and RLS_REQ with no DID */ -#define RFAL_NFCDEP_DSL_RLS_LEN_DID \ - (RFAL_NFCDEP_DSL_RLS_LEN_NO_DID + \ - RFAL_NFCDEP_DID_LEN) /*!< Length of DSL_REQ and RLS_REQ with DID */ - -#define RFAL_NFCDEP_FS_VAL_MIN \ - 64U /*!< Minimum LR value */ -#define RFAL_NFCDEP_LR_VAL_MASK \ - 0x03U /*!< Bit mask for a LR value */ -#define RFAL_NFCDEP_PP_LR_MASK \ - 0x30U /*!< Bit mask for LR value in PP byte on a ATR REQ/RES */ -#define RFAL_NFCDEP_PP_LR_SHIFT \ - 4U /*!< Position of LR value in PP byte on a ATR REQ/RES */ - -#define RFAL_NFCDEP_DID_MAX \ - 14U /*!< Max DID value Digital 14.6.2.3 */ -#define RFAL_NFCDEP_DID_KEEP \ - 0xFFU /*!< Keep DID value already configured */ -#define RFAL_NFCDEP_DID_NO \ - 0x00U /*!< No DID shall be used */ -#define RFAL_NFCDEP_NAD_NO \ - 0x00U /*!< No NAD shall be used */ - -#define RFAL_NFCDEP_OPER_RTOX_REQ_DIS \ - 0x01U /*!< Operation config: RTOX REQ disable */ -#define RFAL_NFCDEP_OPER_RTOX_REQ_EN \ - 0x00U /*!< Operation config: RTOX REQ enable */ - -#define RFAL_NFCDEP_OPER_ATN_DIS \ - 0x00U /*!< Operation config: ATN disable */ -#define RFAL_NFCDEP_OPER_ATN_EN \ - 0x02U /*!< Operation config: ATN enable */ - -#define RFAL_NFCDEP_OPER_EMPTY_DEP_DIS \ - 0x04U /*!< Operation config: empty DEPs disable */ -#define RFAL_NFCDEP_OPER_EMPTY_DEP_EN \ - 0x00U /*!< Operation config: empty DEPs enable */ - -#define RFAL_NFCDEP_OPER_FULL_MI_DIS \ - 0x00U /*!< Operation config: full chaining DEPs disable */ -#define RFAL_NFCDEP_OPER_FULL_MI_EN \ - 0x08U /*!< Operation config: full chaining DEPs enable */ - -#define RFAL_NFCDEP_BRS_MAINTAIN \ - 0xC0U /*!< Value signalling that BR is to be maintained (no PSL) */ -#define RFAL_NFCDEP_BRS_Dx_MASK \ - 0x07U /*!< Value signalling that BR is to be maintained (no PSL) */ -#define RFAL_NFCDEP_BRS_DSI_POS \ - 3U /*!< Value signalling that BR is to be maintained (no PSL) */ - -#define RFAL_NFCDEP_WT_DELTA \ - (16U - RFAL_NFCDEP_WT_DELTA_ADJUST) /*!< NFC-DEP dWRT (adjusted) Digital 2.0 B.10 */ -#define RFAL_NFCDEP_WT_DELTA_ADJUST \ - 4U /*!< dWRT value adjustment */ - -#define RFAL_NFCDEP_ATR_REQ_NFCID3_POS \ - 2U /*!< NFCID3 offset in ATR_REQ frame */ -#define RFAL_NFCDEP_NFCID3_LEN \ - 10U /*!< NFCID3 Length */ - -#define RFAL_NFCDEP_LEN_MIN \ - 3U /*!< Minimum length byte LEN value */ -#define RFAL_NFCDEP_LEN_MAX \ - 255U /*!< Maximum length byte LEN value */ - -#define RFAL_NFCDEP_ATRRES_HEADER_LEN \ - 2U /*!< ATR RES Header Len: CmdType: 0xD5 + Cod: 0x01 */ -#define RFAL_NFCDEP_ATRRES_MIN_LEN \ - 17U /*!< Minimum length for an ATR RES */ -#define RFAL_NFCDEP_ATRRES_MAX_LEN \ - 64U /*!< Maximum length for an ATR RES Digital 1.0 14.6.1 */ -#define RFAL_NFCDEP_ATRREQ_MIN_LEN \ - 16U /*!< Minimum length for an ATR REQ */ -#define RFAL_NFCDEP_ATRREQ_MAX_LEN \ - RFAL_NFCDEP_ATRRES_MAX_LEN /*!< Maximum length for an ATR REQ Digital 1.0 14.6.1 */ - -#define RFAL_NFCDEP_GB_MAX_LEN \ - (RFAL_NFCDEP_ATRREQ_MAX_LEN - \ - RFAL_NFCDEP_ATRREQ_MIN_LEN) /*!< Maximum length the General Bytes on ATR Digital 1.1 16.6.3 */ - -#define RFAL_NFCDEP_WT_INI_DEFAULT \ - RFAL_NFCDEP_WT_INI_MAX /*!< WT Initiator default value Digital 1.0 14.6.3.8 */ -#define RFAL_NFCDEP_WT_INI_MIN 0U /*!< WT Initiator minimum value Digital 1.0 14.6.3.8 */ -#define RFAL_NFCDEP_WT_INI_MAX 14U /*!< WT Initiator maximum value Digital 1.0 14.6.3.8 A.10 */ -#define RFAL_NFCDEP_RWT_INI_MAX \ - rfalNfcDepWT2RWT(RFAL_NFCDEP_WT_INI_MAX) /*!< RWT Initiator maximum value */ - -#define RFAL_NFCDEP_WT_TRG_MAX_D10 8U /*!< WT target max Digital 1.0 14.6.3.8 A.10 */ -#define RFAL_NFCDEP_WT_TRG_MAX_D11 14U /*!< WT target max Digital 1.1 16.6.3.9 A.9 */ -#define RFAL_NFCDEP_WT_TRG_MAX_L13 10U /*!< WT target max [LLCP] 1.3 6.2.1 */ -#define RFAL_NFCDEP_WT_TRG_MAX \ - RFAL_NFCDEP_WT_TRG_MAX_D11 /*!< WT target max Digital x.x | LLCP x.x */ -#define RFAL_NFCDEP_RWT_TRG_MAX \ - rfalNfcDepWT2RWT(RFAL_NFCDEP_WT_TRG_MAX) /*!< RWT Initiator maximum value */ - -/*! Maximum Frame Waiting Time = ((256 * 16/fc)*2^FWImax) = ((256*16/fc)*2^14) = (1048576 / 64)/fc = (100000h*64)/fc */ -#define RFAL_NFCDEP_MAX_FWT ((uint32_t)1U << 20) - -#define RFAL_NFCDEP_WT_MASK \ - 0x0FU /*!< Bit mask for the Wait Time value */ - -#define RFAL_NFCDEP_BR_MASK_106 \ - 0x01U /*!< Enable mask bit rate 106 */ -#define RFAL_NFCDEP_BR_MASK_212 \ - 0x02U /*!< Enable mask bit rate 242 */ -#define RFAL_NFCDEP_BR_MASK_424 \ - 0x04U /*!< Enable mask bit rate 424 */ - -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ - -#define rfalNfcDepWT2RWT(wt) \ - ((uint32_t)1U \ - << (((uint32_t)(wt)&RFAL_NFCDEP_WT_MASK) + \ - 12U)) /*!< Converts WT value to RWT (1/fc) */ - -/*! Returns the BRS value from the given bit rate */ -#define rfalNfcDepDx2BRS(br) \ - ((((uint8_t)(br)&RFAL_NFCDEP_BRS_Dx_MASK) << RFAL_NFCDEP_BRS_DSI_POS) | \ - ((uint8_t)(br)&RFAL_NFCDEP_BRS_Dx_MASK)) - -#define rfalNfcDepBRS2DRI(brs) \ - (uint8_t)(( \ - uint8_t)(brs)&RFAL_NFCDEP_BRS_Dx_MASK) /*!< Returns the DRI value from the given BRS byte */ -#define rfalNfcDepBRS2DSI(brs) \ - (uint8_t)( \ - ((uint8_t)(brs) >> RFAL_NFCDEP_BRS_DSI_POS) & \ - RFAL_NFCDEP_BRS_Dx_MASK) /*!< Returns the DSI value from the given BRS byte */ - -#define rfalNfcDepPP2LR(PPx) \ - (((uint8_t)(PPx)&RFAL_NFCDEP_PP_LR_MASK) >> \ - RFAL_NFCDEP_PP_LR_SHIFT) /*!< Returns the LR value from the given PPx byte */ -#define rfalNfcDepLR2PP(LRx) \ - (((uint8_t)(LRx) << RFAL_NFCDEP_PP_LR_SHIFT) & \ - RFAL_NFCDEP_PP_LR_MASK) /*!< Returns the PP byte with the given LRx value */ - -/*! Returns the Frame size value from the given LRx value */ -#define rfalNfcDepLR2FS(LRx) \ - (uint16_t)( \ - MIN((RFAL_NFCDEP_FS_VAL_MIN * ((uint16_t)(LRx) + 1U)), RFAL_NFCDEP_FRAME_SIZE_MAX_LEN)) - -/*! - * Despite DIGITAL 1.0 14.6.2.1 stating that the last two bytes may filled with - * any value, some devices (Samsung Google Nexus) only accept when these are 0 */ -#define rfalNfcDepSetNFCID(dst, src, len) \ - ST_MEMSET((dst), 0x00, RFAL_NFCDEP_NFCID3_LEN); \ - if((len) > 0U) { \ - ST_MEMCPY((dst), (src), (len)); \ - } - -/* - ****************************************************************************** - * GLOBAL ENUMERATIONS - ****************************************************************************** - */ - -/*! Enumeration of NFC-DEP bit rate in ATR Digital 1.0 Table 93 and 94 */ -enum { - RFAL_NFCDEP_Bx_NO_HIGH_BR = 0x00, /*!< Peer supports no high bit rates */ - RFAL_NFCDEP_Bx_08_848 = 0x01, /*!< Peer also supports 848 */ - RFAL_NFCDEP_Bx_16_1695 = 0x02, /*!< Peer also supports 1695 */ - RFAL_NFCDEP_Bx_32_3390 = 0x04, /*!< Peer also supports 3390 */ - RFAL_NFCDEP_Bx_64_6780 = 0x08 /*!< Peer also supports 6780 */ -}; - -/*! Enumeration of NFC-DEP bit rate Divider in PSL Digital 1.0 Table 100 */ -enum { - RFAL_NFCDEP_Dx_01_106 = RFAL_BR_106, /*!< Divisor D = 1 : bit rate = 106 */ - RFAL_NFCDEP_Dx_02_212 = RFAL_BR_212, /*!< Divisor D = 2 : bit rate = 212 */ - RFAL_NFCDEP_Dx_04_424 = RFAL_BR_424, /*!< Divisor D = 4 : bit rate = 424 */ - RFAL_NFCDEP_Dx_08_848 = RFAL_BR_848, /*!< Divisor D = 8 : bit rate = 848 */ - RFAL_NFCDEP_Dx_16_1695 = RFAL_BR_1695, /*!< Divisor D = 16 : bit rate = 1695 */ - RFAL_NFCDEP_Dx_32_3390 = RFAL_BR_3390, /*!< Divisor D = 32 : bit rate = 3390 */ - RFAL_NFCDEP_Dx_64_6780 = RFAL_BR_6780 /*!< Divisor D = 64 : bit rate = 6780 */ -}; - -/*! Enumeration of NFC-DEP Length Reduction (LR) Digital 1.0 Table 91 */ -enum { - RFAL_NFCDEP_LR_64 = 0x00, /*!< Maximum payload size is 64 bytes */ - RFAL_NFCDEP_LR_128 = 0x01, /*!< Maximum payload size is 128 bytes */ - RFAL_NFCDEP_LR_192 = 0x02, /*!< Maximum payload size is 192 bytes */ - RFAL_NFCDEP_LR_254 = 0x03 /*!< Maximum payload size is 254 bytes */ -}; - -/* - ****************************************************************************** - * GLOBAL DATA TYPES - ****************************************************************************** - */ - -/*! NFC-DEP callback to check if upper layer has deactivation pending */ -typedef bool (*rfalNfcDepDeactCallback)(void); - -/*! Enumeration of the nfcip communication modes */ -typedef enum { - RFAL_NFCDEP_COMM_PASSIVE, /*!< Passive communication mode */ - RFAL_NFCDEP_COMM_ACTIVE /*!< Active communication mode */ -} rfalNfcDepCommMode; - -/*! Enumeration of the nfcip roles */ -typedef enum { - RFAL_NFCDEP_ROLE_INITIATOR, /*!< Perform as Initiator */ - RFAL_NFCDEP_ROLE_TARGET /*!< Perform as Target */ -} rfalNfcDepRole; - -/*! Struct that holds all NFCIP configs */ -typedef struct { - rfalNfcDepRole role; /*!< Current NFCIP role */ - rfalNfcDepCommMode commMode; /*!< Current NFCIP communication mode */ - uint8_t oper; /*!< Operation config similar to NCI 1.0 Table 81 */ - - uint8_t did; /*!< Current Device ID (DID) */ - uint8_t nad; /*!< Current Node Addressing (NAD) */ - uint8_t bs; /*!< Bit rate in Sending Direction */ - uint8_t br; /*!< Bit rate in Receiving Direction */ - uint8_t nfcid[RFAL_NFCDEP_NFCID3_LEN]; /*!< Pointer to the NFCID to be used */ - uint8_t nfcidLen; /*!< Length of the given NFCID in nfcid */ - uint8_t gb[RFAL_NFCDEP_GB_MAX_LEN]; /*!< Pointer General Bytes (GB) to be used */ - uint8_t gbLen; /*!< Length of the given GB in gb */ - uint8_t lr; /*!< Length Reduction (LR) to be used */ - uint8_t to; /*!< Timeout (TO) to be used */ - uint32_t fwt; /*!< Frame Waiting Time (FWT) to be used */ - uint32_t dFwt; /*!< Delta Frame Waiting Time (dFWT) to be used */ -} rfalNfcDepConfigs; - -/*! ATR_REQ command Digital 1.1 16.6.2 */ -typedef struct { - uint8_t CMD1; /*!< Command format 0xD4 */ - uint8_t CMD2; /*!< Command Value */ - uint8_t NFCID3[RFAL_NFCDEP_NFCID3_LEN]; /*!< NFCID3 value */ - uint8_t DID; /*!< DID */ - uint8_t BSi; /*!< Sending Bitrate for Initiator */ - uint8_t BRi; /*!< Receiving Bitrate for Initiator */ - uint8_t PPi; /*!< Optional Parameters presence indicator */ - uint8_t GBi[RFAL_NFCDEP_GB_MAX_LEN]; /*!< General Bytes */ -} rfalNfcDepAtrReq; - -/*! ATR_RES response Digital 1.1 16.6.3 */ -typedef struct { - uint8_t CMD1; /*!< Response Byte 0xD5 */ - uint8_t CMD2; /*!< Command Value */ - uint8_t NFCID3[RFAL_NFCDEP_NFCID3_LEN]; /*!< NFCID3 value */ - uint8_t DID; /*!< DID */ - uint8_t BSt; /*!< Sending Bitrate for Initiator */ - uint8_t BRt; /*!< Receiving Bitrate for Initiator */ - uint8_t TO; /*!< Timeout */ - uint8_t PPt; /*!< Optional Parameters presence indicator */ - uint8_t GBt[RFAL_NFCDEP_GB_MAX_LEN]; /*!< General Bytes */ -} rfalNfcDepAtrRes; - -/*! Structure of transmit I-PDU Buffer format from caller */ -typedef struct { - uint8_t prologue[RFAL_NFCDEP_DEPREQ_HEADER_LEN]; /*!< Prologue space for NFC-DEP header*/ - uint8_t inf[RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN]; /*!< INF | Data area of the buffer */ -} rfalNfcDepBufFormat; - -/*! Structure of APDU Buffer format from caller */ -typedef struct { - uint8_t prologue[RFAL_NFCDEP_DEPREQ_HEADER_LEN]; /*!< Prologue/SoD buffer */ - uint8_t pdu[RFAL_FEATURE_NFC_DEP_PDU_MAX_LEN]; /*!< Complete PDU/Payload buffer */ -} rfalNfcDepPduBufFormat; - -/*! Activation info as Initiator and Target */ -typedef union { /* PRQA S 0750 # MISRA 19.2 - Both members of the union will not be used concurrently , device is only initiatior or target a time. No problem can occur. */ - struct { - rfalNfcDepAtrRes ATR_RES; /*!< ATR RES (Initiator mode) */ - uint8_t ATR_RESLen; /*!< ATR RES length (Initiator mode) */ - } Target; /*!< Target */ - struct { - rfalNfcDepAtrReq ATR_REQ; /*!< ATR REQ (Target mode) */ - uint8_t ATR_REQLen; /*!< ATR REQ length (Target mode) */ - } Initiator; /*!< Initiator */ -} rfalNfcDepActivation; - -/*! NFC-DEP device Info */ -typedef struct { - uint8_t GBLen; /*!< General Bytes length */ - uint8_t WT; /*!< WT to be used (ignored in Listen Mode) */ - uint32_t FWT; /*!< FWT to be used (1/fc)(ignored Listen Mode) */ - uint32_t dFWT; /*!< Delta FWT to be used (1/fc) */ - uint8_t LR; /*!< Length Reduction coding the max payload */ - uint16_t FS; /*!< Frame Size */ - rfalBitRate DSI; /*!< Bit Rate coding from Initiator to Target */ - rfalBitRate DRI; /*!< Bit Rate coding from Target to Initiator */ - uint8_t DID; /*!< Device ID (RFAL_NFCDEP_DID_NO if no DID) */ - uint8_t NAD; /*!< Node ADdress (RFAL_NFCDEP_NAD_NO if no NAD)*/ -} rfalNfcDepInfo; - -/*! NFC-DEP Device structure */ -typedef struct { - rfalNfcDepActivation activation; /*!< Activation Info */ - rfalNfcDepInfo info; /*!< NFC-DEP device Info */ -} rfalNfcDepDevice; - -/*! NFCIP Protocol structure for P2P Target - * - * operParam : derives from NFC-Forum NCI NFC-DEP Operation Parameter - * NCI 1.1 Table 86: NFC-DEP Operation Parameter - * and it's a bit mask composed as: - * [ 0000b - * | Chain SHALL use max. Transport Data Byte[1b] - * | I-PDU with no Transport Data SHALL NOT be sent [1b] - * | NFC-DEP Target SHALL NOT send RTOX request [1b] - * ] - * - */ -typedef struct { - rfalNfcDepCommMode commMode; /*!< Initiator in Active P2P or Passive P2P*/ - uint8_t operParam; /*!< NFC-DEP Operation Parameter */ - uint8_t* nfcid; /*!< Initiator's NFCID2 or NFCID3 */ - uint8_t nfcidLen; /*!< Initiator's NFCID length (NFCID2/3) */ - uint8_t DID; /*!< Initiator's Device ID DID */ - uint8_t NAD; /*!< Initiator's Node ID NAD */ - uint8_t BS; /*!< Initiator's Bit Rates supported in Tx */ - uint8_t BR; /*!< Initiator's Bit Rates supported in Rx */ - uint8_t LR; /*!< Initiator's Length reduction */ - uint8_t* GB; /*!< Initiator's General Bytes (Gi) */ - uint8_t GBLen; /*!< Initiator's General Bytes length */ -} rfalNfcDepAtrParam; - -/*! Structure of parameters to be passed in for nfcDepListenStartActivation */ -typedef struct { - rfalNfcDepBufFormat* rxBuf; /*!< Receive Buffer struct reference */ - uint16_t* rxLen; /*!< Receive INF data length in bytes */ - bool* isRxChaining; /*!< Received data is not complete */ - rfalNfcDepDevice* nfcDepDev; /*!< NFC-DEP device info */ -} rfalNfcDepListenActvParam; - -/*! NFCIP Protocol structure for P2P Target - * - * operParam : derives from NFC-Forum NCI NFC-DEP Operation Parameter - * NCI 1.1 Table 86: NFC-DEP Operation Parameter - * and it's a bit mask composed as: - * [ 0000b - * | Chain SHALL use max. Transport Data Byte[1b] - * | I-PDU with no Transport Data SHALL NOT be sent [1b] - * | NFC-DEP Target SHALL NOT send RTOX request [1b] - * ] - * - */ -typedef struct { - rfalNfcDepCommMode commMode; /*!< Target in Active P2P or Passive P2P */ - uint8_t nfcid3[RFAL_NFCDEP_NFCID3_LEN]; /*!< Target's NFCID3 */ - uint8_t bst; /*!< Target's Bit Rates supported in Tx */ - uint8_t brt; /*!< Target's Bit Rates supported in Rx */ - uint8_t to; /*!< Target's timeout (TO) value */ - uint8_t ppt; /*!< Target's Presence optional Params(PPt)*/ - uint8_t GBt[RFAL_NFCDEP_GB_MAX_LEN]; /*!< Target's General Bytes (Gt) */ - uint8_t GBtLen; /*!< Target's General Bytes length */ - uint8_t operParam; /*!< NFC-DEP Operation Parameter */ -} rfalNfcDepTargetParam; - -/*! Structure of parameters to be passed in for nfcDepStartIpduTransceive */ -typedef struct { - rfalNfcDepBufFormat* txBuf; /*!< Transmit Buffer struct reference */ - uint16_t txBufLen; /*!< Transmit Buffer INF field length in bytes */ - bool isTxChaining; /*!< Transmit data is not complete */ - rfalNfcDepBufFormat* rxBuf; /*!< Receive Buffer struct reference */ - uint16_t* rxLen; /*!< Receive INF data length */ - bool* isRxChaining; /*!< Received data is not complete */ - uint32_t FWT; /*!< FWT to be used (ignored in Listen Mode) */ - uint32_t dFWT; /*!< Delta FWT to be used */ - uint16_t FSx; /*!< Other device Frame Size (FSD or FSC) */ - uint8_t DID; /*!< Device ID (RFAL_ISODEP_NO_DID if no DID) */ -} rfalNfcDepTxRxParam; - -/*! Structure of parameters used on NFC DEP PDU Transceive */ -typedef struct { - rfalNfcDepPduBufFormat* txBuf; /*!< Transmit Buffer struct reference */ - uint16_t txBufLen; /*!< Transmit Buffer INF field length in Bytes*/ - rfalNfcDepPduBufFormat* rxBuf; /*!< Receive Buffer struct reference in Bytes */ - uint16_t* rxLen; /*!< Received INF data length in Bytes */ - rfalNfcDepBufFormat* tmpBuf; /*!< Temp buffer for single PDUs (internal) */ - uint32_t FWT; /*!< FWT to be used (ignored in Listen Mode) */ - uint32_t dFWT; /*!< Delta FWT to be used */ - uint16_t FSx; /*!< Other device Frame Size (FSD or FSC) */ - uint8_t DID; /*!< Device ID (RFAL_ISODEP_NO_DID if no DID) */ -} rfalNfcDepPduTxRxParam; - -/* - * ***************************************************************************** - * GLOBAL VARIABLE DECLARATIONS - ****************************************************************************** - */ - -/* - ****************************************************************************** - * GLOBAL FUNCTION PROTOTYPES - ****************************************************************************** - */ - -/*! - ****************************************************************************** - * \brief NFCIP Initialize - * - * This method resets all NFC-DEP inner states, counters and context and sets - * default values - * - ****************************************************************************** - */ -void rfalNfcDepInitialize(void); - -/*! - ****************************************************************************** - * \brief Set deactivating callback - * - * Sets the deactivating callback so that nfcip layer can check if upper layer - * has a deactivation pending, and not perform error recovery upon specific - * errors - * - * \param[in] pFunc : method pointer to deactivation flag check - ****************************************************************************** - */ -void rfalNfcDepSetDeactivatingCallback(rfalNfcDepDeactCallback pFunc); - -/*! - ****************************************************************************** - * \brief Calculate Response Waiting Time - * - * Calculates the Response Waiting Time (RWT) from the given Waiting Time (WT) - * - * \param[in] wt : the WT value to calculate RWT - * - * \return RWT value in 1/fc - ****************************************************************************** - */ -uint32_t rfalNfcDepCalculateRWT(uint8_t wt); - -/*! - ****************************************************************************** - * \brief NFC-DEP Initiator ATR (Attribute Request) - * - * This method configures the NFC-DEP layer with given parameters and then - * sends an ATR to the Target with and checks for a valid response response - * - * \param[in] param : parameters to initialize and compose the ATR - * \param[out] atrRes : location to store the ATR_RES - * \param[out] atrResLen : length of the ATR_RES received - * - * \return ERR_NONE : No error - * \return ERR_TIMEOUT : Timeout occurred - * \return ERR_PROTO : Protocol error occurred - ****************************************************************************** - */ -ReturnCode - rfalNfcDepATR(const rfalNfcDepAtrParam* param, rfalNfcDepAtrRes* atrRes, uint8_t* atrResLen); - -/*! - ****************************************************************************** - * \brief NFC-DEP Initiator PSL (Parameter Selection) - * - * This method sends a PSL to the Target with the given parameters and checks - * for a valid response response - * - * The parameters must be coded according to Digital 1.1 16.7.1 - * - * \param[in] BRS : the selected Bit Rates for Initiator and Target - * \param[in] FSL : the maximum length of Commands and Responses - * - * \return ERR_NONE : No error - * \return ERR_TIMEOUT : Timeout occurred - * \return ERR_PROTO : Protocol error occurred - ****************************************************************************** - */ -ReturnCode rfalNfcDepPSL(uint8_t BRS, uint8_t FSL); - -/*! - ****************************************************************************** - * \brief NFC-DEP Initiator DSL (Deselect) - * - * This method checks if the NFCIP module is configured as initiator and if - * so sends a DSL REQ, waits the target's response and checks it - * - * In case of performing as target no action is taken - * - * \return ERR_NONE : No error - * \return ERR_TIMEOUT : Timeout occurred - * \return ERR_MAX_RERUNS : Timeout occurred - * \return ERR_PROTO : Protocol error occurred - ****************************************************************************** - */ -ReturnCode rfalNfcDepDSL(void); - -/*! - ****************************************************************************** - * \brief NFC-DEP Initiator RLS (Release) - * - * This method checks if the NFCIP module is configured as initiator and if - * so sends a RLS REQ, waits target's response and checks it - * - * In case of performing as target no action is taken - * - * \return ERR_NONE : No error - * \return ERR_TIMEOUT : Timeout occurred - * \return ERR_MAX_RERUNS : Timeout occurred - * \return ERR_PROTO : Protocol error occurred - ****************************************************************************** - */ -ReturnCode rfalNfcDepRLS(void); - -/*! - ***************************************************************************** - * \brief NFC-DEP Initiator Handle Activation - * - * This performs a Activation into NFC-DEP layer with the given - * parameters. It sends ATR_REQ and if the higher bit rates are supported by - * both devices it additionally sends PSL - * Once Activated all details of the device are provided on nfcDepDev - * - * \param[in] param : required parameters to initialize and send ATR_REQ - * \param[in] desiredBR : Desired bit rate supported by the Poller - * \param[out] nfcDepDev : NFC-DEP information of the activated Listen device - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, activation successful - ***************************************************************************** - */ -ReturnCode rfalNfcDepInitiatorHandleActivation( - rfalNfcDepAtrParam* param, - rfalBitRate desiredBR, - rfalNfcDepDevice* nfcDepDev); - -/*! - ****************************************************************************** - * \brief Check if buffer contains valid ATR_REQ - * - * This method checks if the given ATR_REQ is valid - * - * - * \param[in] buf : buffer holding Initiator's received request - * \param[in] bufLen : size of the msg contained on the buf in Bytes - * \param[out] nfcid3 : pointer to where the NFCID3 may be outputted, - * nfcid3 has NFCF_SENSF_NFCID3_LEN as length - * Pass NULL if output parameter not desired - * - * \return true : Valid ATR_REQ received, the ATR_RES has been computed in txBuf - * \return false : Invalid protocol request - * - ****************************************************************************** - */ -bool rfalNfcDepIsAtrReq(const uint8_t* buf, uint16_t bufLen, uint8_t* nfcid3); - -/*! - ****************************************************************************** - * \brief Check is Target has received ATR - * - * This method checks if the NFCIP module is configured as target and if a - * ATR REQ has been received ( whether is in activation or in data exchange) - * - * \return true : a ATR has already been received - * \return false : no ATR has been received - ****************************************************************************** - */ -bool rfalNfcDepTargetRcvdATR(void); - -/*! - ***************************************************************************** - * \brief NFCDEP Start Listen Activation Handling - * - * Start Activation Handling and setup to receive first frame which may - * contain complete or partial DEP-REQ after activation is completed - * - * Pass in ATR_REQ for NFC-DEP to handle ATR_RES. The Activation Handling - * handles ATR_RES and PSL_RES if a PSL_REQ is received - * - * Activation is completed if PSL_RES is sent or if first I-PDU is received - * - * \ref rfalNfcDepListenGetActivationStatus() provide status of the - * ongoing activation - * - * \warning nfcDepGetTransceiveStatus() shall be called right after activation - * is completed (i.e. rfalNfcDepListenGetActivationStatus() return ERR_NONE) - * to check for first received frame. - * - * \param[in] param : Target parameters to be used - * \param[in] atrReq : reference to buffer containing ATR_REQ - * \param[in] atrReqLength: Length of ATR_REQ - * \param[out] rxParam : references to buffer, length and chaining indication - * for first complete LLCP to be received - * - * \return ERR_NONE : ATR_REQ is valid and activation ongoing - * \return ERR_PARAM : ATR_REQ or other params are invalid - * \return ERR_LINK_LOSS : Remote Field is turned off - ***************************************************************************** - */ -ReturnCode rfalNfcDepListenStartActivation( - const rfalNfcDepTargetParam* param, - const uint8_t* atrReq, - uint16_t atrReqLength, - rfalNfcDepListenActvParam rxParam); - -/*! - ***************************************************************************** - * \brief Get the current NFC-DEP Activation Status - * - * \return ERR_NONE : Activation has completed successfully - * \return ERR_BUSY : Activation is ongoing - * \return ERR_LINK_LOSS : Remote Field was turned off - ***************************************************************************** - */ -ReturnCode rfalNfcDepListenGetActivationStatus(void); - -/*! - ***************************************************************************** - * \brief Start Transceive - * - * Transceives a complete or partial DEP block - * - * The txBuf contains complete or partial of DEP to be transmitted. - * The Prologue field of the I-PDU is handled internally - * - * If the buffer contains partial LLCP and is not the last block, then - * isTxChaining must be set to true - * - * \param[in] param: reference parameters to be used for the Transceive - * - * \return ERR_PARAM : Bad request - * \return ERR_WRONG_STATE : The module is not in a proper state - * \return ERR_NONE : The Transceive request has been started - ***************************************************************************** - */ -ReturnCode rfalNfcDepStartTransceive(const rfalNfcDepTxRxParam* param); - -/*! - ***************************************************************************** - * \brief Return the Transceive status - * - * Returns the status of the NFC-DEP Transceive - * - * \warning When the other device is performing chaining once a chained - * block is received the error ERR_AGAIN is sent. At this point - * caller must handle the received data immediately. - * When ERR_AGAIN is returned an ACK has already been sent to - * the other device and the next block might be incoming. - * If rfalWorker() is called frequently it will place the next - * block on the given buffer - * - * \return ERR_NONE : Transceive has been completed successfully - * \return ERR_BUSY : Transceive is ongoing - * \return ERR_PROTO : Protocol error occurred - * \return ERR_TIMEOUT : Timeout error occurred - * \return ERR_SLEEP_REQ : Deselect has been received and responded - * \return ERR_NOMEM : The received I-PDU does not fit into the - * receive buffer - * \return ERR_LINK_LOSS : Communication is lost because Reader/Writer - * has turned off its field - * \return ERR_AGAIN : received one chaining block, continue to call - * this method to retrieve the remaining blocks - ***************************************************************************** - */ -ReturnCode rfalNfcDepGetTransceiveStatus(void); - -/*! - ***************************************************************************** - * \brief Start PDU Transceive - * - * This method triggers a NFC-DEP Transceive containing a complete PDU - * It transmits the given message and handles all protocol retransmitions, - * error handling and control messages - * - * The txBuf contains a complete PDU to be transmitted - * The Prologue field will be manipulated by the Transceive - * - * \warning the txBuf will be modified during the transmission - * \warning the maximum RF frame which can be received is limited by param.tmpBuf - * - * \param[in] param: reference parameters to be used for the Transceive - * - * \return ERR_PARAM : Bad request - * \return ERR_WRONG_STATE : The module is not in a proper state - * \return ERR_NONE : The Transceive request has been started - ***************************************************************************** - */ -ReturnCode rfalNfcDepStartPduTransceive(rfalNfcDepPduTxRxParam param); - -/*! - ***************************************************************************** - * \brief Return the PSU Transceive status - * - * Returns the status of the NFC-DEP PDU Transceive - * - * - * \return ERR_NONE : Transceive has been completed successfully - * \return ERR_BUSY : Transceive is ongoing - * \return ERR_PROTO : Protocol error occurred - * \return ERR_TIMEOUT : Timeout error occurred - * \return ERR_SLEEP_REQ : Deselect has been received and responded - * \return ERR_NOMEM : The received I-PDU does not fit into the - * receive buffer - * \return ERR_LINK_LOSS : Communication is lost because Reader/Writer - * has turned off its field - ***************************************************************************** - */ -ReturnCode rfalNfcDepGetPduTransceiveStatus(void); - -#endif /* RFAL_NFCDEP_H_ */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_nfca.h b/lib/ST25RFAL002/include/rfal_nfca.h deleted file mode 100644 index 4772586cb..000000000 --- a/lib/ST25RFAL002/include/rfal_nfca.h +++ /dev/null @@ -1,497 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfca.h - * - * \author Gustavo Patricio - * - * \brief Provides several NFC-A convenience methods and definitions - * - * It provides a Poller (ISO14443A PCD) interface and as well as - * some NFC-A Listener (ISO14443A PICC) helpers. - * - * The definitions and helpers methods provided by this module are only - * up to ISO14443-3 layer - * - * - * An usage example is provided here: \ref exampleRfalNfca.c - * \example exampleRfalNfca.c - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup NFC-A - * \brief RFAL NFC-A Module - * @{ - * - */ - -#ifndef RFAL_NFCA_H -#define RFAL_NFCA_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" -#include "rfal_t1t.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_NFCA_CASCADE_1_UID_LEN \ - 4U /*!< UID length of cascade level 1 only tag */ -#define RFAL_NFCA_CASCADE_2_UID_LEN \ - 7U /*!< UID length of cascade level 2 only tag */ -#define RFAL_NFCA_CASCADE_3_UID_LEN \ - 10U /*!< UID length of cascade level 3 only tag */ - -#define RFAL_NFCA_SENS_RES_PLATFORM_MASK \ - 0x0FU /*!< SENS_RES (ATQA) platform configuration mask Digital 1.1 Table 10 */ -#define RFAL_NFCA_SENS_RES_PLATFORM_T1T \ - 0x0CU /*!< SENS_RES (ATQA) T1T platform configuration Digital 1.1 Table 10 */ - -#define RFAL_NFCA_SEL_RES_CONF_MASK \ - 0x60U /*!< SEL_RES (SAK) platform configuration mask Digital 1.1 Table 19 */ -#define RFAL_NFCA_SEL_RES_CONF_T2T \ - 0x00U /*!< SEL_RES (SAK) T2T configuration Digital 1.1 Table 19 */ -#define RFAL_NFCA_SEL_RES_CONF_T4T \ - 0x20U /*!< SEL_RES (SAK) T4T configuration Digital 1.1 Table 19 */ -#define RFAL_NFCA_SEL_RES_CONF_NFCDEP \ - 0x40U /*!< SEL_RES (SAK) NFC-DEP configuration Digital 1.1 Table 19 */ -#define RFAL_NFCA_SEL_RES_CONF_T4T_NFCDEP \ - 0x60U /*!< SEL_RES (SAK) T4T and NFC-DEP configuration Digital 1.1 Table 19 */ - -/*! NFC-A minimum FDT(listen) = ((n * 128 + (84)) / fc) with n_min = 9 Digital 1.1 6.10.1 - * = (1236)/fc - * Relax with 3etu: (3*128)/fc as with multiple NFC-A cards, response may take longer (JCOP cards) - * = (1236 + 384)/fc = 1620 / fc */ -#define RFAL_NFCA_FDTMIN 1620U -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ - -/*! Checks if device is a T1T given its SENS_RES */ -#define rfalNfcaIsSensResT1T(sensRes) \ - ((((rfalNfcaSensRes*)(sensRes))->platformInfo & RFAL_NFCA_SENS_RES_PLATFORM_MASK) == \ - RFAL_NFCA_SENS_RES_PLATFORM_T1T) - -/*! Checks if device is a T2T given its SENS_RES */ -#define rfalNfcaIsSelResT2T(selRes) \ - ((((rfalNfcaSelRes*)(selRes))->sak & RFAL_NFCA_SEL_RES_CONF_MASK) == \ - RFAL_NFCA_SEL_RES_CONF_T2T) - -/*! Checks if device is a T4T given its SENS_RES */ -#define rfalNfcaIsSelResT4T(selRes) \ - ((((rfalNfcaSelRes*)(selRes))->sak & RFAL_NFCA_SEL_RES_CONF_MASK) == \ - RFAL_NFCA_SEL_RES_CONF_T4T) - -/*! Checks if device supports NFC-DEP protocol given its SENS_RES */ -#define rfalNfcaIsSelResNFCDEP(selRes) \ - ((((rfalNfcaSelRes*)(selRes))->sak & RFAL_NFCA_SEL_RES_CONF_MASK) == \ - RFAL_NFCA_SEL_RES_CONF_NFCDEP) - -/*! Checks if device supports ISO-DEP and NFC-DEP protocol given its SENS_RES */ -#define rfalNfcaIsSelResT4TNFCDEP(selRes) \ - ((((rfalNfcaSelRes*)(selRes))->sak & RFAL_NFCA_SEL_RES_CONF_MASK) == \ - RFAL_NFCA_SEL_RES_CONF_T4T_NFCDEP) - -/*! Checks if a NFC-A listener device supports multiple protocols (ISO-DEP and NFC-DEP) */ -#define rfalNfcaLisDevIsMultiProto(lisDev) \ - (((rfalNfcaListenDevice*)(lisDev))->type == RFAL_NFCA_T4T_NFCDEP) - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! NFC-A Listen device types */ -typedef enum { - RFAL_NFCA_T1T = - 0x01, /* Device configured for T1T Digital 1.1 Table 9 */ - RFAL_NFCA_T2T = - 0x00, /* Device configured for T2T Digital 1.1 Table 19 */ - RFAL_NFCA_T4T = - 0x20, /* Device configured for T4T Digital 1.1 Table 19 */ - RFAL_NFCA_NFCDEP = - 0x40, /* Device configured for NFC-DEP Digital 1.1 Table 19 */ - RFAL_NFCA_T4T_NFCDEP = - 0x60 /* Device configured for NFC-DEP and T4T Digital 1.1 Table 19 */ -} rfalNfcaListenDeviceType; - -/*! SENS_RES (ATQA) format Digital 1.1 6.6.3 & Table 7 */ -typedef struct { - uint8_t - anticollisionInfo; /*!< SENS_RES Anticollision Information */ - uint8_t - platformInfo; /*!< SENS_RES Platform Information */ -} rfalNfcaSensRes; - -/*! SDD_REQ (Anticollision) format Digital 1.1 6.7.1 & Table 11 */ -typedef struct { - uint8_t - selCmd; /*!< SDD_REQ SEL_CMD: cascade Level */ - uint8_t - selPar; /*!< SDD_REQ SEL_PAR: Byte Count[4b] | Bit Count[4b] (NVB: Number of Valid Bits)*/ -} rfalNfcaSddReq; - -/*! SDD_RES (UID CLn) format Digital 1.1 6.7.2 & Table 15 */ -typedef struct { - uint8_t nfcid1 - [RFAL_NFCA_CASCADE_1_UID_LEN]; /*!< NFCID1 cascade level NFCID */ - uint8_t bcc; /*!< BCC Exclusive-OR over first 4 bytes of SDD_RES */ -} rfalNfcaSddRes; - -/*! SEL_REQ (Select) format Digital 1.1 6.8.1 & Table 17 */ -typedef struct { - uint8_t - selCmd; /*!< SDD_REQ SEL_CMD: cascade Level */ - uint8_t - selPar; /*!< SDD_REQ SEL_PAR: Byte Count[4b] | Bit Count[4b] (NVB: Number of Valid Bits)*/ - uint8_t nfcid1 - [RFAL_NFCA_CASCADE_1_UID_LEN]; /*!< NFCID1 data */ - uint8_t bcc; /*!< Checksum calculated as exclusive-OR over the 4 bytes of NFCID1 CLn */ -} rfalNfcaSelReq; - -/*! SEL_RES (SAK) format Digital 1.1 6.8.2 & Table 19 */ -typedef struct { - uint8_t sak; /*!< Select Acknowledge */ -} rfalNfcaSelRes; - -/*! NFC-A listener device (PICC) struct */ -typedef struct { - rfalNfcaListenDeviceType - type; /*!< NFC-A Listen device type */ - rfalNfcaSensRes - sensRes; /*!< SENS_RES (ATQA) */ - rfalNfcaSelRes - selRes; /*!< SEL_RES (SAK) */ - uint8_t - nfcId1Len; /*!< NFCID1 Length */ - uint8_t nfcId1 - [RFAL_NFCA_CASCADE_3_UID_LEN]; /*!< NFCID1 (UID) */ -#ifdef RFAL_FEATURE_T1T - rfalT1TRidRes - ridRes; /*!< RID_RES */ -#endif /* RFAL_FEATURE_T1T */ - bool isSleep; /*!< Device sleeping flag */ -} rfalNfcaListenDevice; - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Initialize NFC-A Poller mode - * - * This methods configures RFAL RF layer to perform as a - * NFC-A Poller/RW (ISO14443A PCD) including all default timings and bit rate - * to 106 kbps - - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcaPollerInitialize(void); - -/*! - ***************************************************************************** - * \brief NFC-A Poller Check Presence - * - * This method checks if a NFC-A Listen device (PICC) is present on the field - * by sending an ALL_REQ (WUPA) or SENS_REQ (REQA) - * - * \param[in] cmd : Indicate if to send an ALL_REQ or a SENS_REQ - * \param[out] sensRes : If received, the SENS_RES - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_RF_COLLISION : Collision detected one or more device in the field - * \return ERR_PAR : Parity error detected, one or more device in the field - * \return ERR_CRC : CRC error detected, one or more device in the field - * \return ERR_FRAMING : Framing error detected, one or more device in the field - * \return ERR_PROTO : Protocol error detected, one or more device in the field - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_NONE : No error, one or more device in the field - ***************************************************************************** - */ -ReturnCode rfalNfcaPollerCheckPresence(rfal14443AShortFrameCmd cmd, rfalNfcaSensRes* sensRes); - -/*! - ***************************************************************************** - * \brief NFC-A Poller Select - * - * This method selects a NFC-A Listener device (PICC) - * - * \param[in] nfcid1 : Listener device NFCID1 to be selected - * \param[in] nfcidLen : Length of the NFCID1 to be selected - * \param[out] selRes : pointer to place the SEL_RES - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, SEL_RES received - ***************************************************************************** - */ -ReturnCode rfalNfcaPollerSelect(const uint8_t* nfcid1, uint8_t nfcidLen, rfalNfcaSelRes* selRes); - -/*! - ***************************************************************************** - * \brief NFC-A Poller Sleep - * - * This method sends a SLP_REQ (HLTA) - * No response is expected afterwards Digital 1.1 6.9.2.1 - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcaPollerSleep(void); - -/*! - ***************************************************************************** - * \brief NFC-A Technology Detection - * - * This method performs NFC-A Technology Detection as defined in the spec - * given in the compliance mode - * - * \param[in] compMode : compliance mode to be performed - * \param[out] sensRes : location to store the SENS_RES, if received - * - * When compMode is set to ISO compliance a SLP_REQ (HLTA) is not sent - * after detection. When set to EMV a ALL_REQ (WUPA) is sent instead of - * a SENS_REQ (REQA) - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_NONE : No error, one or more device in the field - ***************************************************************************** - */ -ReturnCode - rfalNfcaPollerTechnologyDetection(rfalComplianceMode compMode, rfalNfcaSensRes* sensRes); - -/*! - ***************************************************************************** - * \brief NFC-A Poller Collision Resolution - * - * Collision resolution for one NFC-A Listener device/card (PICC) as - * defined in Activity 2.1 9.3.4 - * - * This method executes anti collision loop and select the device with higher NFCID1 - * - * When devLimit = 0 it is configured to perform collision detection only. Once a collision - * is detected the collision resolution is aborted immediately. If only one device is found - * with no collisions, it will properly resolved. - * - * \param[in] devLimit : device limit value (CON_DEVICES_LIMIT) - * \param[out] collPending : pointer to collision pending flag (INT_COLL_PEND) - * \param[out] selRes : location to store the last Select Response from listener device (PICC) - * \param[out] nfcId1 : location to store the NFCID1 (UID), ensure RFAL_NFCA_CASCADE_3_UID_LEN - * \param[out] nfcId1Len : pointer to length of NFCID1 (UID) - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_PROTO : Card length invalid - * \return ERR_IGNORE : conDevLimit is 0 and there is a collision - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcaPollerSingleCollisionResolution( - uint8_t devLimit, - bool* collPending, - rfalNfcaSelRes* selRes, - uint8_t* nfcId1, - uint8_t* nfcId1Len); - -/*! - ***************************************************************************** - * \brief NFC-A Poller Full Collision Resolution - * - * Performs a full Collision resolution as defined in Activity 2.1 9.3.4 - * - * \param[in] compMode : compliance mode to be performed - * \param[in] devLimit : device limit value, and size nfcaDevList - * \param[out] nfcaDevList : NFC-A listener device info - * \param[out] devCnt : Devices found counter - * - * When compMode is set to ISO compliance it assumes that the device is - * not sleeping and therefore no ALL_REQ (WUPA) is sent at the beginning. - * When compMode is set to NFC compliance an additional ALL_REQ (WUPA) is sent - * at the beginning. - * - * - * When devLimit = 0 it is configured to perform collision detection only. Once a collision - * is detected the collision resolution is aborted immediately. If only one device is found - * with no collisions, it will properly resolved. - * - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcaPollerFullCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcaListenDevice* nfcaDevList, - uint8_t* devCnt); - -/*! - ***************************************************************************** - * \brief NFC-A Poller Full Collision Resolution with Sleep - * - * Performs a full Collision resolution similar to rfalNfcaPollerFullCollisionResolution - * but an additional SLP_REQ (HLTA) -> SENS_RES (REQA) is sent regardless if there - * was a collision. - * This proprietary behaviour ensures proper activation of certain devices that suffer - * from influence of Type B commands as foreseen in ISO14443-3 5.2.3 or were somehow - * not detected by the first round of collision resolution - * - * \param[in] devLimit : device limit value, and size nfcaDevList - * \param[out] nfcaDevList : NFC-A listener device info - * \param[out] devCnt : Devices found counter - * - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcaPollerSleepFullCollisionResolution( - uint8_t devLimit, - rfalNfcaListenDevice* nfcaDevList, - uint8_t* devCnt); - -/*! - ***************************************************************************** - * \brief NFC-A Poller Start Full Collision Resolution - * - * This method starts the full Collision resolution as defined - * in Activity 1.0 or 1.1 9.3.4 - * - * \param[in] compMode : compliance mode to be performed - * \param[in] devLimit : device limit value, and size nfcaDevList - * \param[out] nfcaDevList : NFC-A listener device info - * \param[out] devCnt : Devices found counter - * - * When compMode is set to ISO compliance it assumes that the device is - * not sleeping and therefore no ALL_REQ (WUPA) is sent at the beginning. - * When compMode is set to NFC compliance an additional ALL_REQ (WUPA) is sent at - * the beginning. - * - * - * When devLimit = 0 it is configured to perform collision detection only. Once a collision - * is detected the collision resolution is aborted immediately. If only one device is found - * with no collisions, it will properly resolved. - * - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcaPollerStartFullCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcaListenDevice* nfcaDevList, - uint8_t* devCnt); - -/*! - ***************************************************************************** - * \brief NFC-A Get Full Collision Resolution Status - * - * Returns the Collision Resolution status - * - * \return ERR_BUSY : Operation is ongoing - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, activation successful - ***************************************************************************** - */ -ReturnCode rfalNfcaPollerGetFullCollisionResolutionStatus(void); - -/*! - ***************************************************************************** - * \brief NFC-A Listener is SLP_REQ - * - * Checks if the given buffer contains valid NFC-A SLP_REQ (HALT) - * - * \param[in] buf: buffer containing data - * \param[in] bufLen: length of the data in buffer to be checked - * - * \return true if data in buf contains a SLP_REQ ; false otherwise - ***************************************************************************** - */ -bool rfalNfcaListenerIsSleepReq(const uint8_t* buf, uint16_t bufLen); - -#endif /* RFAL_NFCA_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_nfcb.h b/lib/ST25RFAL002/include/rfal_nfcb.h deleted file mode 100644 index 67bcb3271..000000000 --- a/lib/ST25RFAL002/include/rfal_nfcb.h +++ /dev/null @@ -1,425 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfcb.h - * - * \author Gustavo Patricio - * - * \brief Implementation of NFC-B (ISO14443B) helpers - * - * It provides a NFC-B Poller (ISO14443B PCD) interface and - * also provides some NFC-B Listener (ISO14443B PICC) helpers - * - * The definitions and helpers methods provided by this module are only - * up to ISO14443-3 layer (excluding ATTRIB) - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup NFC-B - * \brief RFAL NFC-B Module - * @{ - * - */ - -#ifndef RFAL_NFCB_H -#define RFAL_NFCB_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_NFCB_FWTSENSB 7680U /*!< NFC-B FWT(SENSB) Digital 2.0 B.3 */ -#define RFAL_NFCB_DFWT 49152U /*!< NFC-B dFWT Delta 2.0 7.9.1.3 & B.3 */ -#define RFAL_NFCB_DTPOLL_10 rfalConvMsTo1fc(20) /*!< NFC-B Delta Tb Poll Digital 1.0 A.2 */ -#define RFAL_NFCB_DTPOLL_20 rfalConvMsTo1fc(17) /*!< NFC-B Delta Tb Poll Digital 2.1 B.3 */ - -#define RFAL_NFCB_AFI 0x00U /*!< NFC-B default Application Family Digital 1.1 7.6.1.1 */ -#define RFAL_NFCB_PARAM 0x00U /*!< NFC-B default SENSB_REQ PARAM */ -#define RFAL_NFCB_CRC_LEN 2U /*!< NFC-B CRC length and CRC_B(AID) Digital 1.1 Table 28 */ -#define RFAL_NFCB_NFCID0_LEN 4U /*!< Length of NFC-B NFCID0 */ -#define RFAL_NFCB_CMD_LEN 1U /*!< Length of NFC-B Command */ - -#define RFAL_NFCB_SENSB_RES_LEN 12U /*!< Standard length of SENSB_RES without SFGI byte */ -#define RFAL_NFCB_SENSB_RES_EXT_LEN \ - 13U /*!< Extended length of SENSB_RES with SFGI byte */ - -#define RFAL_NFCB_SENSB_REQ_ADV_FEATURE \ - 0x20U /*!< Bit mask for Advance Feature in SENSB_REQ */ -#define RFAL_NFCB_SENSB_RES_FSCI_MASK \ - 0x0FU /*!< Bit mask for FSCI value in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_FSCI_SHIFT \ - 4U /*!< Shift for FSCI value in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_PROTO_RFU_MASK \ - 0x08U /*!< Bit mask for Protocol Type RFU in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_PROTO_TR2_MASK \ - 0x03U /*!< Bit mask for Protocol Type TR2 in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_PROTO_TR2_SHIFT \ - 1U /*!< Shift for Protocol Type TR2 in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_PROTO_ISO_MASK \ - 0x01U /*!< Bit mask Protocol Type ISO14443 Compliant in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_FWI_MASK \ - 0x0FU /*!< Bit mask for FWI value in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_FWI_SHIFT \ - 4U /*!< Bit mask for FWI value in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_ADC_MASK \ - 0x0CU /*!< Bit mask for ADC value in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_ADC_ADV_FEATURE_MASK \ - 0x08U /*!< Bit mask for ADC.Advanced Proto Features in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_ADC_PROPRIETARY_MASK \ - 0x04U /*!< Bit mask for ADC.Proprietary Application in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_FO_DID_MASK \ - 0x01U /*!< Bit mask for DID in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_FO_NAD_MASK \ - 0x02U /*!< Bit mask for DID in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_FO_MASK \ - 0x03U /*!< Bit mask for FO value in SENSB_RES (NAD and DID) */ -#define RFAL_NFCB_SENSB_RES_SFGI_MASK \ - 0x0FU /*!< Bit mask for SFGI in SENSB_RES */ -#define RFAL_NFCB_SENSB_RES_SFGI_SHIFT \ - 4U /*!< Shift for SFGI in SENSB_RES */ - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ - -/*! Get device's FSCI given its SENSB_RES Digital 1.1 7.6.2 */ -#define rfalNfcbGetFSCI(sensbRes) \ - ((((rfalNfcbSensbRes*)(sensbRes))->protInfo.FsciProType >> RFAL_NFCB_SENSB_RES_FSCI_SHIFT) & \ - RFAL_NFCB_SENSB_RES_FSCI_MASK) - -/*! Checks if the given NFC-B device indicates ISO-DEP support */ -#define rfalNfcbIsIsoDepSupported(dev) \ - ((((rfalNfcbListenDevice*)(dev))->sensbRes.protInfo.FsciProType & \ - RFAL_NFCB_SENSB_RES_PROTO_ISO_MASK) != 0U) - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! SENSB_REQ and ALLB_REQ param Digital 1.1 7.6.1 */ -typedef enum { - RFAL_NFCB_SENS_CMD_ALLB_REQ = 0x08, /*!< ALLB_REQ (WUPB) */ - RFAL_NFCB_SENS_CMD_SENSB_REQ = 0x00 /*!< SENSB_REQ (REQB) */ -} rfalNfcbSensCmd; - -/*! Number of Slots (NI) codes used for NFC-B anti collision Digital 1.1 Table 26 */ -typedef enum { - RFAL_NFCB_SLOT_NUM_1 = 0, /*!< N=0 : 1 slot */ - RFAL_NFCB_SLOT_NUM_2 = 1, /*!< N=1 : 2 slots */ - RFAL_NFCB_SLOT_NUM_4 = 2, /*!< N=2 : 4 slots */ - RFAL_NFCB_SLOT_NUM_8 = 3, /*!< N=3 : 8 slots */ - RFAL_NFCB_SLOT_NUM_16 = 4 /*!< N=4 : 16 slots */ -} rfalNfcbSlots; - -/*! SENSB_RES (ATQB) Application Data Format Digital 1.1 Table 28 */ -typedef struct { - uint8_t AFI; /*!< Application Family Identifier */ - uint8_t CRC_B[RFAL_NFCB_CRC_LEN]; /*!< CRC_B of AID */ - uint8_t numApps; /*!< Number of Applications */ -} rfalNfcbSensbResAppData; - -/*! SENSB_RES Protocol Info format Digital 1.1 Table 29 */ -typedef struct { - uint8_t - BRC; /*!< Bit Rate Capability */ - uint8_t - FsciProType; /*!< Frame Size Card Integer [4b] | Protocol Type[4 bits] */ - uint8_t - FwiAdcFo; /*!< Frame Waiting Integer [4b] | Application Data Coding [2b] | Frame Options [2b] */ - uint8_t - SFGI; /*!< Optional: Start-Up Frame Guard Time Integer[4b] | RFU [4b] */ -} rfalNfcbSensbResProtocolInfo; - -/*! SENSB_RES format Digital 1.1 7.6.2 */ -typedef struct { - uint8_t cmd; /*!< SENSB_RES: 50h */ - uint8_t nfcid0[RFAL_NFCB_NFCID0_LEN]; /*!< NFC Identifier (PUPI)*/ - rfalNfcbSensbResAppData appData; /*!< Application Data */ - rfalNfcbSensbResProtocolInfo protInfo; /*!< Protocol Information */ -} rfalNfcbSensbRes; - -/*! NFC-B listener device (PICC) struct */ -typedef struct { - uint8_t sensbResLen; /*!< SENSB_RES length */ - rfalNfcbSensbRes sensbRes; /*!< SENSB_RES */ - bool isSleep; /*!< Device sleeping flag */ -} rfalNfcbListenDevice; - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Initialize NFC-B Poller mode - * - * This methods configures RFAL RF layer to perform as a - * NFC-B Poller/RW (ISO14443B PCD) including all default timings - * - * It sets NFC-B parameters (AFI, PARAM) to default values - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcbPollerInitialize(void); - -/*! - ***************************************************************************** - * \brief Set NFC-B Poller parameters - * - * This methods configures RFAL RF layer to perform as a - * NFCA Poller/RW (ISO14443A PCD) including all default timings - * - * Additionally configures NFC-B specific parameters to be used on the - * following communications - * - * \param[in] AFI : Application Family Identifier to be used - * \param[in] PARAM : PARAM to be used, it announces whether Advanced - * Features or Extended SENSB_RES is supported - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcbPollerInitializeWithParams(uint8_t AFI, uint8_t PARAM); - -/*! - ***************************************************************************** - * \brief NFC-B Poller Check Presence - * - * This method checks if a NFC-B Listen device (PICC) is present on the field - * by sending an ALLB_REQ (WUPB) or SENSB_REQ (REQB) - * - * \param[in] cmd : Indicate if to send an ALL_REQ or a SENS_REQ - * \param[in] slots : The number of slots to be announced - * \param[out] sensbRes : If received, the SENSB_RES - * \param[out] sensbResLen : If received, the SENSB_RES length - * - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_RF_COLLISION : Collision detected one or more device in the field - * \return ERR_PAR : Parity error detected, one or more device in the field - * \return ERR_CRC : CRC error detected, one or more device in the field - * \return ERR_FRAMING : Framing error detected, one or more device in the field - * \return ERR_PROTO : Protocol error detected, invalid SENSB_RES received - * \return ERR_NONE : No error, SENSB_RES received - ***************************************************************************** - */ -ReturnCode rfalNfcbPollerCheckPresence( - rfalNfcbSensCmd cmd, - rfalNfcbSlots slots, - rfalNfcbSensbRes* sensbRes, - uint8_t* sensbResLen); - -/*! - ***************************************************************************** - * \brief NFC-B Poller Sleep - * - * This function is used to send the SLPB_REQ (HLTB) command to put the PICC with - * the given NFCID0 to state HALT so that they do not reply to further SENSB_REQ - * commands (only to ALLB_REQ) - * - * \param[in] nfcid0 : NFCID of the device to be put to Sleep - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcbPollerSleep(const uint8_t* nfcid0); - -/*! - ***************************************************************************** - * \brief NFC-B Poller Slot Marker - * - * This method selects a NFC-B Slot marker frame - * - * \param[in] slotCode : Slot Code [1-15] - * \param[out] sensbRes : If received, the SENSB_RES - * \param[out] sensbResLen : If received, the SENSB_RES length - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error, SEL_RES received - ***************************************************************************** - */ -ReturnCode - rfalNfcbPollerSlotMarker(uint8_t slotCode, rfalNfcbSensbRes* sensbRes, uint8_t* sensbResLen); - -/*! - ***************************************************************************** - * \brief NFC-B Technology Detection - * - * This method performs NFC-B Technology Detection as defined in the spec - * given in the compliance mode - * - * \param[in] compMode : compliance mode to be performed - * \param[out] sensbRes : location to store the SENSB_RES, if received - * \param[out] sensbResLen : length of the SENSB_RES, if received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_NONE : No error, one or more device in the field - ***************************************************************************** - */ -ReturnCode rfalNfcbPollerTechnologyDetection( - rfalComplianceMode compMode, - rfalNfcbSensbRes* sensbRes, - uint8_t* sensbResLen); - -/*! - ***************************************************************************** - * \brief NFC-B Poller Collision Resolution - * - * NFC-B Collision resolution Listener device/card (PICC) as - * defined in Activity 1.1 9.3.5 - * - * This function is used to perform collision resolution for detection in case - * of multiple NFC Forum Devices with Technology B detected. - * Target with valid SENSB_RES will be stored in devInfo and nfcbDevCount incremented. - * - * \param[in] compMode : compliance mode to be performed - * \param[in] devLimit : device limit value, and size nfcbDevList - * \param[out] nfcbDevList : NFC-B listener device info - * \param[out] devCnt : devices found counter - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcbPollerCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcbListenDevice* nfcbDevList, - uint8_t* devCnt); - -/*! - ***************************************************************************** - * \brief NFC-B Poller Collision Resolution Slotted - * - * NFC-B Collision resolution Listener device/card (PICC). The sequence can - * be configured to be according to NFC Forum Activity 1.1 9.3.5, ISO10373 - * or EMVCo - * - * This function is used to perform collision resolution for detection in case - * of multiple NFC Forum Devices with Technology B are detected. - * Target with valid SENSB_RES will be stored in devInfo and nfcbDevCount incremented. - * - * This method provides the means to perform a collision resolution loop with specific - * initial and end number of slots. This allows to user to start the loop already with - * greater number of slots, and or limit the end number of slots. At the end a flag - * indicating whether there were collisions pending is returned. - * - * If RFAL_COMPLIANCE_MODE_ISO is used \a initSlots must be set to RFAL_NFCB_SLOT_NUM_1 - * - * - * \param[in] compMode : compliance mode to be performed - * \param[in] devLimit : device limit value, and size nfcbDevList - * \param[in] initSlots : number of slots to open initially - * \param[in] endSlots : number of slots when to stop collision resolution - * \param[out] nfcbDevList : NFC-B listener device info - * \param[out] devCnt : devices found counter - * \param[out] colPending : flag indicating whether collision are still pending - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcbPollerSlottedCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcbSlots initSlots, - rfalNfcbSlots endSlots, - rfalNfcbListenDevice* nfcbDevList, - uint8_t* devCnt, - bool* colPending); - -/*! - ***************************************************************************** - * \brief NFC-B TR2 code to FDT - * - * Converts the TR2 code as defined in Digital 1.1 Table 33 Minimum - * TR2 Coding to Frame Delay Time (FDT) in 1/Fc - * - * \param[in] tr2Code : TR2 code as defined in Digital 1.1 Table 33 - * - * \return FDT in 1/Fc - ***************************************************************************** - */ -uint32_t rfalNfcbTR2ToFDT(uint8_t tr2Code); - -#endif /* RFAL_NFCB_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_nfcf.h b/lib/ST25RFAL002/include/rfal_nfcf.h deleted file mode 100644 index 30c34765d..000000000 --- a/lib/ST25RFAL002/include/rfal_nfcf.h +++ /dev/null @@ -1,403 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfcf.h - * - * \author Gustavo Patricio - * - * \brief Implementation of NFC-F Poller (FeliCa PCD) device - * - * The definitions and helpers methods provided by this module are - * aligned with NFC-F (FeliCa - JIS X6319-4) - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup NFC-F - * \brief RFAL NFC-F Module - * @{ - * - */ - -#ifndef RFAL_NFCF_H -#define RFAL_NFCF_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_NFCF_NFCID2_LEN 8U /*!< NFCID2 (FeliCa IDm) length */ -#define RFAL_NFCF_SENSF_RES_LEN_MIN 16U /*!< SENSF_RES minimum length */ -#define RFAL_NFCF_SENSF_RES_LEN_MAX 18U /*!< SENSF_RES maximum length */ -#define RFAL_NFCF_SENSF_RES_PAD0_LEN 2U /*!< SENSF_RES PAD0 length */ -#define RFAL_NFCF_SENSF_RES_PAD1_LEN 2U /*!< SENSF_RES PAD1 length */ -#define RFAL_NFCF_SENSF_RES_RD_LEN 2U /*!< SENSF_RES Request Data length */ -#define RFAL_NFCF_SENSF_RES_BYTE1 1U /*!< SENSF_RES first byte value */ -#define RFAL_NFCF_SENSF_SC_LEN 2U /*!< Felica SENSF_REQ System Code length */ -#define RFAL_NFCF_SENSF_PARAMS_SC1_POS 0U /*!< System Code byte1 position in the SENSF_REQ */ -#define RFAL_NFCF_SENSF_PARAMS_SC2_POS 1U /*!< System Code byte2 position in the SENSF_REQ */ -#define RFAL_NFCF_SENSF_PARAMS_RC_POS 2U /*!< Request Code position in the SENSF_REQ */ -#define RFAL_NFCF_SENSF_PARAMS_TSN_POS 3U /*!< Time Slot Number position in the SENSF_REQ */ -#define RFAL_NFCF_POLL_MAXCARDS 16U /*!< Max number slots/cards 16 */ - -#define RFAL_NFCF_CMD_POS 0U /*!< Command/Response code length */ -#define RFAL_NFCF_CMD_LEN 1U /*!< Command/Response code length */ -#define RFAL_NFCF_LENGTH_LEN 1U /*!< LEN field length */ -#define RFAL_NFCF_HEADER_LEN (RFAL_NFCF_LENGTH_LEN + RFAL_NFCF_CMD_LEN) /*!< Header length*/ - -#define RFAL_NFCF_SENSF_NFCID2_BYTE1_POS \ - 0U /*!< NFCID2 byte1 position */ -#define RFAL_NFCF_SENSF_NFCID2_BYTE2_POS \ - 1U /*!< NFCID2 byte2 position */ - -#define RFAL_NFCF_SENSF_NFCID2_PROT_TYPE_LEN \ - 2U /*!< NFCID2 length for byte 1 and byte 2 indicating NFC-DEP or T3T support */ -#define RFAL_NFCF_SENSF_NFCID2_BYTE1_NFCDEP \ - 0x01U /*!< NFCID2 byte1 NFC-DEP support Digital 1.0 Table 44 */ -#define RFAL_NFCF_SENSF_NFCID2_BYTE2_NFCDEP \ - 0xFEU /*!< NFCID2 byte2 NFC-DEP support Digital 1.0 Table 44 */ - -#define RFAL_NFCF_SYSTEMCODE \ - 0xFFFFU /*!< SENSF_RES Default System Code Digital 1.0 6.6.1.1 */ - -#define RFAL_NFCF_BLOCK_LEN \ - 16U /*!< NFCF T3T Block size T3T 1.0 4.1 */ -#define RFAL_NFCF_CHECKUPDATE_RES_ST1_POS \ - 9U /*!< Check|Update Res Status Flag 1 position T3T 1.0 Table 8 */ -#define RFAL_NFCF_CHECKUPDATE_RES_ST2_POS \ - 10U /*!< Check|Update Res Status Flag 2 position T3T 1.0 Table 8 */ -#define RFAL_NFCF_CHECKUPDATE_RES_NOB_POS \ - 11U /*!< Check|Update Res Number of Blocks position T3T 1.0 Table 8 */ - -#define RFAL_NFCF_STATUS_FLAG_SUCCESS \ - 0x00U /*!< Check response Number of Blocks position T3T 1.0 Table 11 */ -#define RFAL_NFCF_STATUS_FLAG_ERROR \ - 0xFFU /*!< Check response Number of Blocks position T3T 1.0 Table 11 */ - -#define RFAL_NFCF_BLOCKLISTELEM_LEN \ - 0x80U /*!< Block List Element Length bit (2|3 bytes) T3T 1.0 5.6.1 */ - -#define RFAL_NFCF_SERVICECODE_RDONLY \ - 0x000BU /*!< NDEF Service Code as Read-Only T3T 1.0 7.2.1 */ -#define RFAL_NFCF_SERVICECODE_RDWR \ - 0x0009U /*!< NDEF Service Code as Read and Write T3T 1.0 7.2.1 */ - -/*! NFC-F Felica command set JIS X6319-4 9.1 */ -enum { - RFAL_NFCF_CMD_POLLING = - 0x00, /*!< SENSF_REQ (Felica Poll/REQC command to identify a card ) */ - RFAL_NFCF_CMD_POLLING_RES = - 0x01, /*!< SENSF_RES (Felica Poll/REQC command response ) */ - RFAL_NFCF_CMD_REQUEST_SERVICE = - 0x02, /*!< verify the existence of Area and Service */ - RFAL_NFCF_CMD_REQUEST_RESPONSE = - 0x04, /*!< verify the existence of a card */ - RFAL_NFCF_CMD_READ_WITHOUT_ENCRYPTION = - 0x06, /*!< read Block Data from a Service that requires no authentication */ - RFAL_NFCF_CMD_READ_WITHOUT_ENCRYPTION_RES = - 0x07, /*!< read Block Data response from a Service with no authentication */ - RFAL_NFCF_CMD_WRITE_WITHOUT_ENCRYPTION = - 0x08, /*!< write Block Data to a Service that requires no authentication */ - RFAL_NFCF_CMD_WRITE_WITHOUT_ENCRYPTION_RES = - 0x09, /*!< write Block Data response to a Service with no authentication */ - RFAL_NFCF_CMD_REQUEST_SYSTEM_CODE = - 0x0c, /*!< acquire the System Code registered to a card */ - RFAL_NFCF_CMD_AUTHENTICATION1 = - 0x10, /*!< authenticate a card */ - RFAL_NFCF_CMD_AUTHENTICATION2 = - 0x12, /*!< allow a card to authenticate a Reader/Writer */ - RFAL_NFCF_CMD_READ = - 0x14, /*!< read Block Data from a Service that requires authentication */ - RFAL_NFCF_CMD_WRITE = - 0x16, /*!< write Block Data to a Service that requires authentication */ -}; - -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ - -/*! Checks if the given NFC-F device indicates NFC-DEP support */ -#define rfalNfcfIsNfcDepSupported(dev) \ - ((((rfalNfcfListenDevice*)(dev))->sensfRes.NFCID2[RFAL_NFCF_SENSF_NFCID2_BYTE1_POS] == \ - RFAL_NFCF_SENSF_NFCID2_BYTE1_NFCDEP) && \ - (((rfalNfcfListenDevice*)(dev))->sensfRes.NFCID2[RFAL_NFCF_SENSF_NFCID2_BYTE2_POS] == \ - RFAL_NFCF_SENSF_NFCID2_BYTE2_NFCDEP)) - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! NFC-F SENSF_RES format Digital 1.1 8.6.2 */ -typedef struct { - uint8_t CMD; /*!< Command Code: 01h */ - uint8_t NFCID2[RFAL_NFCF_NFCID2_LEN]; /*!< NFCID2 */ - uint8_t PAD0[RFAL_NFCF_SENSF_RES_PAD0_LEN]; /*!< PAD0 */ - uint8_t PAD1[RFAL_NFCF_SENSF_RES_PAD1_LEN]; /*!< PAD1 */ - uint8_t MRTIcheck; /*!< MRTIcheck */ - uint8_t MRTIupdate; /*!< MRTIupdate */ - uint8_t PAD2; /*!< PAD2 */ - uint8_t RD[RFAL_NFCF_SENSF_RES_RD_LEN]; /*!< Request Data */ -} rfalNfcfSensfRes; - -/*! NFC-F poller device (PCD) struct */ -typedef struct { - uint8_t NFCID2[RFAL_NFCF_NFCID2_LEN]; /*!< NFCID2 */ -} rfalNfcfPollDevice; - -/*! NFC-F listener device (PICC) struct */ -typedef struct { - uint8_t sensfResLen; /*!< SENF_RES length */ - rfalNfcfSensfRes sensfRes; /*!< SENF_RES */ -} rfalNfcfListenDevice; - -typedef uint16_t rfalNfcfServ; /*!< NFC-F Service Code */ - -/*! NFC-F Block List Element (2 or 3 bytes element) T3T 1.0 5.6.1 */ -typedef struct { - uint8_t conf; /*!< Access Mode | Serv Code List Order */ - uint16_t blockNum; /*!< Block Number */ -} rfalNfcfBlockListElem; - -/*! Check Update Service list and Block list parameter */ -typedef struct { - uint8_t numServ; /*!< Number of Services */ - rfalNfcfServ* servList; /*!< Service Code List */ - uint8_t numBlock; /*!< Number of Blocks */ - rfalNfcfBlockListElem* blockList; /*!< Block Number List */ -} rfalNfcfServBlockListParam; - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Initialize NFC-F Poller mode - * - * This methods configures RFAL RF layer to perform as a - * NFC-F Poller/RW (FeliCa PCD) including all default timings - * - * \param[in] bitRate : NFC-F bitrate to be initialize (212 or 424) - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Incorrect bitrate - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcfPollerInitialize(rfalBitRate bitRate); - -/*! - ***************************************************************************** - * \brief NFC-F Poller Check Presence - * - * This function sends a Poll/SENSF command according to NFC Activity spec - * It detects if a NCF-F device is within range - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_NONE : No error and some NFC-F device was detected - * - ***************************************************************************** - */ -ReturnCode rfalNfcfPollerCheckPresence(void); - -/*! - ***************************************************************************** - * \brief NFC-F Poller Poll - * - * This function sends to all PICCs in field the POLL command with the given - * number of slots. - * - * \param[in] slots : the number of slots to be performed - * \param[in] sysCode : as given in FeliCa poll command - * \param[in] reqCode : FeliCa communication parameters - * \param[out] cardList : Parameter of type rfalFeliCaPollRes which will hold the cards found - * \param[out] devCnt : actual number of cards found - * \param[out] collisions : number of collisions encountered - * - * \warning the list cardList has to be as big as the number of slots for the Poll - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_NONE : No error and some NFC-F device was detected - * - ***************************************************************************** - */ -ReturnCode rfalNfcfPollerPoll( - rfalFeliCaPollSlots slots, - uint16_t sysCode, - uint8_t reqCode, - rfalFeliCaPollRes* cardList, - uint8_t* devCnt, - uint8_t* collisions); - -/*! - ***************************************************************************** - * \brief NFC-F Poller Full Collision Resolution - * - * Performs a full Collision resolution as defined in Activity 1.1 9.3.4 - * - * \param[in] compMode : compliance mode to be performed - * \param[in] devLimit : device limit value, and size nfcaDevList - * \param[out] nfcfDevList : NFC-F listener devices list - * \param[out] devCnt : Devices found counter - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcfPollerCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcfListenDevice* nfcfDevList, - uint8_t* devCnt); - -/*! - ***************************************************************************** - * \brief NFC-F Poller Check/Read - * - * It computes a Check / Read command according to T3T 1.0 and JIS X6319-4 and - * sends it to PICC. If successfully, the rxBuf will contain the the number of - * blocks in the first byte followed by the blocks data. - * - * \param[in] nfcid2 : nfcid2 of the device - * \param[in] servBlock : parameter containing the list of Services and - * Blocks to be addressed by this command - * \param[out] rxBuf : buffer to place check/read data - * \param[in] rxBufLen : size of the rxBuf - * \param[out] rcvdLen : length of data placed in rxBuf - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_REQUEST : The request was executed with error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcfPollerCheck( - const uint8_t* nfcid2, - const rfalNfcfServBlockListParam* servBlock, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvdLen); - -/*! - ***************************************************************************** - * \brief NFC-F Poller Update/Write - * - * It computes a Update / Write command according to T3T 1.0 and JIS X6319-4 and - * sends it to PICC. - * - * \param[in] nfcid2 : nfcid2 of the device - * \param[in] servBlock : parameter containing the list of Services and - * Blocks to be addressed by this command - * \param[in] txBuf : buffer where the request will be composed - * \param[in] txBufLen : size of txBuf - * \param[in] blockData : data to written on the given block(s) - * \param[out] rxBuf : buffer to place check/read data - * \param[in] rxBufLen : size of the rxBuf - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_REQUEST : The request was executed with error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalNfcfPollerUpdate( - const uint8_t* nfcid2, - const rfalNfcfServBlockListParam* servBlock, - uint8_t* txBuf, - uint16_t txBufLen, - const uint8_t* blockData, - uint8_t* rxBuf, - uint16_t rxBufLen); - -/*! - ***************************************************************************** - * \brief NFC-F Listener is T3T Request - * - * This method checks if the given data is a valid T3T command (Read or Write) - * and in case a valid request has been received it may output the request's NFCID2 - * - * \param[in] buf : buffer holding Initiator's received command - * \param[in] bufLen : length of received command in bytes - * \param[out] nfcid2 : pointer to where the NFCID2 may be outputted, - * nfcid2 has NFCF_SENSF_NFCID2_LEN as length - * Pass NULL if output parameter not desired - * - * \return true : Valid T3T command (Read or Write) received - * \return false : Invalid protocol request - * - ***************************************************************************** - */ -bool rfalNfcfListenerIsT3TReq(const uint8_t* buf, uint16_t bufLen, uint8_t* nfcid2); - -#endif /* RFAL_NFCF_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_nfcv.h b/lib/ST25RFAL002/include/rfal_nfcv.h deleted file mode 100644 index b5e1c00ae..000000000 --- a/lib/ST25RFAL002/include/rfal_nfcv.h +++ /dev/null @@ -1,923 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfcv.h - * - * \author Gustavo Patricio - * - * \brief Implementation of NFC-V Poller (ISO15693) device - * - * The definitions and helpers methods provided by this module - * are aligned with NFC-V Digital 2.1 - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup NFC-V - * \brief RFAL NFC-V Module - * @{ - * - */ - -#ifndef RFAL_NFCV_H -#define RFAL_NFCV_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_NFCV_UID_LEN 8U /*!< NFC-V UID length */ -#define RFAL_NFCV_MAX_BLOCK_LEN \ - 32U /*!< Max Block size: can be of up to 256 bits ISO 15693 2000 5 */ -#define RFAL_NFCV_BNO_LEN 1U /*!< NFC-V Block Number length */ -#define RFAL_NFCV_CRC_LEN 2U /*!< NFC-V CRC length */ -#define RFAL_NFCV_MAX_GEN_DATA_LEN \ - (RFAL_NFCV_MAX_BLOCK_LEN + RFAL_NFCV_BNO_LEN + RFAL_NFCV_UID_LEN) /*!
© COPYRIGHT 2020 STMicroelectronics
- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_rf.h - * - * \author Gustavo Patricio - * - * \brief RF Abstraction Layer (RFAL) - * - * RFAL (RF Abstraction Layer) provides several functionalities required to - * perform RF/NFC communications.
The RFAL encapsulates the different - * RF ICs (ST25R3911, ST25R391x, etc) into a common and easy to use interface. - * - * It provides interfaces to configure the RF IC, set/get timings, modes, bit rates, - * specific handlings, execute listen mode, etc. - * - * Furthermore it provides a common interface to perform a Transceive operations. - * The Transceive can be executed in a blocking or non blocking way.
- * Additionally few specific Transceive methods are available to cope with the - * specifics of these particular operations. - * - * The most common interfaces are: - *
  rfalInitialize() - *
  rfalSetFDTPoll() - *
  rfalSetFDTListen() - *
  rfalSetGT() - *
  rfalSetBitRate() - *
  rfalSetMode() - *
  rfalFieldOnAndStartGT() - *
  rfalFieldOff() - *
  rfalStartTransceive() - *
  rfalGetTransceiveStatus() - *
  rfalTransceiveBlockingTxRx() - * - * An usage example is provided here: \ref exampleRfalPoller.c - * \example exampleRfalPoller.c - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-HAL - * \brief RFAL Hardware Abstraction Layer - * @{ - * - * \addtogroup RF - * \brief RFAL RF Abstraction Layer - * @{ - * - */ - -#ifndef RFAL_RF_H -#define RFAL_RF_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "platform.h" -#include "st_errno.h" -#include "rfal_features.h" - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ -#define RFAL_VERSION 0x020200U /*!< RFAL Current Version: v2.2.0 */ - -#define RFAL_FWT_NONE 0xFFFFFFFFU /*!< Disabled FWT: Wait forever for a response */ -#define RFAL_GT_NONE RFAL_TIMING_NONE /*!< Disabled GT: No GT will be applied after Field On */ - -#define RFAL_TIMING_NONE 0x00U /*!< Timing disabled | Don't apply */ - -#define RFAL_1FC_IN_4096FC \ - (uint32_t)4096U /*!< Number of 1/fc cycles in one 4096/fc */ -#define RFAL_1FC_IN_512FC (uint32_t)512U /*!< Number of 1/fc cycles in one 512/fc */ -#define RFAL_1FC_IN_64FC (uint32_t)64U /*!< Number of 1/fc cycles in one 64/fc */ -#define RFAL_1FC_IN_8FC (uint32_t)8U /*!< Number of 1/fc cycles in one 8/fc */ -#define RFAL_US_IN_MS (uint32_t)1000U /*!< Number of us in one ms */ -#define RFAL_1MS_IN_1FC (uint32_t)13560U /*!< Number of 1/fc cycles in 1ms */ -#define RFAL_BITS_IN_BYTE (uint16_t)8U /*!< Number of bits in one byte */ - -#define RFAL_CRC_LEN 2U /*!< RF CRC LEN */ - -/*! Default TxRx flags: Tx CRC automatic, Rx CRC removed, NFCIP1 mode off, AGC On, Tx Parity automatic, Rx Parity removed */ -#define RFAL_TXRX_FLAGS_DEFAULT \ - ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_AUTO | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_REMV | \ - (uint32_t)RFAL_TXRX_FLAGS_NFCIP1_OFF | (uint32_t)RFAL_TXRX_FLAGS_AGC_ON | \ - (uint32_t)RFAL_TXRX_FLAGS_PAR_RX_REMV | (uint32_t)RFAL_TXRX_FLAGS_PAR_TX_AUTO | \ - (uint32_t)RFAL_TXRX_FLAGS_NFCV_FLAG_AUTO) -#define RFAL_TXRX_FLAGS_RAW \ - ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP | \ - (uint32_t)RFAL_TXRX_FLAGS_NFCIP1_OFF | (uint32_t)RFAL_TXRX_FLAGS_AGC_ON | \ - (uint32_t)RFAL_TXRX_FLAGS_PAR_RX_KEEP | (uint32_t)RFAL_TXRX_FLAGS_PAR_TX_NONE | \ - (uint32_t)RFAL_TXRX_FLAGS_NFCV_FLAG_AUTO) - -#define RFAL_LM_MASK_NFCA \ - ((uint32_t)1U \ - << (uint8_t)RFAL_MODE_LISTEN_NFCA) /*!< Bitmask for Listen Mode enabling NFCA */ -#define RFAL_LM_MASK_NFCB \ - ((uint32_t)1U \ - << (uint8_t)RFAL_MODE_LISTEN_NFCB) /*!< Bitmask for Listen Mode enabling NFCB */ -#define RFAL_LM_MASK_NFCF \ - ((uint32_t)1U \ - << (uint8_t)RFAL_MODE_LISTEN_NFCF) /*!< Bitmask for Listen Mode enabling NFCF */ -#define RFAL_LM_MASK_ACTIVE_P2P \ - ((uint32_t)1U \ - << (uint8_t)RFAL_MODE_LISTEN_ACTIVE_P2P) /*!< Bitmask for Listen Mode enabling AP2P */ - -#define RFAL_LM_SENS_RES_LEN 2U /*!< NFC-A SENS_RES (ATQA) length */ -#define RFAL_LM_SENSB_RES_LEN 13U /*!< NFC-B SENSB_RES (ATQB) length */ -#define RFAL_LM_SENSF_RES_LEN 19U /*!< NFC-F SENSF_RES length */ -#define RFAL_LM_SENSF_SC_LEN 2U /*!< NFC-F System Code length */ - -#define RFAL_NFCID3_LEN 10U /*!< NFCID3 length */ -#define RFAL_NFCID2_LEN 8U /*!< NFCID2 length */ -#define RFAL_NFCID1_TRIPLE_LEN 10U /*!< NFCID1 length */ -#define RFAL_NFCID1_DOUBLE_LEN 7U /*!< NFCID1 length */ -#define RFAL_NFCID1_SINGLE_LEN 4U /*!< NFCID1 length */ - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ - -/*! Returns the maximum supported bit rate for RW mode. Caller must check if mode is supported before, as even if mode is not supported will return the min */ -#define rfalGetMaxBrRW() \ - (((RFAL_SUPPORT_BR_RW_6780) ? \ - RFAL_BR_6780 : \ - ((RFAL_SUPPORT_BR_RW_3390) ? \ - RFAL_BR_3390 : \ - ((RFAL_SUPPORT_BR_RW_1695) ? \ - RFAL_BR_1695 : \ - ((RFAL_SUPPORT_BR_RW_848) ? \ - RFAL_BR_848 : \ - ((RFAL_SUPPORT_BR_RW_424) ? \ - RFAL_BR_424 : \ - ((RFAL_SUPPORT_BR_RW_212) ? RFAL_BR_212 : RFAL_BR_106))))))) - -/*! Returns the maximum supported bit rate for AP2P mode. Caller must check if mode is supported before, as even if mode is not supported will return the min */ -#define rfalGetMaxBrAP2P() \ - (((RFAL_SUPPORT_BR_AP2P_848) ? \ - RFAL_BR_848 : \ - ((RFAL_SUPPORT_BR_AP2P_424) ? \ - RFAL_BR_424 : \ - ((RFAL_SUPPORT_BR_AP2P_212) ? RFAL_BR_212 : RFAL_BR_106)))) - -/*! Returns the maximum supported bit rate for CE-A mode. Caller must check if mode is supported before, as even if mode is not supported will return the min */ -#define rfalGetMaxBrCEA() \ - (((RFAL_SUPPORT_BR_CE_A_848) ? \ - RFAL_BR_848 : \ - ((RFAL_SUPPORT_BR_CE_A_424) ? \ - RFAL_BR_424 : \ - ((RFAL_SUPPORT_BR_CE_A_212) ? RFAL_BR_212 : RFAL_BR_106)))) - -/*! Returns the maximum supported bit rate for CE-B mode. Caller must check if mode is supported before, as even if mode is not supported will return the min */ -#define rfalGetMaxBrCEB() \ - (((RFAL_SUPPORT_BR_CE_B_848) ? \ - RFAL_BR_848 : \ - ((RFAL_SUPPORT_BR_CE_B_424) ? \ - RFAL_BR_424 : \ - ((RFAL_SUPPORT_BR_CE_B_212) ? RFAL_BR_212 : RFAL_BR_106)))) - -/*! Returns the maximum supported bit rate for CE-F mode. Caller must check if mode is supported before, as even if mode is not supported will return the min */ -#define rfalGetMaxBrCEF() (((RFAL_SUPPORT_BR_CE_F_424) ? RFAL_BR_424 : RFAL_BR_212)) - -#define rfalIsModeActiveComm(md) \ - (((md) == RFAL_MODE_POLL_ACTIVE_P2P) || \ - ((md) == RFAL_MODE_LISTEN_ACTIVE_P2P)) /*!< Checks if mode md is Active Communication */ -#define rfalIsModePassiveComm(md) \ - (!rfalIsModeActiveComm(md)) /*!< Checks if mode md is Passive Communication */ -#define rfalIsModePassiveListen(md) \ - (((md) == RFAL_MODE_LISTEN_NFCA) || ((md) == RFAL_MODE_LISTEN_NFCB) || \ - ((md) == RFAL_MODE_LISTEN_NFCF)) /*!< Checks if mode md is Passive Listen */ -#define rfalIsModePassivePoll(md) \ - (rfalIsModePassiveComm(md) && \ - !rfalIsModePassiveListen(md)) /*!< Checks if mode md is Passive Poll */ - -#define rfalConv1fcTo8fc(t) \ - (uint32_t)((uint32_t)(t) / RFAL_1FC_IN_8FC) /*!< Converts the given t from 1/fc to 8/fc */ -#define rfalConv8fcTo1fc(t) \ - (uint32_t)((uint32_t)(t)*RFAL_1FC_IN_8FC) /*!< Converts the given t from 8/fc to 1/fc */ - -#define rfalConv1fcTo64fc(t) \ - (uint32_t)((uint32_t)(t) / RFAL_1FC_IN_64FC) /*!< Converts the given t from 1/fc to 64/fc */ -#define rfalConv64fcTo1fc(t) \ - (uint32_t)((uint32_t)(t)*RFAL_1FC_IN_64FC) /*!< Converts the given t from 64/fc to 1/fc */ - -#define rfalConv1fcTo512fc(t) \ - (uint32_t)( \ - (uint32_t)(t) / RFAL_1FC_IN_512FC) /*!< Converts the given t from 1/fc to 512/fc */ -#define rfalConv512fcTo1fc(t) \ - (uint32_t)((uint32_t)(t)*RFAL_1FC_IN_512FC) /*!< Converts the given t from 512/fc to 1/fc */ - -#define rfalConv1fcTo4096fc(t) \ - (uint32_t)( \ - (uint32_t)(t) / RFAL_1FC_IN_4096FC) /*!< Converts the given t from 1/fc to 4096/fc */ -#define rfalConv4096fcTo1fc(t) \ - (uint32_t)((uint32_t)(t)*RFAL_1FC_IN_4096FC) /*!< Converts the given t from 4096/fc to 1/fc */ - -#define rfalConv1fcToMs(t) \ - (uint32_t)((uint32_t)(t) / RFAL_1MS_IN_1FC) /*!< Converts the given t from 1/fc to ms */ -#define rfalConvMsTo1fc(t) \ - (uint32_t)((uint32_t)(t)*RFAL_1MS_IN_1FC) /*!< Converts the given t from ms to 1/fc */ - -#define rfalConv1fcToUs(t) \ - (uint32_t)( \ - ((uint32_t)(t)*RFAL_US_IN_MS) / \ - RFAL_1MS_IN_1FC) /*!< Converts the given t from 1/fc to us */ -#define rfalConvUsTo1fc(t) \ - (uint32_t)( \ - ((uint32_t)(t)*RFAL_1MS_IN_1FC) / \ - RFAL_US_IN_MS) /*!< Converts the given t from us to 1/fc */ - -#define rfalConv64fcToMs(t) \ - (uint32_t)( \ - (uint32_t)(t) / \ - (RFAL_1MS_IN_1FC / RFAL_1FC_IN_64FC)) /*!< Converts the given t from 64/fc to ms */ -#define rfalConvMsTo64fc(t) \ - (uint32_t)( \ - (uint32_t)(t) * \ - (RFAL_1MS_IN_1FC / RFAL_1FC_IN_64FC)) /*!< Converts the given t from ms to 64/fc */ - -#define rfalConvBitsToBytes(n) \ - (uint16_t)( \ - ((uint16_t)(n) + (RFAL_BITS_IN_BYTE - 1U)) / \ - (RFAL_BITS_IN_BYTE)) /*!< Converts the given n from bits to bytes */ -#define rfalConvBytesToBits(n) \ - (uint32_t)( \ - (uint32_t)(n) * (RFAL_BITS_IN_BYTE)) /*!< Converts the given n from bytes to bits */ - -/*! Computes a Transceive context \a ctx with default flags and the lengths - * in bytes with the given arguments - * \a ctx : Transceive context to be assigned - * \a tB : txBuf the pointer to the buffer to be sent - * \a tBL : txBuf length in bytes - * \a rB : rxBuf the pointer to the buffer to place the received frame - * \a rBL : rxBuf length in bytes - * \a rBL : rxBuf length in bytes - * \a t : FWT to be used on this transceive in 1/fc - */ -#define rfalCreateByteTxRxContext(ctx, tB, tBL, rB, rBL, rdL, t) \ - (ctx).txBuf = (uint8_t*)(tB); \ - (ctx).txBufLen = (uint16_t)rfalConvBytesToBits(tBL); \ - (ctx).rxBuf = (uint8_t*)(rB); \ - (ctx).rxBufLen = (uint16_t)rfalConvBytesToBits(rBL); \ - (ctx).rxRcvdLen = (uint16_t*)(rdL); \ - (ctx).flags = (uint32_t)RFAL_TXRX_FLAGS_DEFAULT; \ - (ctx).fwt = (uint32_t)(t); - -/*! Computes a Transceive context \a ctx using lengths in bytes - * with the given flags and arguments - * \a ctx : Transceive context to be assigned - * \a tB : txBuf the pointer to the buffer to be sent - * \a tBL : txBuf length in bytes - * \a rB : rxBuf the pointer to the buffer to place the received frame - * \a rBL : rxBuf length in bytes - * \a rBL : rxBuf length in bytes - * \a t : FWT to be used on this transceive in 1/fc - */ -#define rfalCreateByteFlagsTxRxContext(ctx, tB, tBL, rB, rBL, rdL, fl, t) \ - (ctx).txBuf = (uint8_t*)(tB); \ - (ctx).txBufLen = (uint16_t)rfalConvBytesToBits(tBL); \ - (ctx).rxBuf = (uint8_t*)(rB); \ - (ctx).rxBufLen = (uint16_t)rfalConvBytesToBits(rBL); \ - (ctx).rxRcvdLen = (uint16_t*)(rdL); \ - (ctx).flags = (uint32_t)(fl); \ - (ctx).fwt = (uint32_t)(t); - -#define rfalLogE(...) \ - platformLog(__VA_ARGS__) /*!< Macro for the error log method */ -#define rfalLogW(...) \ - platformLog(__VA_ARGS__) /*!< Macro for the warning log method */ -#define rfalLogI(...) \ - platformLog(__VA_ARGS__) /*!< Macro for the info log method */ -#define rfalLogD(...) \ - platformLog(__VA_ARGS__) /*!< Macro for the debug log method */ - -/* -****************************************************************************** -* GLOBAL ENUMS -****************************************************************************** -*/ - -/* RFAL Guard Time (GT) default values */ -#define RFAL_GT_NFCA \ - rfalConvMsTo1fc( \ - 5U) /*!< GTA Digital 2.0 6.10.4.1 & B.2 */ -#define RFAL_GT_NFCB \ - rfalConvMsTo1fc( \ - 5U) /*!< GTB Digital 2.0 7.9.4.1 & B.3 */ -#define RFAL_GT_NFCF \ - rfalConvMsTo1fc( \ - 20U) /*!< GTF Digital 2.0 8.7.4.1 & B.4 */ -#define RFAL_GT_NFCV \ - rfalConvMsTo1fc( \ - 5U) /*!< GTV Digital 2.0 9.7.5.1 & B.5 */ -#define RFAL_GT_PICOPASS \ - rfalConvMsTo1fc( \ - 1U) /*!< GT Picopass */ -#define RFAL_GT_AP2P \ - rfalConvMsTo1fc( \ - 5U) /*!< TIRFG Ecma 340 11.1.1 */ -#define RFAL_GT_AP2P_ADJUSTED \ - rfalConvMsTo1fc( \ - 5U + \ - 25U) /*!< Adjusted GT for greater interoperability (Sony XPERIA P, Nokia N9, Huawei P2) */ - -/* RFAL Frame Delay Time (FDT) Listen default values */ -#define RFAL_FDT_LISTEN_NFCA_POLLER \ - 1172U /*!< FDTA,LISTEN,MIN (n=9) Last bit: Logic "1" - tnn,min/2 Digital 1.1 6.10 ; EMV CCP Spec Book D v2.01 4.8.1.3 */ -#define RFAL_FDT_LISTEN_NFCB_POLLER \ - 1008U /*!< TR0B,MIN Digital 1.1 7.1.3 & A.3 ; EMV CCP Spec Book D v2.01 4.8.1.3 & Table A.5 */ -#define RFAL_FDT_LISTEN_NFCF_POLLER \ - 2672U /*!< TR0F,LISTEN,MIN Digital 1.1 8.7.1.1 & A.4 */ -#define RFAL_FDT_LISTEN_NFCV_POLLER \ - 4310U /*!< FDTV,LISTEN,MIN t1 min Digital 2.1 B.5 ; ISO15693-3 2009 9.1 */ -#define RFAL_FDT_LISTEN_PICOPASS_POLLER \ - 3400U /*!< ISO15693 t1 min - observed adjustment */ -#define RFAL_FDT_LISTEN_AP2P_POLLER \ - 64U /*!< FDT AP2P No actual FDTListen is required as fields switch and collision avoidance */ -#define RFAL_FDT_LISTEN_NFCA_LISTENER \ - 1172U /*!< FDTA,LISTEN,MIN Digital 1.1 6.10 */ -#define RFAL_FDT_LISTEN_NFCB_LISTENER \ - 1024U /*!< TR0B,MIN Digital 1.1 7.1.3 & A.3 ; EMV CCP Spec Book D v2.01 4.8.1.3 & Table A.5 */ -#define RFAL_FDT_LISTEN_NFCF_LISTENER \ - 2688U /*!< TR0F,LISTEN,MIN Digital 2.1 8.7.1.1 & B.4 */ -#define RFAL_FDT_LISTEN_AP2P_LISTENER \ - 64U /*!< FDT AP2P No actual FDTListen exists as fields switch and collision avoidance */ - -/* RFAL Frame Delay Time (FDT) Poll default values */ -#define RFAL_FDT_POLL_NFCA_POLLER \ - 6780U /*!< FDTA,POLL,MIN Digital 1.1 6.10.3.1 & A.2 */ -#define RFAL_FDT_POLL_NFCA_T1T_POLLER \ - 384U /*!< RRDDT1T,MIN,B1 Digital 1.1 10.7.1 & A.5 */ -#define RFAL_FDT_POLL_NFCB_POLLER \ - 6780U /*!< FDTB,POLL,MIN = TR2B,MIN,DEFAULT Digital 1.1 7.9.3 & A.3 ; EMVCo 3.0 FDTB,PCD,MIN Table A.5 */ -#define RFAL_FDT_POLL_NFCF_POLLER \ - 6800U /*!< FDTF,POLL,MIN Digital 2.1 8.7.3 & B.4 */ -#define RFAL_FDT_POLL_NFCV_POLLER \ - 4192U /*!< FDTV,POLL Digital 2.1 9.7.3.1 & B.5 */ -#define RFAL_FDT_POLL_PICOPASS_POLLER \ - 1790U /*!< FDT Max */ -#define RFAL_FDT_POLL_AP2P_POLLER \ - 0U /*!< FDT AP2P No actual FDTPoll exists as fields switch and collision avoidance */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! RFAL modes */ -typedef enum { - RFAL_MODE_NONE = 0, /*!< No mode selected/defined */ - RFAL_MODE_POLL_NFCA = - 1, /*!< Mode to perform as NFCA (ISO14443A) Poller (PCD) */ - RFAL_MODE_POLL_NFCA_T1T = - 2, /*!< Mode to perform as NFCA T1T (Topaz) Poller (PCD) */ - RFAL_MODE_POLL_NFCB = - 3, /*!< Mode to perform as NFCB (ISO14443B) Poller (PCD) */ - RFAL_MODE_POLL_B_PRIME = - 4, /*!< Mode to perform as B' Calypso (Innovatron) (PCD) */ - RFAL_MODE_POLL_B_CTS = - 5, /*!< Mode to perform as CTS Poller (PCD) */ - RFAL_MODE_POLL_NFCF = - 6, /*!< Mode to perform as NFCF (FeliCa) Poller (PCD) */ - RFAL_MODE_POLL_NFCV = - 7, /*!< Mode to perform as NFCV (ISO15963) Poller (PCD) */ - RFAL_MODE_POLL_PICOPASS = - 8, /*!< Mode to perform as PicoPass / iClass Poller (PCD) */ - RFAL_MODE_POLL_ACTIVE_P2P = - 9, /*!< Mode to perform as Active P2P (ISO18092) Initiator */ - RFAL_MODE_LISTEN_NFCA = - 10, /*!< Mode to perform as NFCA (ISO14443A) Listener (PICC) */ - RFAL_MODE_LISTEN_NFCB = - 11, /*!< Mode to perform as NFCA (ISO14443B) Listener (PICC) */ - RFAL_MODE_LISTEN_NFCF = - 12, /*!< Mode to perform as NFCA (ISO15963) Listener (PICC) */ - RFAL_MODE_LISTEN_ACTIVE_P2P = - 13 /*!< Mode to perform as Active P2P (ISO18092) Target */ -} rfalMode; - -/*! RFAL Bit rates */ -typedef enum { - RFAL_BR_106 = 0, /*!< Bit Rate 106 kbit/s (fc/128) */ - RFAL_BR_212 = 1, /*!< Bit Rate 212 kbit/s (fc/64) */ - RFAL_BR_424 = 2, /*!< Bit Rate 424 kbit/s (fc/32) */ - RFAL_BR_848 = 3, /*!< Bit Rate 848 kbit/s (fc/16) */ - RFAL_BR_1695 = 4, /*!< Bit Rate 1695 kbit/s (fc/8) */ - RFAL_BR_3390 = 5, /*!< Bit Rate 3390 kbit/s (fc/4) */ - RFAL_BR_6780 = 6, /*!< Bit Rate 6780 kbit/s (fc/2) */ - RFAL_BR_13560 = 7, /*!< Bit Rate 13560 kbit/s (fc) */ - RFAL_BR_52p97 = 0xEB, /*!< Bit Rate 52.97 kbit/s (fc/256) Fast Mode VICC->VCD */ - RFAL_BR_26p48 = 0xEC, /*!< Bit Rate 26,48 kbit/s (fc/512) NFCV VICC->VCD & VCD->VICC 1of4 */ - RFAL_BR_1p66 = 0xED, /*!< Bit Rate 1,66 kbit/s (fc/8192) NFCV VCD->VICC 1of256 */ - RFAL_BR_KEEP = 0xFF /*!< Value indicating to keep the same previous bit rate */ -} rfalBitRate; - -/*! RFAL Compliance modes for upper modules */ -typedef enum { - RFAL_COMPLIANCE_MODE_NFC, /*!< Perform with NFC Forum 1.1 compliance */ - RFAL_COMPLIANCE_MODE_EMV, /*!< Perform with EMVCo compliance */ - RFAL_COMPLIANCE_MODE_ISO /*!< Perform with ISO10373 compliance */ -} rfalComplianceMode; - -/*! RFAL main states flags */ -typedef enum { - RFAL_STATE_IDLE = 0, - RFAL_STATE_INIT = 1, - RFAL_STATE_MODE_SET = 2, - - RFAL_STATE_TXRX = 3, - RFAL_STATE_LM = 4, - RFAL_STATE_WUM = 5 - -} rfalState; - -/*! RFAL transceive states */ -typedef enum { - RFAL_TXRX_STATE_IDLE = 0, - RFAL_TXRX_STATE_INIT = 1, - RFAL_TXRX_STATE_START = 2, - - RFAL_TXRX_STATE_TX_IDLE = 11, - RFAL_TXRX_STATE_TX_WAIT_GT = 12, - RFAL_TXRX_STATE_TX_WAIT_FDT = 13, - RFAL_TXRX_STATE_TX_TRANSMIT = 14, - RFAL_TXRX_STATE_TX_WAIT_WL = 15, - RFAL_TXRX_STATE_TX_RELOAD_FIFO = 16, - RFAL_TXRX_STATE_TX_WAIT_TXE = 17, - RFAL_TXRX_STATE_TX_DONE = 18, - RFAL_TXRX_STATE_TX_FAIL = 19, - - RFAL_TXRX_STATE_RX_IDLE = 81, - RFAL_TXRX_STATE_RX_WAIT_EON = 82, - RFAL_TXRX_STATE_RX_WAIT_RXS = 83, - RFAL_TXRX_STATE_RX_WAIT_RXE = 84, - RFAL_TXRX_STATE_RX_READ_FIFO = 85, - RFAL_TXRX_STATE_RX_ERR_CHECK = 86, - RFAL_TXRX_STATE_RX_READ_DATA = 87, - RFAL_TXRX_STATE_RX_WAIT_EOF = 88, - RFAL_TXRX_STATE_RX_DONE = 89, - RFAL_TXRX_STATE_RX_FAIL = 90, - -} rfalTransceiveState; - -/*! RFAL transceive flags */ -enum { - RFAL_TXRX_FLAGS_CRC_TX_AUTO = - (0U - << 0), /*!< CRC will be generated automatic upon transmission */ - RFAL_TXRX_FLAGS_CRC_TX_MANUAL = - (1U - << 0), /*!< CRC was calculated manually, included in txBuffer */ - RFAL_TXRX_FLAGS_CRC_RX_KEEP = - (1U - << 1), /*!< Upon Reception keep the CRC in rxBuffer (reflected on rcvd length) */ - RFAL_TXRX_FLAGS_CRC_RX_REMV = - (0U - << 1), /*!< Enable CRC check and remove the CRC from rxBuffer */ - RFAL_TXRX_FLAGS_NFCIP1_ON = - (1U - << 2), /*!< Enable NFCIP1 mode: Add SB(F0) and LEN bytes during Tx and skip SB(F0) byte during Rx */ - RFAL_TXRX_FLAGS_NFCIP1_OFF = - (0U - << 2), /*!< Disable NFCIP1 mode: do not append protocol bytes while Tx nor skip while Rx */ - RFAL_TXRX_FLAGS_AGC_OFF = - (1U - << 3), /*!< Disable Automatic Gain Control, improving multiple devices collision detection */ - RFAL_TXRX_FLAGS_AGC_ON = - (0U - << 3), /*!< Enable Automatic Gain Control, improving single device reception */ - RFAL_TXRX_FLAGS_PAR_RX_KEEP = - (1U - << 4), /*!< Disable Parity and CRC check and keep the Parity and CRC bits in the received buffer */ - RFAL_TXRX_FLAGS_PAR_RX_REMV = - (0U - << 0), /*!< Enable Parity check and remove the parity bits from the received buffer */ - RFAL_TXRX_FLAGS_PAR_TX_NONE = - (1U - << 5), /*!< Disable automatic Parity generation (ISO14443A) and use the one provided in the buffer*/ - RFAL_TXRX_FLAGS_PAR_TX_AUTO = - (0U - << 5), /*!< Enable automatic Parity generation (ISO14443A) */ - RFAL_TXRX_FLAGS_NFCV_FLAG_MANUAL = - (1U - << 6), /*!< Disable automatic adaption of flag byte (ISO15693) according to current comm params */ - RFAL_TXRX_FLAGS_NFCV_FLAG_AUTO = - (0U - << 6), /*!< Enable automatic adaption of flag byte (ISO115693) according to current comm params */ -}; - -/*! RFAL error handling */ -typedef enum { - RFAL_ERRORHANDLING_NONE = - 0, /*!< No special error handling will be performed */ - RFAL_ERRORHANDLING_NFC = - 1, /*!< Error handling set to perform as NFC compliant device */ - RFAL_ERRORHANDLING_EMVCO = - 2 /*!< Error handling set to perform as EMVCo compliant device */ -} rfalEHandling; - -/*! Struct that holds all context to be used on a Transceive */ -typedef struct { - uint8_t* txBuf; /*!< (In) Buffer where outgoing message is located */ - uint16_t txBufLen; /*!< (In) Length of the outgoing message in bits */ - - uint8_t* rxBuf; /*!< (Out) Buffer where incoming message will be placed */ - uint16_t rxBufLen; /*!< (In) Maximum length of the incoming message in bits */ - uint16_t* rxRcvdLen; /*!< (Out) Actual received length in bits */ - - uint32_t flags; /*!< (In) TransceiveFlags indication special handling */ - uint32_t fwt; /*!< (In) Frame Waiting Time in 1/fc */ -} rfalTransceiveContext; - -/*! System callback to indicate an event that requires a system reRun */ -typedef void (*rfalUpperLayerCallback)(void); - -/*! Callback to be executed before a Transceive */ -typedef void (*rfalPreTxRxCallback)(void* context); - -/*! Callback to be executed after a Transceive */ -typedef void (*rfalPostTxRxCallback)(void* context); - -/** Callback to be executed on each RFAL state change */ -typedef void (*RfalStateChangedCallback)(void* context); - -/*******************************************************************************/ -/* ISO14443A */ -/*******************************************************************************/ - -/*! RFAL ISO 14443A Short Frame Command */ -typedef enum { - RFAL_14443A_SHORTFRAME_CMD_WUPA = 0x52, /*!< ISO14443A WUPA / NFC-A ALL_REQ */ - RFAL_14443A_SHORTFRAME_CMD_REQA = 0x26 /*!< ISO14443A REQA / NFC-A SENS_REQ */ -} rfal14443AShortFrameCmd; - -/*******************************************************************************/ - -/*******************************************************************************/ -/* FeliCa */ -/*******************************************************************************/ - -#define RFAL_FELICA_LEN_LEN \ - 1U /*!< FeliCa LEN byte length */ -#define RFAL_FELICA_POLL_REQ_LEN \ - (RFAL_FELICA_LEN_LEN + 1U + 2U + 1U + \ - 1U) /*!< FeliCa Poll Request length (LEN + CMD + SC + RC + TSN) */ -#define RFAL_FELICA_POLL_RES_LEN \ - (RFAL_FELICA_LEN_LEN + 1U + 8U + 8U + \ - 2U) /*!< Maximum FeliCa Poll Response length (LEN + CMD + NFCID2 + PAD + RD) */ -#define RFAL_FELICA_POLL_MAX_SLOTS \ - 16U /*!< Maximum number of slots (TSN) on FeliCa Poll */ - -/*! NFC-F RC (Request Code) codes NFC Forum Digital 1.1 Table 42 */ -enum { - RFAL_FELICA_POLL_RC_NO_REQUEST = - 0x00, /*!< RC: No System Code information requested */ - RFAL_FELICA_POLL_RC_SYSTEM_CODE = - 0x01, /*!< RC: System Code information requested */ - RFAL_FELICA_POLL_RC_COM_PERFORMANCE = - 0x02 /*!< RC: Advanced protocol features supported */ -}; - -/*! NFC-F TSN (Time Slot Number) codes NFC Forum Digital 1.1 Table 43 */ -typedef enum { - RFAL_FELICA_1_SLOT = 0, /*!< TSN with number of Time Slots: 1 */ - RFAL_FELICA_2_SLOTS = 1, /*!< TSN with number of Time Slots: 2 */ - RFAL_FELICA_4_SLOTS = 3, /*!< TSN with number of Time Slots: 4 */ - RFAL_FELICA_8_SLOTS = 7, /*!< TSN with number of Time Slots: 8 */ - RFAL_FELICA_16_SLOTS = 15 /*!< TSN with number of Time Slots: 16 */ -} rfalFeliCaPollSlots; - -/*! NFCF Poll Response NFC Forum Digital 1.1 Table 44 */ -typedef uint8_t rfalFeliCaPollRes[RFAL_FELICA_POLL_RES_LEN]; - -/*******************************************************************************/ - -/*******************************************************************************/ -/* Listen Mode */ -/*******************************************************************************/ - -/*! RFAL Listen Mode NFCID Length */ -typedef enum { - RFAL_LM_NFCID_LEN_04 = RFAL_NFCID1_SINGLE_LEN, /*!< Listen mode indicates 4 byte NFCID */ - RFAL_LM_NFCID_LEN_07 = RFAL_NFCID1_DOUBLE_LEN, /*!< Listen mode indicates 7 byte NFCID */ - RFAL_LM_NFCID_LEN_10 = RFAL_NFCID1_TRIPLE_LEN, /*!< Listen mode indicates 10 byte NFCID */ -} rfalLmNfcidLen; - -/*! RFAL Listen Mode States */ -typedef enum { - RFAL_LM_STATE_NOT_INIT = 0x00, /*!< Not Initialized state */ - RFAL_LM_STATE_POWER_OFF = 0x01, /*!< Power Off state */ - RFAL_LM_STATE_IDLE = 0x02, /*!< Idle state Activity 1.1 5.2 */ - RFAL_LM_STATE_READY_A = 0x03, /*!< Ready A state Activity 1.1 5.3 5.4 & 5.5 */ - RFAL_LM_STATE_READY_B = 0x04, /*!< Ready B state Activity 1.1 5.11 5.12 */ - RFAL_LM_STATE_READY_F = 0x05, /*!< Ready F state Activity 1.1 5.15 */ - RFAL_LM_STATE_ACTIVE_A = 0x06, /*!< Active A state Activity 1.1 5.6 */ - RFAL_LM_STATE_CARDEMU_4A = 0x07, /*!< Card Emulation 4A state Activity 1.1 5.10 */ - RFAL_LM_STATE_CARDEMU_4B = 0x08, /*!< Card Emulation 4B state Activity 1.1 5.14 */ - RFAL_LM_STATE_CARDEMU_3 = 0x09, /*!< Card Emulation 3 state Activity 1.1 5.18 */ - RFAL_LM_STATE_TARGET_A = 0x0A, /*!< Target A state Activity 1.1 5.9 */ - RFAL_LM_STATE_TARGET_F = 0x0B, /*!< Target F state Activity 1.1 5.17 */ - RFAL_LM_STATE_SLEEP_A = 0x0C, /*!< Sleep A state Activity 1.1 5.7 */ - RFAL_LM_STATE_SLEEP_B = 0x0D, /*!< Sleep B state Activity 1.1 5.13 */ - RFAL_LM_STATE_READY_Ax = 0x0E, /*!< Ready A* state Activity 1.1 5.3 5.4 & 5.5 */ - RFAL_LM_STATE_ACTIVE_Ax = 0x0F, /*!< Active A* state Activity 1.1 5.6 */ - RFAL_LM_STATE_SLEEP_AF = 0x10, /*!< Sleep AF state Activity 1.1 5.19 */ -} rfalLmState; - -/*! RFAL Listen Mode Passive A configs */ -typedef struct { - rfalLmNfcidLen nfcidLen; /*!< NFCID Len (4, 7 or 10 bytes) */ - uint8_t nfcid[RFAL_NFCID1_TRIPLE_LEN]; /*!< NFCID */ - uint8_t SENS_RES[RFAL_LM_SENS_RES_LEN]; /*!< NFC-106k; SENS_REQ Response */ - uint8_t SEL_RES; /*!< SEL_RES (SAK) with complete NFCID1 (UID) */ -} rfalLmConfPA; - -/*! RFAL Listen Mode Passive B configs */ -typedef struct { - uint8_t SENSB_RES[RFAL_LM_SENSB_RES_LEN]; /*!< SENSF_RES */ -} rfalLmConfPB; - -/*! RFAL Listen Mode Passive F configs */ -typedef struct { - uint8_t SC[RFAL_LM_SENSF_SC_LEN]; /*!< System Code to listen for */ - uint8_t SENSF_RES[RFAL_LM_SENSF_RES_LEN]; /*!< SENSF_RES */ -} rfalLmConfPF; - -/*******************************************************************************/ - -/*******************************************************************************/ -/* Wake-Up Mode */ -/*******************************************************************************/ - -#define RFAL_WUM_REFERENCE_AUTO 0xFFU /*!< Indicates new reference is set by the driver*/ - -/*! RFAL Wake-Up Mode States */ -typedef enum { - RFAL_WUM_STATE_NOT_INIT = 0x00, /*!< Not Initialized state */ - RFAL_WUM_STATE_ENABLED = 0x01, /*!< Wake-Up mode is enabled */ - RFAL_WUM_STATE_ENABLED_WOKE = 0x02, /*!< Wake-Up mode enabled and has received IRQ(s)*/ -} rfalWumState; - -/*! RFAL Wake-Up Period/Timer */ -typedef enum { - RFAL_WUM_PERIOD_10MS = 0x00, /*!< Wake-Up timer 10ms */ - RFAL_WUM_PERIOD_20MS = 0x01, /*!< Wake-Up timer 20ms */ - RFAL_WUM_PERIOD_30MS = 0x02, /*!< Wake-Up timer 30ms */ - RFAL_WUM_PERIOD_40MS = 0x03, /*!< Wake-Up timer 40ms */ - RFAL_WUM_PERIOD_50MS = 0x04, /*!< Wake-Up timer 50ms */ - RFAL_WUM_PERIOD_60MS = 0x05, /*!< Wake-Up timer 60ms */ - RFAL_WUM_PERIOD_70MS = 0x06, /*!< Wake-Up timer 70ms */ - RFAL_WUM_PERIOD_80MS = 0x07, /*!< Wake-Up timer 80ms */ - RFAL_WUM_PERIOD_100MS = 0x10, /*!< Wake-Up timer 100ms */ - RFAL_WUM_PERIOD_200MS = 0x11, /*!< Wake-Up timer 200ms */ - RFAL_WUM_PERIOD_300MS = 0x12, /*!< Wake-Up timer 300ms */ - RFAL_WUM_PERIOD_400MS = 0x13, /*!< Wake-Up timer 400ms */ - RFAL_WUM_PERIOD_500MS = 0x14, /*!< Wake-Up timer 500ms */ - RFAL_WUM_PERIOD_600MS = 0x15, /*!< Wake-Up timer 600ms */ - RFAL_WUM_PERIOD_700MS = 0x16, /*!< Wake-Up timer 700ms */ - RFAL_WUM_PERIOD_800MS = 0x17, /*!< Wake-Up timer 800ms */ -} rfalWumPeriod; - -/*! RFAL Wake-Up Period/Timer */ -typedef enum { - RFAL_WUM_AA_WEIGHT_4 = 0x00, /*!< Wake-Up Auto Average Weight 4 */ - RFAL_WUM_AA_WEIGHT_8 = 0x01, /*!< Wake-Up Auto Average Weight 8 */ - RFAL_WUM_AA_WEIGHT_16 = 0x02, /*!< Wake-Up Auto Average Weight 16 */ - RFAL_WUM_AA_WEIGHT_32 = 0x03, /*!< Wake-Up Auto Average Weight 32 */ -} rfalWumAAWeight; - -/*! RFAL Wake-Up Mode configuration */ -typedef struct { - rfalWumPeriod period; /*!< Wake-Up Timer period;how often measurement(s) is performed */ - bool irqTout; /*!< IRQ at every timeout will refresh the measurement(s) */ - bool swTagDetect; /*!< Use SW Tag Detection instead of HW Wake-Up mode */ - - struct { - bool enabled; /*!< Inductive Amplitude measurement enabled */ - uint8_t delta; /*!< Delta between the reference and measurement to wake-up */ - uint16_t reference; /*!< Reference to be used;RFAL_WUM_REFERENCE_AUTO sets it auto */ - bool autoAvg; /*!< Use the HW Auto Averaging feature */ - bool aaInclMeas; /*!< When AutoAvg is enabled, include IRQ measurement */ - rfalWumAAWeight aaWeight; /*!< When AutoAvg is enabled, last measure weight */ - } indAmp; /*!< Inductive Amplitude Configuration */ - struct { - bool enabled; /*!< Inductive Phase measurement enabled */ - uint8_t delta; /*!< Delta between the reference and measurement to wake-up */ - uint16_t reference; /*!< Reference to be used;RFAL_WUM_REFERENCE_AUTO sets it auto */ - bool autoAvg; /*!< Use the HW Auto Averaging feature */ - bool aaInclMeas; /*!< When AutoAvg is enabled, include IRQ measurement */ - rfalWumAAWeight aaWeight; /*!< When AutoAvg is enabled, last measure weight */ - } indPha; /*!< Inductive Phase Configuration */ - struct { - bool enabled; /*!< Capacitive measurement enabled */ - uint8_t delta; /*!< Delta between the reference and measurement to wake-up */ - uint16_t reference; /*!< Reference to be used;RFAL_WUM_REFERENCE_AUTO sets it auto */ - bool autoAvg; /*!< Use the HW Auto Averaging feature */ - bool aaInclMeas; /*!< When AutoAvg is enabled, include IRQ measurement */ - rfalWumAAWeight aaWeight; /*!< When AutoAvg is enabled, last measure weight */ - } cap; /*!< Capacitive Configuration */ -} rfalWakeUpConfig; - -/*******************************************************************************/ - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief RFAL Initialize - * - * Initializes RFAL layer and the ST25R391x - * Ensures that ST25R391x is properly connected and returns error if any problem - * is detected - * - * \warning rfalAnalogConfigInitialize() should be called before so that - * the Analog config table has been previously initialized. - * - * \return ERR_HW_MISMATCH : Expected HW do not match or communication error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalInitialize(void); - -/*! - ***************************************************************************** - * \brief RFAL Calibrate - * - * Performs necessary calibration of RF chip in case it is indicated by current - * register settings. E.g. antenna calibration and regulator calibration - * - * \return ERR_WRONG_STATE : RFAL not initialized - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode rfalCalibrate(void); - -/*! - ***************************************************************************** - * \brief RFAL Adjust Regulators - * - * Adjusts ST25R391x regulators - * - * \param[out] result : the result of the calibrate antenna in mV - * NULL if result not requested - * - * \return ERR_WRONG_STATE : RFAL not initialized - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode rfalAdjustRegulators(uint16_t* result); - -/*! - ***************************************************************************** - * \brief RFAL Set System Callback - * - * Sets a callback for the driver to call when an event has occurred that - * may require the system to be notified - * - * \param[in] pFunc : method pointer for the upper layer callback - * - ***************************************************************************** - */ -void rfalSetUpperLayerCallback(rfalUpperLayerCallback pFunc); - -/*! - ***************************************************************************** - * \brief RFAL Set Pre Tx Callback - * - * Sets a callback for the driver to call before a Transceive - * - * \param[in] pFunc : method pointer for the Pre Tx callback - * - ***************************************************************************** - */ -void rfalSetPreTxRxCallback(rfalPreTxRxCallback pFunc); - -/*! - ***************************************************************************** - * \brief RFAL Set Post Tx Callback - * - * Sets a callback for the driver to call after a Transceive - * - * \param[in] pFunc : method pointer for the Post Tx callback - * - ***************************************************************************** - */ -void rfalSetPostTxRxCallback(rfalPostTxRxCallback pFunc); - -/** Set RFAL state changed callback - * - * @param cb RfalStateChangedCallback instance - * @param ctx pointer to context - */ -void rfal_set_state_changed_callback(RfalStateChangedCallback callback); - -/** Set callback context - * - * @param ctx pointer to context - */ -void rfal_set_callback_context(void* context); - -/*! - ***************************************************************************** - * \brief RFAL Deinitialize - * - * Deinitializes RFAL layer and the ST25R391x - * - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode rfalDeinitialize(void); - -/*! - ***************************************************************************** - * \brief RFAL Set Mode - * - * Sets the mode that RFAL will operate on the following communications. - * Proper initializations will be performed on the ST25R391x - * - * \warning bit rate value RFAL_BR_KEEP is not allowed, only in rfalSetBitRate() - * - * \warning the mode will be applied immediately on the RFchip regardless of - * any ongoing operations like Transceive, ListenMode - * - * \param[in] mode : mode for the RFAL/RFchip to perform - * \param[in] txBR : transmit bit rate - * \param[in] rxBR : receive bit rate - * - * \see rfalIsGTExpired - * \see rfalMode - * - * \return ERR_WRONG_STATE : RFAL not initialized - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode rfalSetMode(rfalMode mode, rfalBitRate txBR, rfalBitRate rxBR); - -/*! - ***************************************************************************** - * \brief RFAL Get Mode - * - * Gets the mode that RFAL is set to operate - * - * \see rfalMode - * - * \return rfalMode : The current RFAL mode - ***************************************************************************** - */ -rfalMode rfalGetMode(void); - -/*! - ***************************************************************************** - * \brief RFAL Set Bit Rate - * - * Sets the Tx and Rx bit rates with the given values - * The bit rate change is applied on the RF chip remaining in the same - * mode previous defined with rfalSetMode() - * - * If no mode is defined bit rates will not be applied and an error - * is returned - * - * \param[in] txBR : transmit bit rate - * \param[in] rxBR : receive bit rate - * - * \see rfalSetMode - * \see rfalMode - * \see rfalBitRate - * - * \return ERR_WRONG_STATE : RFAL not initialized - * \return ERR_PARAM : Invalid parameter - * \return ERR_NOT_IMPLEMENTED : Mode not implemented - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode rfalSetBitRate(rfalBitRate txBR, rfalBitRate rxBR); - -/*! - ***************************************************************************** - * \brief RFAL Get Bit Rate - * - * Gets the Tx and Rx current bit rates - * - * If RFAL is not initialized or mode not set the bit rates return will - * be invalid RFAL_BR_KEEP - * - * \param[out] txBR : RFAL's current Tx Bit Rate - * \param[out] rxBR : RFAL's current Rx Bit Rate - * - * \see rfalSetBitRate - * \see rfalBitRate - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalGetBitRate(rfalBitRate* txBR, rfalBitRate* rxBR); - -/*! - ***************************************************************************** - * \brief Set Error Handling Mode - * - * Sets the error handling mode to be used by the RFAL - * - * \param[in] eHandling : the error handling mode - * - ***************************************************************************** - */ -void rfalSetErrorHandling(rfalEHandling eHandling); - -/*! - ***************************************************************************** - * \brief Get Error Handling Mode - * - * Gets the error handling mode currently used by the RFAL - * - * \return rfalEHandling : Current error handling mode - ***************************************************************************** - */ -rfalEHandling rfalGetErrorHandling(void); - -/*! - ***************************************************************************** - * \brief Set Observation Mode - * - * Sets ST25R391x observation modes for RF debug purposes - * - * \param[in] txMode : the observation mode to be used during transmission - * \param[in] rxMode : the observation mode to be used during reception - * - * \warning The Observation Mode is an advanced feature and should be set - * according to the documentation of the part number in use. - * Please refer to the corresponding Datasheet or Application Note(s) - ***************************************************************************** - */ -void rfalSetObsvMode(uint8_t txMode, uint8_t rxMode); - -/*! - ***************************************************************************** - * \brief Get Observation Mode - * - * Gets ST25R391x the current configured observation modes - * - * \param[in] txMode : the current observation mode configured for transmission - * \param[in] rxMode : the current observation mode configured for reception - * - ***************************************************************************** - */ -void rfalGetObsvMode(uint8_t* txMode, uint8_t* rxMode); - -/*! - ***************************************************************************** - * \brief Disable Observation Mode - * - * Disables the ST25R391x observation mode - ***************************************************************************** - */ -void rfalDisableObsvMode(void); - -/*! - ***************************************************************************** - * \brief RFAL Set FDT Poll - * - * Sets the Frame Delay Time (FDT) to be used on the following - * communications. - * - * FDT Poll is the minimum time following a Poll Frame during - * which no subsequent Poll Frame can be sent (without a response from - * the Listener in between) - * FDTx,PP,MIN - Digital 1.1 6.10.2 & 7.9.2 & 8.7.2 - * - * \param[in] FDTPoll : Frame Delay Time in 1/fc cycles - * - ***************************************************************************** - */ -void rfalSetFDTPoll(uint32_t FDTPoll); - -/*! - ***************************************************************************** - * \brief RFAL Set FDT Poll - * - * Gets the current Frame Delay Time (FDT) - * - * FDT Poll is the minimum time following a Poll Frame during - * which no subsequent Poll Frame can be sent (without a response from - * the Listener in between) - * FDTx,PP,MIN - Digital 1.1 6.10.2 & 7.9.2 & 8.7.2 - * - * \return FDT : current FDT value in 1/fc cycles - * - ***************************************************************************** - */ -uint32_t rfalGetFDTPoll(void); - -/*! - ***************************************************************************** - * \brief RFAL Set FDT Listen - * - * Sets the Frame Delay Time (FDT) Listen minimum to be used on the - * following communications. - * - * FDT Listen is the minimum time between a Poll Frame and a Listen Frame - * FDTx,LISTEN,MIN - Digital 1.1 6.10.1 & 7.9.1 & 8.7.1 - * - * \param[in] FDTListen : Frame Delay Time in 1/fc cycles - * - ***************************************************************************** - */ -void rfalSetFDTListen(uint32_t FDTListen); - -/*! - ***************************************************************************** - * \brief RFAL Set FDT Listen - * - * Gets the Frame Delay Time (FDT) Listen minimum - * - * FDT Listen is the minimum time between a Poll Frame and a Listen Frame - * FDTx,LISTEN,MIN - Digital 1.1 6.10.1 & 7.9.1 & 8.7.1 - * - * \return FDT : current FDT value in 1/fc cycles - * - ***************************************************************************** - */ -uint32_t rfalGetFDTListen(void); - -/*! - ***************************************************************************** - * \brief RFAL Get GT - * - * Gets the current Guard Time (GT) - * - * GT is the minimum time when a device in Listen Mode is exposed to an - * unmodulated carrier - * - * \return GT : Guard Time in 1/fc cycles - * - ***************************************************************************** - */ -uint32_t rfalGetGT(void); - -/*! - ***************************************************************************** - * \brief RFAL Set GT - * - * Sets the Guard Time (GT) to be used on the following communications. - * - * GT is the minimum time when a device in Listen Mode is exposed to an - * unmodulated carrier - * - * \param[in] GT : Guard Time in 1/fc cycles - * RFAL_GT_NONE if no GT should be applied - * - ***************************************************************************** - */ -void rfalSetGT(uint32_t GT); - -/*! - ***************************************************************************** - * \brief RFAL Is GT expired - * - * Checks whether the GT timer has expired - * - * \return true : GT has expired or not running - * \return false : GT is still running - * - ***************************************************************************** - */ -bool rfalIsGTExpired(void); - -/*! - ***************************************************************************** - * \brief RFAL Turn Field On and Start GT - * - * Turns the Field On, performing Initial Collision Avoidance - * - * After Field On, if GT was set before, it starts the GT timer to be - * used on the following communications. - * - * \return ERR_RF_COLLISION : External field detected - * \return ERR_NONE : Field turned On - * - ***************************************************************************** - */ -ReturnCode rfalFieldOnAndStartGT(void); - -/*! - ***************************************************************************** - * \brief RFAL Turn Field Off - * - * Turns the Field Off - * - * \return ERR_NONE : Field turned Off - ***************************************************************************** - */ -ReturnCode rfalFieldOff(void); - -/***************************************************************************** - * Transceive * - *****************************************************************************/ - -/*! - ***************************************************************************** - * \brief RFAL Set transceive context - * - * Set the context that will be used for the following Transceive - * Output and input buffers have to be passed and all other details prior to - * the Transceive itself has been started - * - * This method only sets the context, once set rfalWorker has - * to be executed until is done - * - * \param[in] ctx : the context for the following Transceive - * - * \see rfalWorker - * \see rfalGetTransceiveStatus - * - * \return ERR_NONE : Done with no error - * \return ERR_WRONG_STATE : Not initialized properly - * \return ERR_PARAM : Invalid parameter or configuration - ***************************************************************************** - */ -ReturnCode rfalStartTransceive(const rfalTransceiveContext* ctx); - -/*! - ***************************************************************************** - * \brief Get Transceive State - * - * Gets current Transceive internal State - * - * \return rfalTransceiveState : the current Transceive internal State - ***************************************************************************** - */ -rfalTransceiveState rfalGetTransceiveState(void); - -/*! - ***************************************************************************** - * \brief Get Transceive Status - * - * Gets current Transceive status - * - * \return ERR_NONE : Transceive done with no error - * \return ERR_BUSY : Transceive ongoing - * \return ERR_XXXX : Error occurred - * \return ERR_TIMEOUT : No response - * \return ERR_FRAMING : Framing error detected - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_LINK_LOSS : Link Loss - External Field is Off - * \return ERR_RF_COLLISION : Collision detected - * \return ERR_IO : Internal error - ***************************************************************************** - */ -ReturnCode rfalGetTransceiveStatus(void); - -/*! - ***************************************************************************** - * \brief Is Transceive in Tx - * - * Checks if Transceive is in Transmission state - * - * \return true Transmission ongoing - * \return false Not in transmission state - ***************************************************************************** - */ -bool rfalIsTransceiveInTx(void); - -/*! - ***************************************************************************** - * \brief Is Transceive in Rx - * - * Checks if Transceive is in Reception state - * - * \return true Transmission done/reception ongoing - * \return false Not in reception state - ***************************************************************************** - */ -bool rfalIsTransceiveInRx(void); - -/*! - ***************************************************************************** - * \brief Get Transceive RSSI - * - * Gets the RSSI value of the last executed Transceive in mV - * - * \param[out] rssi : RSSI value - * - * \return ERR_NOTSUPP : Feature not supported - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalGetTransceiveRSSI(uint16_t* rssi); - -/*! - ***************************************************************************** - * \brief RFAL Worker - * - * This runs RFAL layer, which drives the actual Transceive procedure - * It MUST be executed frequently in order to execute the RFAL internal - * states and perform the requested operations - * - ***************************************************************************** - */ -void rfalWorker(void); - -/***************************************************************************** - * ISO1443A * - *****************************************************************************/ - -/*! - ***************************************************************************** - * \brief Transceives an ISO14443A ShortFrame - * - * Sends REQA to detect if there is any PICC in the field - * - * \param[in] txCmd: Command to be sent: - * 0x52 WUPA / ALL_REQ - * 0x26 REQA / SENS_REQ - * - * \param[in] txCmd : type of short frame to be sent REQA or WUPA - * \param[out] rxBuf : buffer to place the response - * \param[in] rxBufLen : length of rxBuf - * \param[out] rxRcvdLen: received length - * \param[in] fwt : Frame Waiting Time in 1/fc - * - * \warning If fwt is set to RFAL_FWT_NONE it will make endlessly for - * a response, which on a blocking method may not be the - * desired usage - * - * \return ERR_NONE if there is response - * \return ERR_TIMEOUT if there is no response - * \return ERR_COLLISION collision has occurred - * - ***************************************************************************** - */ -ReturnCode rfalISO14443ATransceiveShortFrame( - rfal14443AShortFrameCmd txCmd, - uint8_t* rxBuf, - uint8_t rxBufLen, - uint16_t* rxRcvdLen, - uint32_t fwt); - -/*! - ***************************************************************************** - * \brief Sends an ISO14443A Anticollision Frame - * - * This is use to perform ISO14443A anti-collision. - * \note Anticollision is sent without CRC - * - * - * \param[in] buf : reference to ANTICOLLISION command (with known UID if any) to be sent (also out param) - * reception will be place on this buf after bytesToSend - * \param[in] bytesToSend: reference number of full bytes to be sent (including CMD byte and SEL_PAR) - * if a collision occurs will contain the number of clear bytes - * \param[in] bitsToSend : reference to number of bits (0-7) to be sent; and received (also out param) - * if a collision occurs will indicate the number of clear bits (also out param) - * \param[out] rxLength : reference to the return the received length - * \param[in] fwt : Frame Waiting Time in 1/fc - * - * \return ERR_NONE if there is no error - ***************************************************************************** - */ -ReturnCode rfalISO14443ATransceiveAnticollisionFrame( - uint8_t* buf, - uint8_t* bytesToSend, - uint8_t* bitsToSend, - uint16_t* rxLength, - uint32_t fwt); - -/***************************************************************************** - * FeliCa * - *****************************************************************************/ - -/*! - ***************************************************************************** - * \brief FeliCa Poll - * - * Sends a Poll Request and collects all Poll Responses according to the - * given slots - * - * - * \param[in] slots : number of slots for the Poll Request - * \param[in] sysCode : system code (SC) for the Poll Request - * \param[in] reqCode : request code (RC) for the Poll Request - * \param[out] pollResList : list of all responses - * \param[in] pollResListSize : number of responses that can be placed in pollResList - * \param[out] devicesDetected : number of cards found - * \param[out] collisionsDetected: number of collisions detected - * - * \return ERR_NONE if there is no error - * \return ERR_TIMEOUT if there is no response - ***************************************************************************** - */ -ReturnCode rfalFeliCaPoll( - rfalFeliCaPollSlots slots, - uint16_t sysCode, - uint8_t reqCode, - rfalFeliCaPollRes* pollResList, - uint8_t pollResListSize, - uint8_t* devicesDetected, - uint8_t* collisionsDetected); - -/***************************************************************************** - * ISO15693 * - *****************************************************************************/ - -/*! - ***************************************************************************** - * \brief Sends an ISO15693 Anticollision Frame - * - * This send the Anticollision|Inventory frame (INVENTORY_REQ) - * - * \warning rxBuf must be able to contain the payload and CRC - * - * \param[in] txBuf : Buffer where outgoing message is located - * \param[in] txBufLen : Length of the outgoing message in bytes - * \param[out] rxBuf : Buffer where incoming message will be placed - * \param[in] rxBufLen : Maximum length of the incoming message in bytes - * \param[out] actLen : Actual received length in bits - * - * \return ERR_NONE : Transceive done with no error - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_IO : Internal error - ***************************************************************************** - */ -ReturnCode rfalISO15693TransceiveAnticollisionFrame( - uint8_t* txBuf, - uint8_t txBufLen, - uint8_t* rxBuf, - uint8_t rxBufLen, - uint16_t* actLen); - -/*! - ***************************************************************************** - * \brief Sends an ISO15693 Anticollision EOF - * - * This sends the Anticollision|Inventory EOF used as a slot marker - * - * \warning rxBuf must be able to contain the payload and CRC - * - * \param[out] rxBuf : Buffer where incoming message will be placed - * \param[in] rxBufLen : Maximum length of the incoming message in bytes - * \param[out] actLen : Actual received length in bits - * - * \return ERR_NONE : Transceive done with no error - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_IO : Internal error - ***************************************************************************** - */ -ReturnCode - rfalISO15693TransceiveEOFAnticollision(uint8_t* rxBuf, uint8_t rxBufLen, uint16_t* actLen); - -/*! - ***************************************************************************** - * \brief Sends an ISO15693 EOF - * - * This is method sends an ISO15693 (EoF) used for a Write operation - * - * \warning rxBuf must be able to contain the payload and CRC - * - * \param[out] rxBuf : Buffer where incoming message will be placed - * \param[in] rxBufLen : Maximum length of the incoming message in bytes - * \param[out] actLen : Actual received length in bytes - * - * \return ERR_NONE : Transceive done with no error - * \return ERR_IO : Internal error - ***************************************************************************** - */ -ReturnCode rfalISO15693TransceiveEOF(uint8_t* rxBuf, uint8_t rxBufLen, uint16_t* actLen); - -/*! - ***************************************************************************** - * \brief Transceive Blocking Tx - * - * This is method triggers a Transceive and executes it blocking until the - * Tx has been completed - * - * \param[in] txBuf : Buffer where outgoing message is located - * \param[in] txBufLen : Length of the outgoing message in bytes - * \param[out] rxBuf : Buffer where incoming message will be placed - * \param[in] rxBufLen : Maximum length of the incoming message in bytes - * \param[out] actLen : Actual received length in bits - * \param[in] flags : TransceiveFlags indication special handling - * \param[in] fwt : Frame Waiting Time in 1/fc - * - * \return ERR_NONE : Transceive done with no error - * \return ERR_BUSY : Transceive ongoing - * \return ERR_XXXX : Error occurred - * \return ERR_LINK_LOSS : Link Loss - External Field is Off - * \return ERR_RF_COLLISION : Collision detected - * \return ERR_IO : Internal error - ***************************************************************************** - */ -ReturnCode rfalTransceiveBlockingTx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt); - -/*! - ***************************************************************************** - * \brief Transceive Blocking Rx - * - * This is method executes the reception of an ongoing Transceive triggered - * before by rfalTransceiveBlockingTx() - * - * \return ERR_NONE : Transceive done with no error - * \return ERR_BUSY : Transceive ongoing - * \return ERR_XXXX : Error occurred - * \return ERR_TIMEOUT : No response - * \return ERR_FRAMING : Framing error detected - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_LINK_LOSS : Link Loss - External Field is Off - * \return ERR_RF_COLLISION : Collision detected - * \return ERR_IO : Internal error - ***************************************************************************** - */ -ReturnCode rfalTransceiveBlockingRx(void); - -/*! - ***************************************************************************** - * \brief Transceive Blocking - * - * This is method triggers a Transceive and executes it blocking until it - * has been completed - * - * \param[in] txBuf : Buffer where outgoing message is located - * \param[in] txBufLen : Length of the outgoing message in bytes - * \param[out] rxBuf : Buffer where incoming message will be placed - * \param[in] rxBufLen : Maximum length of the incoming message in bytes - * \param[out] actLen : Actual received length in bytes - * \param[in] flags : TransceiveFlags indication special handling - * \param[in] fwt : Frame Waiting Time in 1/fc - * - * \return ERR_NONE : Transceive done with no error - * \return ERR_BUSY : Transceive ongoing - * \return ERR_XXXX : Error occurred - * \return ERR_TIMEOUT : No response - * \return ERR_FRAMING : Framing error detected - * \return ERR_PAR : Parity error detected - * \return ERR_CRC : CRC error detected - * \return ERR_LINK_LOSS : Link Loss - External Field is Off - * \return ERR_RF_COLLISION : Collision detected - * \return ERR_IO : Internal error - ***************************************************************************** - */ -ReturnCode rfalTransceiveBlockingTxRx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt); - -ReturnCode rfalTransceiveBitsBlockingTxRx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt); - -ReturnCode rfalTransceiveBitsBlockingTx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt); - -/***************************************************************************** - * Listen Mode * - *****************************************************************************/ - -/*! - ***************************************************************************** - * \brief Is external Field On - * - * Checks if external field (other peer/device) is on/detected - * - * \return true External field is On - * \return false No external field is detected - * - ***************************************************************************** - */ -bool rfalIsExtFieldOn(void); - -/*! - ***************************************************************************** - * \brief Listen Mode start - * - * Configures RF Chip to go into listen mode enabling the given technologies - * - * - * \param[in] lmMask: mask with the enabled/disabled listen modes - * use: RFAL_LM_MASK_NFCA ; RFAL_LM_MASK_NFCB ; - * RFAL_LM_MASK_NFCF ; RFAL_LM_MASK_ACTIVE_P2P - * \param[in] confA: pointer to Passive A configurations (NULL if disabled) - * \param[in] confB: pointer to Passive B configurations (NULL if disabled) - * \param[in] confF: pointer to Passive F configurations (NULL if disabled) - * \param[in] rxBuf: buffer to place incoming data - * \param[in] rxBufLen: length in bits of rxBuf - * \param[in] rxLen: pointer to write the data length in bits placed into rxBuf - * - * - * \return ERR_PARAM Invalid parameter - * \return ERR_REQUEST Invalid listen mode mask - * \return ERR_NONE Done with no error - * - ***************************************************************************** - */ -ReturnCode rfalListenStart( - uint32_t lmMask, - const rfalLmConfPA* confA, - const rfalLmConfPB* confB, - const rfalLmConfPF* confF, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rxLen); - -/*! - ***************************************************************************** - * \brief Listen Mode start Sleeping - * - * - ***************************************************************************** - */ -ReturnCode - rfalListenSleepStart(rfalLmState sleepSt, uint8_t* rxBuf, uint16_t rxBufLen, uint16_t* rxLen); - -/*! - ***************************************************************************** - * \brief Listen Mode Stop - * - * Disables the listen mode on the RF Chip - * - * \warning the listen mode will be disabled immediately on the RFchip regardless - * of any ongoing operations like Transceive - * - * \return ERR_NONE Done with no error - * - ***************************************************************************** - */ -ReturnCode rfalListenStop(void); - -/*! - ***************************************************************************** - * \brief Listen Mode get state - * - * Sets the new state of the Listen Mode and applies the necessary changes - * on the RF Chip - * - * \param[out] dataFlag: indicates that Listen Mode has rcvd data and caller - * must process it. The received message is located - * at the rxBuf passed on rfalListenStart(). - * rfalListenSetState() will clear this flag - * if NULL output parameter will no be written/returned - * \param[out] lastBR: bit rate detected of the last initiator request - * if NULL output parameter will no be written/returned - * - * \return rfalLmState RFAL_LM_STATE_NOT_INIT : LM not initialized properly - * Any Other : LM State - * - ***************************************************************************** - */ -rfalLmState rfalListenGetState(bool* dataFlag, rfalBitRate* lastBR); - -/*! - ***************************************************************************** - * \brief Listen Mode set state - * - * Sets the new state of the Listen Mode and applies the necessary changes - * on the RF Chip - * - * \param[in] newSt : New state to go to - * - * \return ERR_WRONG_STATE : Not initialized properly - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : Done with no error - * - ***************************************************************************** - */ -ReturnCode rfalListenSetState(rfalLmState newSt); - -/***************************************************************************** - * Wake-Up Mode * - *****************************************************************************/ - -/*! - ***************************************************************************** - * \brief Wake-Up Mode Start - * - * Sets the RF Chip in Low Power Wake-Up Mode according to the given - * configuration. - * - * \param[in] config : Generic Wake-Up configuration provided by lower - * layers. If NULL will automatically configure the - * Wake-Up mode - * - * \return ERR_WRONG_STATE : Not initialized properly - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : Done with no error - * - ***************************************************************************** - */ -ReturnCode rfalWakeUpModeStart(const rfalWakeUpConfig* config); - -/*! - ***************************************************************************** - * \brief Wake-Up Has Woke - * - * Returns true if the Wake-Up mode is enabled and it has already received - * the indication from the RF Chip that the surrounding environment has changed - * and flagged at least one wake-Up interrupt - * - * \return true : Wake-Up mode enabled and has received a wake-up IRQ - * \return false : no Wake-Up IRQ has been received - * - ***************************************************************************** - */ -bool rfalWakeUpModeHasWoke(void); - -/*! - ***************************************************************************** - * \brief Wake-Up Mode Stop - * - * Stops the Wake-Up Mode - * - * \return ERR_WRONG_STATE : Not initialized properly - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : Done with no error - * - ***************************************************************************** - */ -ReturnCode rfalWakeUpModeStop(void); - -/*! - ***************************************************************************** - * \brief Low Power Mode Start - * - * Sets the RF Chip in Low Power Mode. - * In this mode the RF Chip is placed in Low Power Mode, similar to Wake-up - * mode but no operation nor period measurement is performed. - * Mode must be terminated by rfalLowPowerModeStop() - * - * \return ERR_WRONG_STATE : Not initialized properly - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : Done with no error - * - ***************************************************************************** - */ -ReturnCode rfalLowPowerModeStart(void); - -/*! - ***************************************************************************** - * \brief Low Power Mode Stop - * - * Stops the Low Power Mode re-enabling the device - * - * \return ERR_WRONG_STATE : Not initialized properly - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : Done with no error - * - ***************************************************************************** - */ -ReturnCode rfalLowPowerModeStop(void); - -#endif /* RFAL_RF_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_st25tb.h b/lib/ST25RFAL002/include/rfal_st25tb.h deleted file mode 100644 index dcd7baa57..000000000 --- a/lib/ST25RFAL002/include/rfal_st25tb.h +++ /dev/null @@ -1,340 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_st25tb.h - * - * \author Gustavo Patricio - * - * \brief Implementation of ST25TB interface - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup ST25TB - * \brief RFAL ST25TB Module - * @{ - * - */ - -#ifndef RFAL_ST25TB_H -#define RFAL_ST25TB_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" -#include "rfal_nfcb.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_ST25TB_CHIP_ID_LEN 1U /*!< ST25TB chip ID length */ -#define RFAL_ST25TB_CRC_LEN 2U /*!< ST25TB CRC length */ -#define RFAL_ST25TB_UID_LEN 8U /*!< ST25TB Unique ID length */ -#define RFAL_ST25TB_BLOCK_LEN 4U /*!< ST25TB Data Block length */ - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ -typedef uint8_t rfalSt25tbUID[RFAL_ST25TB_UID_LEN]; /*!< ST25TB UID type */ -typedef uint8_t rfalSt25tbBlock[RFAL_ST25TB_BLOCK_LEN]; /*!< ST25TB Block type */ - -/*! ST25TB listener device (PICC) struct */ -typedef struct { - uint8_t chipID; /*!< Device's session Chip ID */ - rfalSt25tbUID UID; /*!< Device's UID */ - bool isDeselected; /*!< Device deselect flag */ -} rfalSt25tbListenDevice; - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Initialize ST25TB Poller mode - * - * This methods configures RFAL RF layer to perform as a - * ST25TB Poller/RW including all default timings - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerInitialize(void); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Check Presence - * - * This method checks if a ST25TB Listen device (PICC) is present on the field - * by sending an Initiate command - * - * \param[out] chipId : if successfully retrieved, the device's chip ID - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_RF_COLLISION : Collision detected one or more device in the field - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerCheckPresence(uint8_t* chipId); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Collision Resolution - * - * This method performs ST25TB Collision resolution, selects the each device, - * retrieves its UID and then deselects. - * In case only one device is identified the ST25TB device is left in select - * state. - * - * \param[in] devLimit : device limit value, and size st25tbDevList - * \param[out] st25tbDevList : ST35TB listener device info - * \param[out] devCnt : Devices found counter - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_RF_COLLISION : Collision detected one or more device in the field - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerCollisionResolution( - uint8_t devLimit, - rfalSt25tbListenDevice* st25tbDevList, - uint8_t* devCnt); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Initiate - * - * This method sends an Initiate command - * - * If a single device responds the chip ID will be retrieved - * - * \param[out] chipId : chip ID of the device - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerInitiate(uint8_t* chipId); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Pcall - * - * This method sends a Pcall command - * If successful the device's chip ID will be retrieved - * - * \param[out] chipId : Chip ID of the device - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerPcall(uint8_t* chipId); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Slot Marker - * - * This method sends a Slot Marker - * - * If a single device responds the chip ID will be retrieved - * - * \param[in] slotNum : Slot Number - * \param[out] chipIdRes : Chip ID of the device - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerSlotMarker(uint8_t slotNum, uint8_t* chipIdRes); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Select - * - * This method sends a ST25TB Select command with the given chip ID. - * - * If the device is already in Selected state and receives an incorrect chip - * ID, it goes into Deselected state - * - * \param[in] chipId : chip ID of the device to be selected - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerSelect(uint8_t chipId); - -/*! - ***************************************************************************** - * \brief ST25TB Get UID - * - * This method sends a Get_UID command - * - * If a single device responds the chip UID will be retrieved - * - * \param[out] UID : UID of the found device - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerGetUID(rfalSt25tbUID* UID); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Read Block - * - * This method reads a block of the ST25TB - * - * \param[in] blockAddress : address of the block to be read - * \param[out] blockData : location to place the data read from block - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerReadBlock(uint8_t blockAddress, rfalSt25tbBlock* blockData); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Write Block - * - * This method writes a block of the ST25TB - * - * \param[in] blockAddress : address of the block to be written - * \param[in] blockData : data to be written on the block - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerWriteBlock(uint8_t blockAddress, const rfalSt25tbBlock* blockData); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Completion - * - * This method sends a completion command to the ST25TB. After the - * completion the card no longer will reply to any command. - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_PROTO : Protocol error detected, invalid SENSB_RES received - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerCompletion(void); - -/*! - ***************************************************************************** - * \brief ST25TB Poller Reset to Inventory - * - * This method sends a Reset to Inventory command to the ST25TB. - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_TIMEOUT : Timeout error, no listener device detected - * \return ERR_PROTO : Protocol error detected, invalid SENSB_RES received - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalSt25tbPollerResetToInventory(void); - -#endif /* RFAL_ST25TB_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_st25xv.h b/lib/ST25RFAL002/include/rfal_st25xv.h deleted file mode 100644 index d7bec8377..000000000 --- a/lib/ST25RFAL002/include/rfal_st25xv.h +++ /dev/null @@ -1,844 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_st25xv.h - * - * \author Gustavo Patricio - * - * \brief NFC-V ST25 NFC-V Tag specific features - * - * This module provides support for ST's specific features available on - * NFC-V (ISO15693) tag families: ST25D, ST25TV, M24LR - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup ST25xV - * \brief RFAL ST25xV Module - * @{ - * - */ - -#ifndef RFAL_ST25xV_H -#define RFAL_ST25xV_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_nfc.h" -#include "rfal_rf.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_NFCV_BLOCKNUM_M24LR_LEN \ - 2U /*!< Block Number length of MR24LR tags: 16 bits */ -#define RFAL_NFCV_ST_IC_MFG_CODE \ - 0x02 /*!< ST IC Mfg code (used for custom commands) */ - -/*! - ***************************************************************************** - * \brief NFC-V Poller Read Single Block (M24LR) - * - * Reads a Single Block from a M24LR tag which has the number of blocks - * bigger than 256 (M24LR16 ; M24LR64) - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * default: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] blockNum : Number of the block to read (16 bits) - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerM24LRReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Read Single Block (M24LR) - * - * Reads a Single Block from a M24LR tag which has the number of blocks - * bigger than 256 (M24LR16 ; M24LR64) using ST Fast mode - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * default: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] blockNum : Number of the block to read (16 bits) - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerM24LRFastReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Write Single Block (M24LR) - * - * Writes a Single Block from a M24LR tag which has the number of blocks - * bigger than 256 (M24LR16 ; M24LR64) - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be written - * if not provided Select mode will be used - * \param[in] blockNum : Number of the block to write (16 bits) - * \param[in] wrData : data to be written on the given block - * \param[in] blockLen : number of bytes of a block - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerM24LRWriteSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - const uint8_t* wrData, - uint8_t blockLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Read Multiple Blocks (M24LR) - * - * Reads Multiple Blocks from a device from a M24LR tag which has the number of blocks - * bigger than 256 (M24LR16 ; M24LR64) - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] firstBlockNum : first block to be read (16 bits) - * \param[in] numOfBlocks : number of block to read - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerM24LRReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint16_t firstBlockNum, - uint8_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Read Multiple Blocks (M24LR) - * - * Reads Multiple Blocks from a device from a M24LR tag which has the number of blocks - * bigger than 256 (M24LR16 ; M24LR64) using ST Fast mode - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] firstBlockNum : first block to be read (16 bits) - * \param[in] numOfBlocks : number of block to read - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerM24LRFastReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint16_t firstBlockNum, - uint8_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Read Single Block - * - * Reads a Single Block from a device (VICC) using ST Fast mode - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] blockNum : Number of the block to read - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerFastReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint8_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Read Multiple Blocks - * - * Reads Multiple Blocks from a device (VICC) using ST Fast mode - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] firstBlockNum : first block to be read - * \param[in] numOfBlocks : number of block to read - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerFastReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint8_t firstBlockNum, - uint8_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Extended Read Single Block - * - * Reads a Single Block from a device (VICC) supporting extended commands using ST Fast mode - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] blockNum : Number of the block to read (16 bits) - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerFastExtendedReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Extended Read Multiple Blocks - * - * Reads Multiple Blocks from a device (VICC) supporting extended commands using ST Fast mode - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] firstBlockNum : first block to be read (16 bits) - * \param[in] numOfBlocks : number of consecutive blocks to read (16 bits) - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerFastExtReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint16_t firstBlockNum, - uint16_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Read Configuration - * - * Reads static configuration registers at the Pointer address - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] pointer : Pointer address - * \param[out] regValue : Register value - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerReadConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t* regValue); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Write Configuration - * - * Writes static configuration registers at the Pointer address - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] pointer : Pointer address - * \param[in] regValue : Register value - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerWriteConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t regValue); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Read Dynamic Configuration - * - * Reads dynamic registers at the Pointer address - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] pointer : Pointer address - * \param[out] regValue : Register value - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerReadDynamicConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t* regValue); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Write Dynamic Configuration - * - * Writes dynamic registers at the Pointer address - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] pointer : Pointer address - * \param[in] regValue : Register value - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerWriteDynamicConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t regValue); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Read Dynamic Configuration - * - * Reads dynamic registers at the Pointer address using ST Fast mode - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] pointer : Pointer address - * \param[out] regValue : Register value - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerFastReadDynamicConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t* regValue); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Write Dynamic Configuration - * - * Writes dynamic registers at the Pointer address using ST Fast mode - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] pointer : Pointer address - * \param[in] regValue : Register value - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerFastWriteDynamicConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t regValue); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Present Password - * - * Sends the Present Password command - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] pwdNum : Password number - * \param[in] pwd : Password - * \param[in] pwdLen : Password length - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerPresentPassword( - uint8_t flags, - const uint8_t* uid, - uint8_t pwdNum, - const uint8_t* pwd, - uint8_t pwdLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Get Random Number - * - * Returns a 16 bit random number - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerGetRandomNumber( - uint8_t flags, - const uint8_t* uid, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Read Message length - * - * Sends a Read Message Length message to retrieve the value of MB_LEN_Dyn - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[out] msgLen : Message Length - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerReadMessageLength(uint8_t flags, const uint8_t* uid, uint8_t* msgLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Read Message length - * - * Sends a Fast Read Message Length message to retrieve the value of MB_LEN_Dyn using ST Fast mode. - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[out] msgLen : Message Length - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerFastReadMsgLength(uint8_t flags, const uint8_t* uid, uint8_t* msgLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Read Message - * - * Reads up to 256 bytes in the Mailbox from the location - * specified by MBpointer and sends back their value in the rxBuf response. - * First MailBox location is '00'. When Number of bytes is set to 00h - * and MBPointer is equals to 00h, the MB_LEN bytes of the full message - * are returned. Otherwise, Read Message command returns (Number of Bytes + 1) bytes - * (i.e. 01h returns 2 bytes, FFh returns 256 bytes). - * An error is reported if (Pointer + Nb of bytes + 1) is greater than the message length. - * RF Reading of the last byte of the mailbox message automatically clears b1 - * of MB_CTRL_Dyn HOST_PUT_MSG, and allows RF to put a new message. - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] mbPointer : MPpointer - * \param[in] numBytes : number of bytes - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerReadMessage( - uint8_t flags, - const uint8_t* uid, - uint8_t mbPointer, - uint8_t numBytes, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Read Message - * - * Reads up to 256 bytes in the Mailbox from the location - * specified by MBpointer and sends back their value in the rxBuf response using ST Fast mode. - * First MailBox location is '00'. When Number of bytes is set to 00h - * and MBPointer is equals to 00h, the MB_LEN bytes of the full message - * are returned. Otherwise, Read Message command returns (Number of Bytes + 1) bytes - * (i.e. 01h returns 2 bytes, FFh returns 256 bytes). - * An error is reported if (Pointer + Nb of bytes + 1) is greater than the message length. - * RF Reading of the last byte of the mailbox message automatically clears b1 - * of MB_CTRL_Dyn HOST_PUT_MSG, and allows RF to put a new message. - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] mbPointer : MPpointer - * \param[in] numBytes : number of bytes - * \param[out] rxBuf : buffer to store response (also with RES_FLAGS) - * \param[in] rxBufLen : length of rxBuf - * \param[out] rcvLen : number of bytes received - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerFastReadMessage( - uint8_t flags, - const uint8_t* uid, - uint8_t mbPointer, - uint8_t numBytes, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Write Message - * - * Sends Write message Command - * - * On receiving the Write Message command, the ST25DVxxx puts the data contained - * in the request into the Mailbox buffer, update the MB_LEN_Dyn register, and - * set bit RF_PUT_MSG in MB_CTRL_Dyn register. It then reports if the write operation was successful - * in the response. The ST25DVxxx Mailbox contains up to 256 data bytes which are filled from the - * first location '00'. MSGlength parameter of the command is the number of - * Data bytes minus 1 (00 for 1 byte of data, FFh for 256 bytes of data). - * Write Message could be executed only when Mailbox is accessible by RF. - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] msgLen : MSGLen number of Data bytes minus 1 - * \param[in] msgData : Message Data - * \param[out] txBuf : buffer to used to build the Write Message command - * \param[in] txBufLen : length of txBuf - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerWriteMessage( - uint8_t flags, - const uint8_t* uid, - uint8_t msgLen, - const uint8_t* msgData, - uint8_t* txBuf, - uint16_t txBufLen); - -/*! - ***************************************************************************** - * \brief NFC-V Poller Fast Write Message - * - * Sends Fast Write message Command using ST Fast mode - * - * On receiving the Write Message command, the ST25DVxxx puts the data contained - * in the request into the Mailbox buffer, update the MB_LEN_Dyn register, and - * set bit RF_PUT_MSG in MB_CTRL_Dyn register. It then reports if the write operation was successful - * in the response. The ST25DVxxx Mailbox contains up to 256 data bytes which are filled from the - * first location '00'. MSGlength parameter of the command is the number of - * Data bytes minus 1 (00 for 1 byte of data, FFh for 256 bytes of data). - * Write Message could be executed only when Mailbox is accessible by RF. - * - * \param[in] flags : Flags to be used: Sub-carrier; Data_rate; Option - * for NFC-Forum use: RFAL_NFCV_REQ_FLAG_DEFAULT - * \param[in] uid : UID of the device to be put to be read - * if not provided Select mode will be used - * \param[in] msgLen : MSGLen number of Data bytes minus 1 - * \param[in] msgData : Message Data - * \param[out] txBuf : buffer to used to build the Write Message command - * \param[in] txBufLen : length of txBuf - * - * \return ERR_WRONG_STATE : RFAL not initialized or incorrect mode - * \return ERR_PARAM : Invalid parameters - * \return ERR_IO : Generic internal error - * \return ERR_CRC : CRC error detected - * \return ERR_FRAMING : Framing error detected - * \return ERR_PROTO : Protocol error detected - * \return ERR_TIMEOUT : Timeout error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalST25xVPollerFastWriteMessage( - uint8_t flags, - const uint8_t* uid, - uint8_t msgLen, - const uint8_t* msgData, - uint8_t* txBuf, - uint16_t txBufLen); - -#endif /* RFAL_ST25xV_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_t1t.h b/lib/ST25RFAL002/include/rfal_t1t.h deleted file mode 100644 index e9e39d23c..000000000 --- a/lib/ST25RFAL002/include/rfal_t1t.h +++ /dev/null @@ -1,178 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_t1t.h - * - * \author Gustavo Patricio - * - * \brief Provides NFC-A T1T convenience methods and definitions - * - * This module provides an interface to perform as a NFC-A Reader/Writer - * to handle a Type 1 Tag T1T (Topaz) - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup T1T - * \brief RFAL T1T Module - * @{ - * - */ - -#ifndef RFAL_T1T_H -#define RFAL_T1T_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ -#define RFAL_T1T_UID_LEN 4 /*!< T1T UID length of cascade level 1 only tag */ -#define RFAL_T1T_HR_LENGTH 2 /*!< T1T HR(Header ROM) length */ - -#define RFAL_T1T_HR0_NDEF_MASK 0xF0 /*!< T1T HR0 NDEF capability mask T1T 1.2 2.2.2 */ -#define RFAL_T1T_HR0_NDEF_SUPPORT 0x10 /*!< T1T HR0 NDEF capable value T1T 1.2 2.2.2 */ - -/*! NFC-A T1T (Topaz) command set */ -typedef enum { - RFAL_T1T_CMD_RID = 0x78, /*!< T1T Read UID */ - RFAL_T1T_CMD_RALL = 0x00, /*!< T1T Read All */ - RFAL_T1T_CMD_READ = 0x01, /*!< T1T Read */ - RFAL_T1T_CMD_WRITE_E = 0x53, /*!< T1T Write with erase (single byte) */ - RFAL_T1T_CMD_WRITE_NE = 0x1A /*!< T1T Write with no erase (single byte) */ -} rfalT1Tcmds; - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! NFC-A T1T (Topaz) RID_RES Digital 1.1 10.6.2 & Table 50 */ -typedef struct { - uint8_t hr0; /*!< T1T Header ROM: HR0 */ - uint8_t hr1; /*!< T1T Header ROM: HR1 */ - uint8_t uid[RFAL_T1T_UID_LEN]; /*!< T1T UID */ -} rfalT1TRidRes; - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Initialize NFC-A T1T Poller mode - * - * This methods configures RFAL RF layer to perform as a - * NFC-A T1T Poller/RW (Topaz) including all default timings - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT1TPollerInitialize(void); - -/*! - ***************************************************************************** - * \brief NFC-A T1T Poller RID - * - * This method reads the UID of a NFC-A T1T Listener device - * - * - * \param[out] ridRes : pointer to place the RID_RES - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT1TPollerRid(rfalT1TRidRes* ridRes); - -/*! - ***************************************************************************** - * \brief NFC-A T1T Poller RALL - * - * This method send a Read All command to a NFC-A T1T Listener device - * - * - * \param[in] uid : the UID of the device to read data - * \param[out] rxBuf : pointer to place the read data - * \param[in] rxBufLen : size of rxBuf - * \param[out] rxRcvdLen : actual received data - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode - rfalT1TPollerRall(const uint8_t* uid, uint8_t* rxBuf, uint16_t rxBufLen, uint16_t* rxRcvdLen); - -/*! - ***************************************************************************** - * \brief NFC-A T1T Poller Write - * - * This method writes the given data on the address of a NFC-A T1T Listener device - * - * - * \param[in] uid : the UID of the device to read data - * \param[in] address : address to write the data - * \param[in] data : the data to be written - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT1TPollerWrite(const uint8_t* uid, uint8_t address, uint8_t data); - -#endif /* RFAL_T1T_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_t2t.h b/lib/ST25RFAL002/include/rfal_t2t.h deleted file mode 100644 index b90462fd2..000000000 --- a/lib/ST25RFAL002/include/rfal_t2t.h +++ /dev/null @@ -1,150 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_t2t.h - * - * \author Gustavo Patricio - * - * \brief Provides NFC-A T2T convenience methods and definitions - * - * This module provides an interface to perform as a NFC-A Reader/Writer - * to handle a Type 2 Tag T2T - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup T2T - * \brief RFAL T2T Module - * @{ - * - */ - -#ifndef RFAL_T2T_H -#define RFAL_T2T_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_T2T_BLOCK_LEN 4U /*!< T2T block length */ -#define RFAL_T2T_READ_DATA_LEN (4U * RFAL_T2T_BLOCK_LEN) /*!< T2T READ data length */ -#define RFAL_T2T_WRITE_DATA_LEN RFAL_T2T_BLOCK_LEN /*!< T2T WRITE data length */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief NFC-A T2T Poller Read - * - * This method sends a Read command to a NFC-A T2T Listener device - * - * - * \param[in] blockNum : Number of the block to read - * \param[out] rxBuf : pointer to place the read data - * \param[in] rxBufLen : size of rxBuf (RFAL_T2T_READ_DATA_LEN) - * \param[out] rcvLen : actual received data - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode - rfalT2TPollerRead(uint8_t blockNum, uint8_t* rxBuf, uint16_t rxBufLen, uint16_t* rcvLen); - -/*! - ***************************************************************************** - * \brief NFC-A T2T Poller Write - * - * This method sends a Write command to a NFC-A T2T Listener device - * - * - * \param[in] blockNum : Number of the block to write - * \param[in] wrData : data to be written on the given block - * size must be of RFAL_T2T_WRITE_DATA_LEN - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT2TPollerWrite(uint8_t blockNum, const uint8_t* wrData); - -/*! - ***************************************************************************** - * \brief NFC-A T2T Poller Sector Select - * - * This method sends a Sector Select commands to a NFC-A T2T Listener device - * - * \param[in] sectorNum : Sector Number - * - * \return ERR_WRONG_STATE : RFAL not initialized or mode not set - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT2TPollerSectorSelect(uint8_t sectorNum); - -#endif /* RFAL_T2T_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/include/rfal_t4t.h b/lib/ST25RFAL002/include/rfal_t4t.h deleted file mode 100644 index 454cad8e0..000000000 --- a/lib/ST25RFAL002/include/rfal_t4t.h +++ /dev/null @@ -1,395 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_t4t.h - * - * \author Gustavo Patricio - * - * \brief Provides convenience methods and definitions for T4T (ISO7816-4) - * - * This module provides an interface to exchange T4T APDUs according to - * NFC Forum T4T and ISO7816-4 - * - * This implementation was based on the following specs: - * - ISO/IEC 7816-4 3rd Edition 2013-04-15 - * - NFC Forum T4T Technical Specification 1.0 2017-08-28 - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-AL - * \brief RFAL Abstraction Layer - * @{ - * - * \addtogroup T4T - * \brief RFAL T4T Module - * @{ - * - */ - -#ifndef RFAL_T4T_H -#define RFAL_T4T_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "platform.h" -#include "st_errno.h" -#include "rfal_rf.h" -#include "rfal_isoDep.h" - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_T4T_MAX_CAPDU_PROLOGUE_LEN \ - 4U /*!< Command-APDU prologue length (CLA INS P1 P2) */ -#define RFAL_T4T_LE_LEN 1U /*!< Le Expected Response Length (short field coding) */ -#define RFAL_T4T_LC_LEN 1U /*!< Lc Data field length (short field coding) */ -#define RFAL_T4T_MAX_RAPDU_SW1SW2_LEN \ - 2U /*!< SW1 SW2 length */ -#define RFAL_T4T_CLA 0x00U /*!< Class byte (contains 00h because secure message are not used) */ - -#define RFAL_T4T_ISO7816_P1_SELECT_BY_DF_NAME \ - 0x04U /*!< P1 value for Select by name */ -#define RFAL_T4T_ISO7816_P1_SELECT_BY_FILEID \ - 0x00U /*!< P1 value for Select by file identifier */ -#define RFAL_T4T_ISO7816_P2_SELECT_FIRST_OR_ONLY_OCCURENCE \ - 0x00U /*!< b2b1 P2 value for First or only occurrence */ -#define RFAL_T4T_ISO7816_P2_SELECT_RETURN_FCI_TEMPLATE \ - 0x00U /*!< b4b3 P2 value for Return FCI template */ -#define RFAL_T4T_ISO7816_P2_SELECT_NO_RESPONSE_DATA \ - 0x0CU /*!< b4b3 P2 value for No response data */ - -#define RFAL_T4T_ISO7816_STATUS_COMPLETE \ - 0x9000U /*!< Command completed \ Normal processing - No further qualification*/ - -/* -****************************************************************************** -* GLOBAL VARIABLES -****************************************************************************** -*/ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ -/*! NFC-A T4T Command-APDU structure */ -typedef struct { - uint8_t CLA; /*!< Class byte */ - uint8_t INS; /*!< Instruction byte */ - uint8_t P1; /*!< Parameter byte 1 */ - uint8_t P2; /*!< Parameter byte 2 */ - uint8_t Lc; /*!< Data field length */ - bool LcFlag; /*!< Lc flag (append Lc when true) */ - uint8_t Le; /*!< Expected Response Length */ - bool LeFlag; /*!< Le flag (append Le when true) */ - - rfalIsoDepApduBufFormat* cApduBuf; /*!< Command-APDU buffer (Tx) */ - uint16_t* cApduLen; /*!< Command-APDU Length */ -} rfalT4tCApduParam; - -/*! NFC-A T4T Response-APDU structure */ -typedef struct { - rfalIsoDepApduBufFormat* rApduBuf; /*!< Response-APDU buffer (Rx) */ - uint16_t rcvdLen; /*!< Full response length */ - uint16_t rApduBodyLen; /*!< Response body length */ - uint16_t statusWord; /*!< R-APDU Status Word SW1|SW2 */ -} rfalT4tRApduParam; - -/*! NFC-A T4T command set T4T 1.0 & ISO7816-4 2013 Table 4 */ -typedef enum { - RFAL_T4T_INS_SELECT = 0xA4U, /*!< T4T Select */ - RFAL_T4T_INS_READBINARY = 0xB0U, /*!< T4T ReadBinary */ - RFAL_T4T_INS_UPDATEBINARY = 0xD6U, /*!< T4T UpdateBinay */ - RFAL_T4T_INS_READBINARY_ODO = 0xB1U, /*!< T4T ReadBinary using ODO */ - RFAL_T4T_INS_UPDATEBINARY_ODO = - 0xD7U /*!< T4T UpdateBinay using ODO */ -} rfalT4tCmds; - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief T4T Compose APDU - * - * This method computes a C-APDU according to NFC Forum T4T and ISO7816-4. - * - * If C-APDU contains data to be sent, it must be placed inside the buffer - * rfalT4tTxRxApduParam.txRx.cApduBuf.apdu and signaled by Lc - * - * To transceive the formed APDU the ISO-DEP layer shall be used - * - * \see rfalIsoDepStartApduTransceive() - * \see rfalIsoDepGetApduTransceiveStatus() - * \see rfalT4TPollerParseRAPDU() - * - * \warning The ISO-DEP module is used to perform the tranceive. Usually - * activation has been done via ISO-DEP activatiavtion. If not - * please call rfalIsoDepInitialize() before. - * - * \param[in,out] apduParam : APDU parameters - * apduParam.cApduLen will contain the APDU length - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT4TPollerComposeCAPDU(const rfalT4tCApduParam* apduParam); - -/*! - ***************************************************************************** - * \brief T4T Parse R-APDU - * - * This method parses a R-APDU according to NFC Forum T4T and ISO7816-4. - * It will extract the data length and check if the Status word is expected. - * - * \param[in,out] apduParam : APDU parameters - * apduParam.rApduBodyLen will contain the data length - * apduParam.statusWord will contain the SW1 and SW2 - * - * \return ERR_REQUEST : Status word (SW1 SW2) different from 9000 - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT4TPollerParseRAPDU(rfalT4tRApduParam* apduParam); - -/*! - ***************************************************************************** - * \brief T4T Compose Select Application APDU - * - * This method computes a Select Application APDU according to NFC Forum T4T - * - * To transceive the formed APDU the ISO-DEP layer shall be used - * - * \see rfalIsoDepStartApduTransceive() - * \see rfalIsoDepGetApduTransceiveStatus() - * - * \param[out] cApduBuf : buffer where the C-APDU will be placed - * \param[in] aid : Application ID to be used - * \param[in] aidLen : Application ID length - * \param[out] cApduLen : Composed C-APDU length - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT4TPollerComposeSelectAppl( - rfalIsoDepApduBufFormat* cApduBuf, - const uint8_t* aid, - uint8_t aidLen, - uint16_t* cApduLen); - -/*! - ***************************************************************************** - * \brief T4T Compose Select File APDU - * - * This method computes a Select File APDU according to NFC Forum T4T - * - * To transceive the formed APDU the ISO-DEP layer shall be used - * - * \see rfalIsoDepStartApduTransceive() - * \see rfalIsoDepGetApduTransceiveStatus() - * - * \param[out] cApduBuf : buffer where the C-APDU will be placed - * \param[in] fid : File ID to be used - * \param[in] fidLen : File ID length - * \param[out] cApduLen : Composed C-APDU length - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT4TPollerComposeSelectFile( - rfalIsoDepApduBufFormat* cApduBuf, - const uint8_t* fid, - uint8_t fidLen, - uint16_t* cApduLen); - -/*! - ***************************************************************************** - * \brief T4T Compose Select File APDU for Mapping Version 1 - * - * This method computes a Select File APDU according to NFC Forum T4TOP_v1.0 - * - * To transceive the formed APDU the ISO-DEP layer shall be used - * - * \see rfalIsoDepStartApduTransceive() - * \see rfalIsoDepGetApduTransceiveStatus() - * - * \param[out] cApduBuf : buffer where the C-APDU will be placed - * \param[in] fid : File ID to be used - * \param[in] fidLen : File ID length - * \param[out] cApduLen : Composed C-APDU length - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT4TPollerComposeSelectFileV1Mapping( - rfalIsoDepApduBufFormat* cApduBuf, - const uint8_t* fid, - uint8_t fidLen, - uint16_t* cApduLen); - -/*! - ***************************************************************************** - * \brief T4T Compose Read Data APDU - * - * This method computes a Read Data APDU according to NFC Forum T4T - * - * To transceive the formed APDU the ISO-DEP layer shall be used - * - * \see rfalIsoDepStartApduTransceive() - * \see rfalIsoDepGetApduTransceiveStatus() - * - * \param[out] cApduBuf : buffer where the C-APDU will be placed - * \param[in] offset : File offset - * \param[in] expLen : Expected length (Le) - * \param[out] cApduLen : Composed C-APDU length - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT4TPollerComposeReadData( - rfalIsoDepApduBufFormat* cApduBuf, - uint16_t offset, - uint8_t expLen, - uint16_t* cApduLen); - -/*! - ***************************************************************************** - * \brief T4T Compose Read Data ODO APDU - * - * This method computes a Read Data ODO APDU according to NFC Forum T4T - * - * To transceive the formed APDU the ISO-DEP layer shall be used - * - * \see rfalIsoDepStartApduTransceive() - * \see rfalIsoDepGetApduTransceiveStatus() - * - * \param[out] cApduBuf : buffer where the C-APDU will be placed - * \param[in] offset : File offset - * \param[in] expLen : Expected length (Le) - * \param[out] cApduLen : Composed C-APDU length - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT4TPollerComposeReadDataODO( - rfalIsoDepApduBufFormat* cApduBuf, - uint32_t offset, - uint8_t expLen, - uint16_t* cApduLen); - -/*! - ***************************************************************************** - * \brief T4T Compose Write Data APDU - * - * This method computes a Write Data APDU according to NFC Forum T4T - * - * To transceive the formed APDU the ISO-DEP layer shall be used - * - * \see rfalIsoDepStartApduTransceive() - * \see rfalIsoDepGetApduTransceiveStatus() - * - * \param[out] cApduBuf : buffer where the C-APDU will be placed - * \param[in] offset : File offset - * \param[in] data : Data to be written - * \param[in] dataLen : Data length to be written (Lc) - * \param[out] cApduLen : Composed C-APDU length - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT4TPollerComposeWriteData( - rfalIsoDepApduBufFormat* cApduBuf, - uint16_t offset, - const uint8_t* data, - uint8_t dataLen, - uint16_t* cApduLen); - -/*! - ***************************************************************************** - * \brief T4T Compose Write Data ODO APDU - * - * This method computes a Write Data ODO sAPDU according to NFC Forum T4T - * - * To transceive the formed APDU the ISO-DEP layer shall be used - * - * \see rfalIsoDepStartApduTransceive() - * \see rfalIsoDepGetApduTransceiveStatus() - * - * \param[out] cApduBuf : buffer where the C-APDU will be placed - * \param[in] offset : File offset - * \param[in] data : Data to be written - * \param[in] dataLen : Data length to be written (Lc) - * \param[out] cApduLen : Composed C-APDU length - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_PROTO : Protocol error - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode rfalT4TPollerComposeWriteDataODO( - rfalIsoDepApduBufFormat* cApduBuf, - uint32_t offset, - const uint8_t* data, - uint8_t dataLen, - uint16_t* cApduLen); - -#endif /* RFAL_T4T_H */ - -/** - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/platform.c b/lib/ST25RFAL002/platform.c deleted file mode 100644 index a97be1c75..000000000 --- a/lib/ST25RFAL002/platform.c +++ /dev/null @@ -1,103 +0,0 @@ -#include "platform.h" -#include -#include -#include - -typedef struct { - FuriThread* thread; - volatile PlatformIrqCallback callback; - bool need_spi_lock; -} RfalPlatform; - -static volatile RfalPlatform rfal_platform = { - .thread = NULL, - .callback = NULL, - .need_spi_lock = true, -}; - -void nfc_isr(void* _ctx) { - UNUSED(_ctx); - if(rfal_platform.callback && platformGpioIsHigh(ST25R_INT_PORT, ST25R_INT_PIN)) { - furi_thread_flags_set(furi_thread_get_id(rfal_platform.thread), 0x1); - } -} - -int32_t rfal_platform_irq_thread(void* context) { - UNUSED(context); - - while(1) { - uint32_t flags = furi_thread_flags_wait(0x1, FuriFlagWaitAny, FuriWaitForever); - if(flags & 0x1) { - rfal_platform.callback(); - } - } -} - -void platformEnableIrqCallback() { - furi_hal_gpio_init(&gpio_nfc_irq_rfid_pull, GpioModeInterruptRise, GpioPullDown, GpioSpeedLow); - furi_hal_gpio_enable_int_callback(&gpio_nfc_irq_rfid_pull); -} - -void platformDisableIrqCallback() { - furi_hal_gpio_init(&gpio_nfc_irq_rfid_pull, GpioModeOutputOpenDrain, GpioPullNo, GpioSpeedLow); - furi_hal_gpio_disable_int_callback(&gpio_nfc_irq_rfid_pull); -} - -void platformSetIrqCallback(PlatformIrqCallback callback) { - rfal_platform.callback = callback; - - if(!rfal_platform.thread) { - rfal_platform.thread = - furi_thread_alloc_ex("RfalIrqDriver", 1024, rfal_platform_irq_thread, NULL); - furi_thread_mark_as_service(rfal_platform.thread); - furi_thread_set_priority(rfal_platform.thread, FuriThreadPriorityIsr); - furi_thread_start(rfal_platform.thread); - } - - furi_hal_gpio_add_int_callback(&gpio_nfc_irq_rfid_pull, nfc_isr, NULL); - // Disable interrupt callback as the pin is shared between 2 apps - // It is enabled in rfalLowPowerModeStop() - furi_hal_gpio_disable_int_callback(&gpio_nfc_irq_rfid_pull); -} - -bool platformSpiTxRx(const uint8_t* txBuf, uint8_t* rxBuf, uint16_t len) { - bool ret = false; - if(txBuf && rxBuf) { - ret = - furi_hal_spi_bus_trx(&furi_hal_spi_bus_handle_nfc, (uint8_t*)txBuf, rxBuf, len, 1000); - } else if(txBuf) { - ret = furi_hal_spi_bus_tx(&furi_hal_spi_bus_handle_nfc, (uint8_t*)txBuf, len, 1000); - } else if(rxBuf) { - ret = furi_hal_spi_bus_rx(&furi_hal_spi_bus_handle_nfc, (uint8_t*)rxBuf, len, 1000); - } - - return ret; -} - -// Until we completely remove RFAL, NFC works with SPI from rfal_platform_irq_thread and nfc_worker -// threads. Some nfc features already stop using RFAL and work with SPI from nfc_worker only. -// rfal_platform_spi_acquire() and rfal_platform_spi_release() functions are used to lock SPI for a -// long term without locking it for each SPI transaction. This is needed for time critical communications. -void rfal_platform_spi_acquire() { - platformDisableIrqCallback(); - rfal_platform.need_spi_lock = false; - furi_hal_spi_acquire(&furi_hal_spi_bus_handle_nfc); -} - -void rfal_platform_spi_release() { - furi_hal_spi_release(&furi_hal_spi_bus_handle_nfc); - rfal_platform.need_spi_lock = true; - platformEnableIrqCallback(); -} - -void platformProtectST25RComm() { - if(rfal_platform.need_spi_lock) { - furi_hal_spi_acquire(&furi_hal_spi_bus_handle_nfc); - } -} - -void platformUnprotectST25RComm() { - if(rfal_platform.need_spi_lock) { - furi_hal_spi_release(&furi_hal_spi_bus_handle_nfc); - } -} diff --git a/lib/ST25RFAL002/platform.h b/lib/ST25RFAL002/platform.h deleted file mode 100644 index d86bba73e..000000000 --- a/lib/ST25RFAL002/platform.h +++ /dev/null @@ -1,188 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include "timer.h" -#include "math.h" -#include -#include -#include - -typedef void (*PlatformIrqCallback)(); -void platformSetIrqCallback(PlatformIrqCallback cb); -void platformEnableIrqCallback(); -void platformDisableIrqCallback(); - -bool platformSpiTxRx(const uint8_t* txBuf, uint8_t* rxBuf, uint16_t len); -void platformProtectST25RComm(); -void platformUnprotectST25RComm(); -void rfal_platform_spi_acquire(); -void rfal_platform_spi_release(); - -#define ST25R_SS_PIN NFC_CS_Pin -#define ST25R_SS_PORT NFC_CS_GPIO_Port - -#define ST25R_INT_PIN NFC_IRQ_Pin -#define ST25R_INT_PORT NFC_IRQ_GPIO_Port - -#define RFAL_ANALOG_CONFIG_CUSTOM \ - true /*!< Enable/Disable RFAL custom analog configuration */ - -#define RFAL_FEATURE_LISTEN_MODE \ - true /*!< Enable/Disable RFAL support for Listen Mode */ -#define RFAL_FEATURE_WAKEUP_MODE \ - true /*!< Enable/Disable RFAL support for the Wake-Up mode */ -#define RFAL_FEATURE_LOWPOWER_MODE \ - true /*!< Enable/Disable RFAL support for the Low Power mode */ -#define RFAL_FEATURE_NFCA \ - true /*!< Enable/Disable RFAL support for NFC-A (ISO14443A) */ -#define RFAL_FEATURE_NFCB \ - true /*!< Enable/Disable RFAL support for NFC-B (ISO14443B) */ -#define RFAL_FEATURE_NFCF \ - true /*!< Enable/Disable RFAL support for NFC-F (FeliCa) */ -#define RFAL_FEATURE_NFCV \ - true /*!< Enable/Disable RFAL support for NFC-V (ISO15693) */ -#define RFAL_FEATURE_T1T \ - true /*!< Enable/Disable RFAL support for T1T (Topaz) */ -#define RFAL_FEATURE_T2T \ - true /*!< Enable/Disable RFAL support for T2T (MIFARE Ultralight) */ -#define RFAL_FEATURE_T4T \ - true /*!< Enable/Disable RFAL support for T4T */ -#define RFAL_FEATURE_ST25TB \ - true /*!< Enable/Disable RFAL support for ST25TB */ -#define RFAL_FEATURE_ST25xV \ - true /*!< Enable/Disable RFAL support for ST25TV/ST25DV */ -#define RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG \ - false /*!< Enable/Disable Analog Configs to be dynamically updated (RAM) */ -#define RFAL_FEATURE_DPO \ - false /*!< Enable/Disable RFAL Dynamic Power Output upport */ -#define RFAL_FEATURE_ISO_DEP \ - true /*!< Enable/Disable RFAL support for ISO-DEP (ISO14443-4) */ -#define RFAL_FEATURE_ISO_DEP_POLL \ - true /*!< Enable/Disable RFAL support for Poller mode (PCD) ISO-DEP (ISO14443-4) */ -#define RFAL_FEATURE_ISO_DEP_LISTEN \ - true /*!< Enable/Disable RFAL support for Listen mode (PICC) ISO-DEP (ISO14443-4) */ -#define RFAL_FEATURE_NFC_DEP \ - true /*!< Enable/Disable RFAL support for NFC-DEP (NFCIP1/P2P) */ - -#define RFAL_FEATURE_ISO_DEP_IBLOCK_MAX_LEN \ - 256U /*!< ISO-DEP I-Block max length. Please use values as defined by rfalIsoDepFSx */ -#define RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN \ - 254U /*!< NFC-DEP Block/Payload length. Allowed values: 64, 128, 192, 254 */ -#define RFAL_FEATURE_NFC_RF_BUF_LEN \ - 256U /*!< RF buffer length used by RFAL NFC layer */ - -#define RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN \ - 512U /*!< ISO-DEP APDU max length. */ -#define RFAL_FEATURE_NFC_DEP_PDU_MAX_LEN \ - 512U /*!< NFC-DEP PDU max length. */ - -#define platformIrqST25RSetCallback(cb) platformSetIrqCallback(cb) - -#define platformProtectST25RIrqStatus() \ - platformProtectST25RComm() /*!< Protect unique access to IRQ status var - IRQ disable on single thread environment (MCU) ; Mutex lock on a multi thread environment */ -#define platformUnprotectST25RIrqStatus() \ - platformUnprotectST25RComm() /*!< Unprotect the IRQ status var - IRQ enable on a single thread environment (MCU) ; Mutex unlock on a multi thread environment */ - -#define platformGpioSet(port, pin) \ - furi_hal_gpio_write_port_pin( \ - port, pin, true) /*!< Turns the given GPIO High */ -#define platformGpioClear(port, pin) \ - furi_hal_gpio_write_port_pin( \ - port, pin, false) /*!< Turns the given GPIO Low */ - -#define platformGpioIsHigh(port, pin) \ - (furi_hal_gpio_read_port_pin(port, pin) == \ - true) /*!< Checks if the given LED is High */ -#define platformGpioIsLow(port, pin) \ - (!platformGpioIsHigh(port, pin)) /*!< Checks if the given LED is Low */ - -#define platformTimerCreate(t) \ - timerCalculateTimer(t) /*!< Create a timer with the given time (ms) */ -#define platformTimerIsExpired(timer) \ - timerIsExpired(timer) /*!< Checks if the given timer is expired */ -#define platformDelay(t) furi_delay_ms(t) /*!< Performs a delay for the given time (ms) */ - -#define platformGetSysTick() furi_get_tick() /*!< Get System Tick (1 tick = 1 ms) */ - -#define platformAssert(exp) assert_param(exp) /*!< Asserts whether the given expression is true*/ - -#define platformSpiSelect() \ - platformGpioClear( \ - ST25R_SS_PORT, ST25R_SS_PIN) /*!< SPI SS\CS: Chip|Slave Select */ -#define platformSpiDeselect() \ - platformGpioSet( \ - ST25R_SS_PORT, ST25R_SS_PIN) /*!< SPI SS\CS: Chip|Slave Deselect */ - -#define platformI2CTx(txBuf, len, last, txOnly) /*!< I2C Transmit */ -#define platformI2CRx(txBuf, len) /*!< I2C Receive */ -#define platformI2CStart() /*!< I2C Start condition */ -#define platformI2CStop() /*!< I2C Stop condition */ -#define platformI2CRepeatStart() /*!< I2C Repeat Start */ -#define platformI2CSlaveAddrWR(add) /*!< I2C Slave address for Write operation */ -#define platformI2CSlaveAddrRD(add) /*!< I2C Slave address for Read operation */ - -#define platformLog(...) /*!< Log method */ - -/* - ****************************************************************************** - * RFAL OPTIONAL MACROS (Do not change) - ****************************************************************************** - */ -#ifndef platformProtectST25RIrqStatus -#define platformProtectST25RIrqStatus() /*!< Protect unique access to IRQ status var - IRQ disable on single thread environment (MCU) ; Mutex lock on a multi thread environment */ -#endif /* platformProtectST25RIrqStatus */ - -#ifndef platformUnprotectST25RIrqStatus -#define platformUnprotectST25RIrqStatus() /*!< Unprotect the IRQ status var - IRQ enable on a single thread environment (MCU) ; Mutex unlock on a multi thread environment */ -#endif /* platformUnprotectST25RIrqStatus */ - -#ifndef platformProtectWorker -#define platformProtectWorker() /* Protect RFAL Worker/Task/Process from concurrent execution on multi thread platforms */ -#endif /* platformProtectWorker */ - -#ifndef platformUnprotectWorker -#define platformUnprotectWorker() /* Unprotect RFAL Worker/Task/Process from concurrent execution on multi thread platforms */ -#endif /* platformUnprotectWorker */ - -#ifndef platformIrqST25RPinInitialize -#define platformIrqST25RPinInitialize() /*!< Initializes ST25R IRQ pin */ -#endif /* platformIrqST25RPinInitialize */ - -#ifndef platformIrqST25RSetCallback -#define platformIrqST25RSetCallback(cb) /*!< Sets ST25R ISR callback */ -#endif /* platformIrqST25RSetCallback */ - -#ifndef platformLedsInitialize -#define platformLedsInitialize() /*!< Initializes the pins used as LEDs to outputs */ -#endif /* platformLedsInitialize */ - -#ifndef platformLedOff -#define platformLedOff(port, pin) /*!< Turns the given LED Off */ -#endif /* platformLedOff */ - -#ifndef platformLedOn -#define platformLedOn(port, pin) /*!< Turns the given LED On */ -#endif /* platformLedOn */ - -#ifndef platformLedToogle -#define platformLedToogle(port, pin) /*!< Toggles the given LED */ -#endif /* platformLedToogle */ - -#ifndef platformGetSysTick -#define platformGetSysTick() /*!< Get System Tick (1 tick = 1 ms) */ -#endif /* platformGetSysTick */ - -#ifndef platformTimerDestroy -#define platformTimerDestroy(timer) /*!< Stops and released the given timer */ -#endif /* platformTimerDestroy */ - -#ifndef platformAssert -#define platformAssert(exp) /*!< Asserts whether the given expression is true */ -#endif /* platformAssert */ - -#ifndef platformErrorHandle -#define platformErrorHandle() /*!< Global error handler or trap */ -#endif /* platformErrorHandle */ diff --git a/lib/ST25RFAL002/source/custom_analog_config.c b/lib/ST25RFAL002/source/custom_analog_config.c deleted file mode 100644 index 00a54db26..000000000 --- a/lib/ST25RFAL002/source/custom_analog_config.c +++ /dev/null @@ -1,777 +0,0 @@ -#include "rfal_analogConfigTbl.h" - -const uint8_t rfalAnalogConfigCustomSettings[] = { - /****** Default Analog Configuration for Chip-Specific Reset ******/ - MODE_ENTRY_16_REG( - (RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_INIT), - ST25R3916_REG_IO_CONF1, - (ST25R3916_REG_IO_CONF1_out_cl_mask | ST25R3916_REG_IO_CONF1_lf_clk_off), - 0x07 /* Disable MCU_CLK */ - , - ST25R3916_REG_IO_CONF2, - (ST25R3916_REG_IO_CONF2_miso_pd1 | ST25R3916_REG_IO_CONF2_miso_pd2), - 0x18 /* SPI Pull downs */ - // , ST25R3916_REG_IO_CONF2, ST25R3916_REG_IO_CONF2_aat_en, ST25R3916_REG_IO_CONF2_aat_en /* Enable AAT */ - , - ST25R3916_REG_TX_DRIVER, - ST25R3916_REG_TX_DRIVER_d_res_mask, - 0x00 /* Set RFO resistance Active Tx */ - , - ST25R3916_REG_RES_AM_MOD, - 0xFF, - 0x80 /* Use minimum non-overlap */ - , - ST25R3916_REG_FIELD_THRESHOLD_ACTV, - ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_mask, - ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_105mV /* Lower activation threshold (higher than deactivation)*/ - , - ST25R3916_REG_FIELD_THRESHOLD_ACTV, - ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_mask, - ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_105mV /* Lower activation threshold (higher than deactivation)*/ - , - ST25R3916_REG_FIELD_THRESHOLD_DEACTV, - ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_mask, - ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_75mV /* Lower deactivation threshold */ - , - ST25R3916_REG_FIELD_THRESHOLD_DEACTV, - ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_mask, - ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_75mV /* Lower deactivation threshold */ - , - ST25R3916_REG_AUX_MOD, - ST25R3916_REG_AUX_MOD_lm_ext, - ST25R3916_REG_AUX_MOD_lm_ext /* Disable External Load Modulation */ - , - ST25R3916_REG_AUX_MOD, - ST25R3916_REG_AUX_MOD_lm_dri, - ST25R3916_REG_AUX_MOD_lm_dri /* Use internal Load Modulation */ - , - ST25R3916_REG_PASSIVE_TARGET, - ST25R3916_REG_PASSIVE_TARGET_fdel_mask, - (5U - << ST25R3916_REG_PASSIVE_TARGET_fdel_shift) /* Adjust the FDT to be aligned with the bitgrid */ - , - ST25R3916_REG_PT_MOD, - (ST25R3916_REG_PT_MOD_ptm_res_mask | ST25R3916_REG_PT_MOD_pt_res_mask), - 0x0f /* Reduce RFO resistance in Modulated state */ - , - ST25R3916_REG_EMD_SUP_CONF, - ST25R3916_REG_EMD_SUP_CONF_rx_start_emv, - ST25R3916_REG_EMD_SUP_CONF_rx_start_emv_on /* Enable start on first 4 bits */ - , - ST25R3916_REG_ANT_TUNE_A, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_ANT_TUNE_B, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - 0x84U, - 0x10, - 0x10 /* Avoid chip internal overheat protection */ - ) - - /****** Default Analog Configuration for Chip-Specific Poll Common ******/ - , - MODE_ENTRY_9_REG( - (RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_POLL_COMMON), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - , - ST25R3916_REG_TX_DRIVER, - ST25R3916_REG_TX_DRIVER_am_mod_mask, - ST25R3916_REG_TX_DRIVER_am_mod_12percent /* Set Modulation index */ - , - ST25R3916_REG_AUX_MOD, - (ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am), - 0x00 /* Use AM via regulator */ - , - ST25R3916_REG_ANT_TUNE_A, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_ANT_TUNE_B, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx Common ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_correlator /* Use Correlator Receiver */ - ) - - /****** Default Analog Configuration for Poll NFC-A Tx 106 ******/ - , - MODE_ENTRY_5_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_106 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_ook /* Use OOK */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx 106 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_106 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x08, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x2D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x51, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-A Tx 212 ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_212 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - , - ST25R3916_REG_AUX_MOD, - (ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am), - 0x88 /* Use Resistive AM */ - , - ST25R3916_REG_RES_AM_MOD, - ST25R3916_REG_RES_AM_MOD_md_res_mask, - 0x7F /* Set Resistive modulation */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx 212 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_212 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x02, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x14, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-A Tx 424 ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_424 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - , - ST25R3916_REG_AUX_MOD, - (ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am), - 0x88 /* Use Resistive AM */ - , - ST25R3916_REG_RES_AM_MOD, - ST25R3916_REG_RES_AM_MOD_md_res_mask, - 0x7F /* Set Resistive modulation */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx 424 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_424 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x42, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x54, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-A Tx 848 ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_848 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - , - ST25R3916_REG_TX_DRIVER, - ST25R3916_REG_TX_DRIVER_am_mod_mask, - ST25R3916_REG_TX_DRIVER_am_mod_40percent /* Set Modulation index */ - , - ST25R3916_REG_AUX_MOD, - (ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am), - 0x00 /* Use AM via regulator */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx 848 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_848 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x42, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x44, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-A Anticolision setting ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_ANTICOL), - ST25R3916_REG_CORR_CONF1, - ST25R3916_REG_CORR_CONF1_corr_s6, - 0x00 /* Set collision detection level different from data */ - ) - -#ifdef RFAL_USE_COHE - /****** Default Analog Configuration for Poll NFC-B Rx Common ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_coherent /* Use Coherent Receiver */ - ) -#else - /****** Default Analog Configuration for Poll NFC-B Rx Common ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_correlator /* Use Correlator Receiver */ - ) -#endif /*RFAL_USE_COHE*/ - - /****** Default Analog Configuration for Poll NFC-B Rx 106 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | RFAL_ANALOG_CONFIG_BITRATE_106 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x04, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x1B, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-B Rx 212 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | RFAL_ANALOG_CONFIG_BITRATE_212 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x02, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x14, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-B Rx 424 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | RFAL_ANALOG_CONFIG_BITRATE_424 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x42, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x54, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-B Rx 848 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | RFAL_ANALOG_CONFIG_BITRATE_848 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x42, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x44, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) -#ifdef RFAL_USE_COHE - - /****** Default Analog Configuration for Poll NFC-F Rx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCF | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_coherent /* Use Pulse Receiver */ - , - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x54, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) -#else - /****** Default Analog Configuration for Poll NFC-F Rx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCF | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_correlator /* Use Correlator Receiver */ - , - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x54, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) -#endif /*RFAL_USE_COHE*/ - - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | RFAL_ANALOG_CONFIG_BITRATE_1OF4 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_ook /* Use OOK */ - ) - -#ifdef RFAL_USE_COHE - /****** Default Analog Configuration for Poll NFC-V Rx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_coherent /* Use Pulse Receiver */ - , - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x2D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x01) -#else - /****** Default Analog Configuration for Poll NFC-V Rx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_correlator /* Use Correlator Receiver */ - , - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x2D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x01) -#endif /*RFAL_USE_COHE*/ - - /****** Default Analog Configuration for Poll AP2P Tx 106 ******/ - , - MODE_ENTRY_5_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | RFAL_ANALOG_CONFIG_BITRATE_106 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_ook /* Use OOK modulation */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll AP2P Tx 212 ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | RFAL_ANALOG_CONFIG_BITRATE_212 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - ) - - /****** Default Analog Configuration for Poll AP2P Tx 424 ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | RFAL_ANALOG_CONFIG_BITRATE_424 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - ) - - /****** Default Analog Configuration for Chip-Specific Listen On ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_LISTEN_ON), - ST25R3916_REG_ANT_TUNE_A, - 0xFF, - 0x00 /* Set Antenna Tuning (Listener): ANTL */ - , - ST25R3916_REG_ANT_TUNE_B, - 0xFF, - 0xff /* Set Antenna Tuning (Listener): ANTL */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - ) - - /****** Default Analog Configuration for Listen AP2P Tx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_ANT_TUNE_A, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_ANT_TUNE_B, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_TX_DRIVER, - ST25R3916_REG_TX_DRIVER_am_mod_mask, - ST25R3916_REG_TX_DRIVER_am_mod_12percent /* Set Modulation index */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - ) - - /****** Default Analog Configuration for Listen AP2P Rx Common ******/ - , - MODE_ENTRY_3_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - ST25R3916_REG_RX_CONF1_lp_mask, - ST25R3916_REG_RX_CONF1_lp_1200khz /* Set Rx filter configuration */ - , - ST25R3916_REG_RX_CONF1, - ST25R3916_REG_RX_CONF1_hz_mask, - ST25R3916_REG_RX_CONF1_hz_12_200khz /* Set Rx filter configuration */ - , - ST25R3916_REG_RX_CONF2, - ST25R3916_REG_RX_CONF2_amd_sel, - ST25R3916_REG_RX_CONF2_amd_sel_mixer /* AM demodulator: mixer */ - ) - - /****** Default Analog Configuration for Listen AP2P Tx 106 ******/ - , - MODE_ENTRY_5_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_106 | RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_ook /* Use OOK modulation */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Listen AP2P Tx 212 ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_212 | RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - ) - - /****** Default Analog Configuration for Listen AP2P Tx 424 ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_424 | RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - ) - -}; - -const uint16_t rfalAnalogConfigCustomSettingsLength = sizeof(rfalAnalogConfigCustomSettings); diff --git a/lib/ST25RFAL002/source/rfal_analogConfig.c b/lib/ST25RFAL002/source/rfal_analogConfig.c deleted file mode 100644 index 1058dd328..000000000 --- a/lib/ST25RFAL002/source/rfal_analogConfig.c +++ /dev/null @@ -1,476 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_analogConfig.c - * - * \author bkam - * - * \brief Functions to manage and set analog settings. - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_analogConfig.h" -#include "rfal_chip.h" -#include "st_errno.h" -#include "platform.h" -#include "utils.h" - -/* Check whether the Default Analog settings are to be used or custom ones */ -#ifdef RFAL_ANALOG_CONFIG_CUSTOM -extern const uint8_t* rfalAnalogConfigCustomSettings; -extern const uint16_t rfalAnalogConfigCustomSettingsLength; -#else -#include "rfal_analogConfigTbl.h" -#endif - -/* - ****************************************************************************** - * DEFINES - ****************************************************************************** - */ - -#define RFAL_TEST_REG 0x0080U /*!< Test Register indicator */ - -/* - ****************************************************************************** - * MACROS - ****************************************************************************** - */ - -/* - ****************************************************************************** - * LOCAL DATA TYPES - ****************************************************************************** - */ - -#if RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG -static uint8_t - gRfalAnalogConfig[RFAL_ANALOG_CONFIG_TBL_SIZE]; /*!< Analog Configuration Settings List */ -#endif /* RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG */ - -/*! Struct for Analog Config Look Up Table Update */ -typedef struct { - const uint8_t* - currentAnalogConfigTbl; /*!< Reference to start of current Analog Configuration */ - uint16_t configTblSize; /*!< Total size of Analog Configuration */ - bool ready; /*!< Indicate if Look Up Table is complete and ready for use */ -} rfalAnalogConfigMgmt; - -static rfalAnalogConfigMgmt gRfalAnalogConfigMgmt; /*!< Analog Configuration LUT management */ - -/* - ****************************************************************************** - * LOCAL TABLES - ****************************************************************************** - */ - -/* - ****************************************************************************** - * LOCAL FUNCTION PROTOTYPES - ****************************************************************************** - */ -static rfalAnalogConfigNum - rfalAnalogConfigSearch(rfalAnalogConfigId configId, uint16_t* configOffset); - -#if RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG -static void rfalAnalogConfigPtrUpdate(const uint8_t* analogConfigTbl); -#endif /* RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG */ - -/* - ****************************************************************************** - * GLOBAL VARIABLE DEFINITIONS - ****************************************************************************** - */ - -/* - ****************************************************************************** - * GLOBAL FUNCTIONS - ****************************************************************************** - */ - -void rfalAnalogConfigInitialize(void) { - /* Use default Analog configuration settings in Flash by default. */ - -/* Check whether the Default Analog settings are to be used or custom ones */ -#ifdef RFAL_ANALOG_CONFIG_CUSTOM - gRfalAnalogConfigMgmt.currentAnalogConfigTbl = (const uint8_t*)&rfalAnalogConfigCustomSettings; - gRfalAnalogConfigMgmt.configTblSize = rfalAnalogConfigCustomSettingsLength; -#else - gRfalAnalogConfigMgmt.currentAnalogConfigTbl = - (const uint8_t*)&rfalAnalogConfigDefaultSettings; - gRfalAnalogConfigMgmt.configTblSize = sizeof(rfalAnalogConfigDefaultSettings); -#endif - - gRfalAnalogConfigMgmt.ready = true; -} /* rfalAnalogConfigInitialize() */ - -bool rfalAnalogConfigIsReady(void) { - return gRfalAnalogConfigMgmt.ready; -} - -ReturnCode rfalAnalogConfigListWriteRaw(const uint8_t* configTbl, uint16_t configTblSize) { -#if RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG - - /* Check if the Configuration Table exceed the Table size */ - if(configTblSize >= RFAL_ANALOG_CONFIG_TBL_SIZE) { - rfalAnalogConfigInitialize(); /* Revert to default Analog Configuration */ - return ERR_NOMEM; - } - - /* Check for invalid parameters */ - if((configTbl == NULL) || (configTblSize == 0U)) { - return ERR_PARAM; - } - - /* NOTE: Function does not check for the validity of the Table contents (conf IDs, conf sets, register address) */ - ST_MEMCPY(gRfalAnalogConfig, configTbl, configTblSize); - - /* Update the total size of configuration settings */ - gRfalAnalogConfigMgmt.configTblSize = configTblSize; - - rfalAnalogConfigPtrUpdate(gRfalAnalogConfig); - return ERR_NONE; - -#else - - // If Analog Configuration Update is to be disabled - NO_WARNING(configTbl); - NO_WARNING(configTblSize); - return ERR_REQUEST; - -#endif /* RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG */ -} - -ReturnCode rfalAnalogConfigListWrite(uint8_t more, const rfalAnalogConfig* config) { -#if RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG - - rfalAnalogConfigId configId; - rfalAnalogConfigNum numConfig; - uint8_t configSize; - - if(true == gRfalAnalogConfigMgmt.ready) { /* First Update to the Configuration list. */ - gRfalAnalogConfigMgmt.ready = false; // invalidate the config List - gRfalAnalogConfigMgmt.configTblSize = 0; // Clear the config List - } - - configId = GETU16(config->id); - - /* Check validity of the Configuration ID. */ - if((RFAL_ANALOG_CONFIG_TECH_RFU <= RFAL_ANALOG_CONFIG_ID_GET_TECH(configId)) || - ((RFAL_ANALOG_CONFIG_BITRATE_6780 < RFAL_ANALOG_CONFIG_ID_GET_BITRATE(configId)) && - (RFAL_ANALOG_CONFIG_BITRATE_1OF4 > RFAL_ANALOG_CONFIG_ID_GET_BITRATE(configId))) || - (RFAL_ANALOG_CONFIG_BITRATE_1OF256 < RFAL_ANALOG_CONFIG_ID_GET_BITRATE(configId))) { - rfalAnalogConfigInitialize(); /* Revert to default Analog Configuration */ - return ERR_PARAM; - } - - numConfig = config->num; - configSize = - (uint8_t)(sizeof(rfalAnalogConfigId) + sizeof(rfalAnalogConfigNum) + (numConfig * sizeof(rfalAnalogConfigRegAddrMaskVal))); - - /* Check if the Configuration Set exceed the Table size. */ - if(RFAL_ANALOG_CONFIG_TBL_SIZE <= (gRfalAnalogConfigMgmt.configTblSize + configSize)) { - rfalAnalogConfigInitialize(); /* Revert to default Analog Configuration */ - return ERR_NOMEM; - } - - /* NOTE: Function does not check for the validity of the Register Address. */ - ST_MEMCPY( - &gRfalAnalogConfig[gRfalAnalogConfigMgmt.configTblSize], - (const uint8_t*)config, - configSize); - - /* Increment the total size of configuration settings. */ - gRfalAnalogConfigMgmt.configTblSize += configSize; - - /* Check if it is the last Analog Configuration to load. */ - if(RFAL_ANALOG_CONFIG_UPDATE_LAST == - more) { /* Update the Analog Configuration to the new settings. */ - rfalAnalogConfigPtrUpdate(gRfalAnalogConfig); - } - - return ERR_NONE; - -#else - - // If Analog Configuration Update is to be disabled - NO_WARNING(config); - NO_WARNING(more); - return ERR_DISABLED; - -#endif /* RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG */ - -} /* rfalAnalogConfigListUpdate() */ - -ReturnCode - rfalAnalogConfigListReadRaw(uint8_t* tblBuf, uint16_t tblBufLen, uint16_t* configTblSize) { - /* Check if the the current table will fit into the given buffer */ - if(tblBufLen < gRfalAnalogConfigMgmt.configTblSize) { - return ERR_NOMEM; - } - - /* Check for invalid parameters */ - if(configTblSize == NULL) { - return ERR_PARAM; - } - - /* Copy the whole Table to the given buffer */ - if(gRfalAnalogConfigMgmt.configTblSize > 0U) /* MISRA 21.18 */ - { - ST_MEMCPY( - tblBuf, - gRfalAnalogConfigMgmt.currentAnalogConfigTbl, - gRfalAnalogConfigMgmt.configTblSize); - } - *configTblSize = gRfalAnalogConfigMgmt.configTblSize; - - return ERR_NONE; -} - -ReturnCode rfalAnalogConfigListRead( - rfalAnalogConfigOffset* configOffset, - uint8_t* more, - rfalAnalogConfig* config, - rfalAnalogConfigNum numConfig) { - uint16_t configSize; - rfalAnalogConfigOffset offset = *configOffset; - rfalAnalogConfigNum numConfigSet; - - /* Check if the number of register-mask-value settings for the respective Configuration ID will fit into the buffer passed in. */ - if(gRfalAnalogConfigMgmt.currentAnalogConfigTbl[offset + sizeof(rfalAnalogConfigId)] > - numConfig) { - return ERR_NOMEM; - } - - /* Get the number of Configuration set */ - numConfigSet = - gRfalAnalogConfigMgmt.currentAnalogConfigTbl[offset + sizeof(rfalAnalogConfigId)]; - - /* Pass Configuration Register-Mask-Value sets */ - configSize = - (sizeof(rfalAnalogConfigId) + sizeof(rfalAnalogConfigNum) + - (uint16_t)(numConfigSet * sizeof(rfalAnalogConfigRegAddrMaskVal))); - ST_MEMCPY((uint8_t*)config, &gRfalAnalogConfigMgmt.currentAnalogConfigTbl[offset], configSize); - *configOffset = offset + configSize; - - /* Check if it is the last Analog Configuration in the Table.*/ - *more = - (uint8_t)((*configOffset >= gRfalAnalogConfigMgmt.configTblSize) ? RFAL_ANALOG_CONFIG_UPDATE_LAST : RFAL_ANALOG_CONFIG_UPDATE_MORE); - - return ERR_NONE; -} /* rfalAnalogConfigListRead() */ - -ReturnCode rfalSetAnalogConfig(rfalAnalogConfigId configId) { - rfalAnalogConfigOffset configOffset = 0; - rfalAnalogConfigNum numConfigSet; - const rfalAnalogConfigRegAddrMaskVal* configTbl; - ReturnCode retCode = ERR_NONE; - rfalAnalogConfigNum i; - - if(true != gRfalAnalogConfigMgmt.ready) { - return ERR_REQUEST; - } - - /* Search LUT for the specific Configuration ID. */ - while(true) { - numConfigSet = rfalAnalogConfigSearch(configId, &configOffset); - if(RFAL_ANALOG_CONFIG_LUT_NOT_FOUND == numConfigSet) { - break; - } - - configTbl = - (rfalAnalogConfigRegAddrMaskVal*)((uint32_t)gRfalAnalogConfigMgmt.currentAnalogConfigTbl + (uint32_t)configOffset); - /* Increment the offset to the next index to search from. */ - configOffset += (uint16_t)(numConfigSet * sizeof(rfalAnalogConfigRegAddrMaskVal)); - - if((gRfalAnalogConfigMgmt.configTblSize + 1U) < - configOffset) { /* Error check make sure that the we do not access outside the configuration Table Size */ - return ERR_NOMEM; - } - - for(i = 0; i < numConfigSet; i++) { - if((GETU16(configTbl[i].addr) & RFAL_TEST_REG) != 0U) { - EXIT_ON_ERR( - retCode, - rfalChipChangeTestRegBits( - (GETU16(configTbl[i].addr) & ~RFAL_TEST_REG), - configTbl[i].mask, - configTbl[i].val)); - } else { - EXIT_ON_ERR( - retCode, - rfalChipChangeRegBits( - GETU16(configTbl[i].addr), configTbl[i].mask, configTbl[i].val)); - } - } - - } /* while(found Analog Config Id) */ - - return retCode; - -} /* rfalSetAnalogConfig() */ - -uint16_t rfalAnalogConfigGenModeID(rfalMode md, rfalBitRate br, uint16_t dir) { - uint16_t id; - - /* Assign Poll/Listen Mode */ - id = ((md >= RFAL_MODE_LISTEN_NFCA) ? RFAL_ANALOG_CONFIG_LISTEN : RFAL_ANALOG_CONFIG_POLL); - - /* Assign Technology */ - switch(md) { - case RFAL_MODE_POLL_NFCA: - case RFAL_MODE_POLL_NFCA_T1T: - case RFAL_MODE_LISTEN_NFCA: - id |= RFAL_ANALOG_CONFIG_TECH_NFCA; - break; - - case RFAL_MODE_POLL_NFCB: - case RFAL_MODE_POLL_B_PRIME: - case RFAL_MODE_POLL_B_CTS: - case RFAL_MODE_LISTEN_NFCB: - id |= RFAL_ANALOG_CONFIG_TECH_NFCB; - break; - - case RFAL_MODE_POLL_NFCF: - case RFAL_MODE_LISTEN_NFCF: - id |= RFAL_ANALOG_CONFIG_TECH_NFCF; - break; - - case RFAL_MODE_POLL_NFCV: - case RFAL_MODE_POLL_PICOPASS: - id |= RFAL_ANALOG_CONFIG_TECH_NFCV; - break; - - case RFAL_MODE_POLL_ACTIVE_P2P: - case RFAL_MODE_LISTEN_ACTIVE_P2P: - id |= RFAL_ANALOG_CONFIG_TECH_AP2P; - break; - - default: - id = RFAL_ANALOG_CONFIG_TECH_CHIP; - break; - } - - /* Assign Bitrate */ - id |= - (((((uint16_t)(br) >= (uint16_t)RFAL_BR_52p97) ? (uint16_t)(br) : ((uint16_t)(br) + 1U)) - << RFAL_ANALOG_CONFIG_BITRATE_SHIFT) & - RFAL_ANALOG_CONFIG_BITRATE_MASK); - - /* Assign Direction */ - id |= ((dir << RFAL_ANALOG_CONFIG_DIRECTION_SHIFT) & RFAL_ANALOG_CONFIG_DIRECTION_MASK); - - return id; - -} /* rfalAnalogConfigGenModeID() */ - -/* - ****************************************************************************** - * LOCAL FUNCTIONS - ****************************************************************************** - */ - -/*! - ***************************************************************************** - * \brief Update the link to Analog Configuration LUT - * - * Update the link to the Analog Configuration LUT for the subsequent search - * of Analog Settings. - * - * \param[in] analogConfigTbl: reference to the start of the new Analog Configuration Table - * - ***************************************************************************** - */ -#if RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG -static void rfalAnalogConfigPtrUpdate(const uint8_t* analogConfigTbl) { - gRfalAnalogConfigMgmt.currentAnalogConfigTbl = analogConfigTbl; - gRfalAnalogConfigMgmt.ready = true; - -} /* rfalAnalogConfigPtrUpdate() */ -#endif /* RFAL_FEATURE_DYNAMIC_ANALOG_CONFIG */ - -/*! - ***************************************************************************** - * \brief Search the Analog Configuration LUT for a specific Configuration ID. - * - * Search the Analog Configuration LUT for the Configuration ID. - * - * \param[in] configId: Configuration ID to search for. - * \param[in] configOffset: Configuration Offset in Table - * - * \return number of Configuration Sets - * \return #RFAL_ANALOG_CONFIG_LUT_NOT_FOUND in case Configuration ID is not found. - ***************************************************************************** - */ -static rfalAnalogConfigNum - rfalAnalogConfigSearch(rfalAnalogConfigId configId, uint16_t* configOffset) { - rfalAnalogConfigId foundConfigId; - rfalAnalogConfigId configIdMaskVal; - const uint8_t* configTbl; - const uint8_t* currentConfigTbl; - uint16_t i; - - currentConfigTbl = gRfalAnalogConfigMgmt.currentAnalogConfigTbl; - configIdMaskVal = - ((RFAL_ANALOG_CONFIG_POLL_LISTEN_MODE_MASK | RFAL_ANALOG_CONFIG_BITRATE_MASK) | - ((RFAL_ANALOG_CONFIG_TECH_CHIP == RFAL_ANALOG_CONFIG_ID_GET_TECH(configId)) ? - (RFAL_ANALOG_CONFIG_TECH_MASK | RFAL_ANALOG_CONFIG_CHIP_SPECIFIC_MASK) : - configId) | - ((RFAL_ANALOG_CONFIG_NO_DIRECTION == RFAL_ANALOG_CONFIG_ID_GET_DIRECTION(configId)) ? - RFAL_ANALOG_CONFIG_DIRECTION_MASK : - configId)); - - /* When specific ConfigIDs are to be used, override search mask */ - if((RFAL_ANALOG_CONFIG_ID_GET_DIRECTION(configId) == RFAL_ANALOG_CONFIG_DPO)) { - configIdMaskVal = - (RFAL_ANALOG_CONFIG_POLL_LISTEN_MODE_MASK | RFAL_ANALOG_CONFIG_TECH_MASK | - RFAL_ANALOG_CONFIG_BITRATE_MASK | RFAL_ANALOG_CONFIG_DIRECTION_MASK); - } - - i = *configOffset; - while(i < gRfalAnalogConfigMgmt.configTblSize) { - configTbl = ¤tConfigTbl[i]; - foundConfigId = GETU16(configTbl); - if(configId == (foundConfigId & configIdMaskVal)) { - *configOffset = - (uint16_t)(i + sizeof(rfalAnalogConfigId) + sizeof(rfalAnalogConfigNum)); - return configTbl[sizeof(rfalAnalogConfigId)]; - } - - /* If Config Id does not match, increment to next Configuration Id */ - i += - (uint16_t)(sizeof(rfalAnalogConfigId) + sizeof(rfalAnalogConfigNum) + (configTbl[sizeof(rfalAnalogConfigId)] * sizeof(rfalAnalogConfigRegAddrMaskVal))); - } /* for */ - - return RFAL_ANALOG_CONFIG_LUT_NOT_FOUND; -} /* rfalAnalogConfigSearch() */ diff --git a/lib/ST25RFAL002/source/rfal_crc.c b/lib/ST25RFAL002/source/rfal_crc.c deleted file mode 100644 index bcf5ad593..000000000 --- a/lib/ST25RFAL002/source/rfal_crc.c +++ /dev/null @@ -1,82 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_crc.c - * - * \author Oliver Regenfelder - * - * \brief CRC calculation implementation - * - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "rfal_crc.h" - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -static uint16_t rfalCrcUpdateCcitt(uint16_t crcSeed, uint8_t dataByte); - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ -uint16_t rfalCrcCalculateCcitt(uint16_t preloadValue, const uint8_t* buf, uint16_t length) { - uint16_t crc = preloadValue; - uint16_t index; - - for(index = 0; index < length; index++) { - crc = rfalCrcUpdateCcitt(crc, buf[index]); - } - - return crc; -} - -/* -****************************************************************************** -* LOCAL FUNCTIONS -****************************************************************************** -*/ -static uint16_t rfalCrcUpdateCcitt(uint16_t crcSeed, uint8_t dataByte) { - uint16_t crc = crcSeed; - uint8_t dat = dataByte; - - dat ^= (uint8_t)(crc & 0xFFU); - dat ^= (dat << 4); - - crc = (crc >> 8) ^ (((uint16_t)dat) << 8) ^ (((uint16_t)dat) << 3) ^ (((uint16_t)dat) >> 4); - - return crc; -} diff --git a/lib/ST25RFAL002/source/rfal_dpo.c b/lib/ST25RFAL002/source/rfal_dpo.c deleted file mode 100644 index 48dd89c77..000000000 --- a/lib/ST25RFAL002/source/rfal_dpo.c +++ /dev/null @@ -1,232 +0,0 @@ - -/****************************************************************************** - * @attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * $Revision: $ - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_dpo.c - * - * \author Martin Zechleitner - * - * \brief Functions to manage and set dynamic power settings. - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_dpoTbl.h" -#include "rfal_dpo.h" -#include "platform.h" -#include "rfal_rf.h" -#include "rfal_chip.h" -#include "rfal_analogConfig.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_DPO -#define RFAL_FEATURE_DPO \ - false /* Dynamic Power Module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_DPO - -/* - ****************************************************************************** - * DEFINES - ****************************************************************************** - */ -#define RFAL_DPO_ANALOGCONFIG_SHIFT 13U -#define RFAL_DPO_ANALOGCONFIG_MASK 0x6000U - -/* - ****************************************************************************** - * LOCAL DATA TYPES - ****************************************************************************** - */ - -static bool gRfalDpoIsEnabled = false; -static uint8_t* gRfalCurrentDpo; -static uint8_t gRfalDpoTableEntries; -static uint8_t gRfalDpo[RFAL_DPO_TABLE_SIZE_MAX]; -static uint8_t gRfalDpoTableEntry; -static rfalDpoMeasureFunc gRfalDpoMeasureCallback = NULL; - -/* - ****************************************************************************** - * GLOBAL FUNCTIONS - ****************************************************************************** - */ -void rfalDpoInitialize(void) { - /* Use the default Dynamic Power values */ - gRfalCurrentDpo = (uint8_t*)rfalDpoDefaultSettings; - gRfalDpoTableEntries = (sizeof(rfalDpoDefaultSettings) / RFAL_DPO_TABLE_PARAMETER); - - ST_MEMCPY(gRfalDpo, gRfalCurrentDpo, sizeof(rfalDpoDefaultSettings)); - - /* by default use amplitude measurement */ - gRfalDpoMeasureCallback = rfalChipMeasureAmplitude; - - /* by default DPO is disabled */ - gRfalDpoIsEnabled = false; - - gRfalDpoTableEntry = 0; -} - -void rfalDpoSetMeasureCallback(rfalDpoMeasureFunc pMeasureFunc) { - gRfalDpoMeasureCallback = pMeasureFunc; -} - -/*******************************************************************************/ -ReturnCode rfalDpoTableWrite(rfalDpoEntry* powerTbl, uint8_t powerTblEntries) { - uint8_t entry = 0; - - /* check if the table size parameter is too big */ - if((powerTblEntries * RFAL_DPO_TABLE_PARAMETER) > RFAL_DPO_TABLE_SIZE_MAX) { - return ERR_NOMEM; - } - - /* check if the first increase entry is 0xFF */ - if((powerTblEntries == 0) || (powerTbl == NULL)) { - return ERR_PARAM; - } - - /* check if the entries of the dynamic power table are valid */ - for(entry = 0; entry < powerTblEntries; entry++) { - if(powerTbl[entry].inc < powerTbl[entry].dec) { - return ERR_PARAM; - } - } - - /* copy the data set */ - ST_MEMCPY(gRfalDpo, powerTbl, (powerTblEntries * RFAL_DPO_TABLE_PARAMETER)); - gRfalCurrentDpo = gRfalDpo; - gRfalDpoTableEntries = powerTblEntries; - - if(gRfalDpoTableEntry > powerTblEntries) { - /* is always greater then zero, otherwise we already returned ERR_PARAM */ - gRfalDpoTableEntry = (powerTblEntries - 1); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalDpoTableRead(rfalDpoEntry* tblBuf, uint8_t tblBufEntries, uint8_t* tableEntries) { - /* wrong request */ - if((tblBuf == NULL) || (tblBufEntries < gRfalDpoTableEntries) || (tableEntries == NULL)) { - return ERR_PARAM; - } - - /* Copy the whole Table to the given buffer */ - ST_MEMCPY(tblBuf, gRfalCurrentDpo, (tblBufEntries * RFAL_DPO_TABLE_PARAMETER)); - *tableEntries = gRfalDpoTableEntries; - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalDpoAdjust(void) { - uint8_t refValue = 0; - uint16_t modeID; - rfalBitRate br; - rfalDpoEntry* dpoTable = (rfalDpoEntry*)gRfalCurrentDpo; - - /* Check if the Power Adjustment is disabled and * - * if the callback to the measurement method is properly set */ - if((gRfalCurrentDpo == NULL) || (!gRfalDpoIsEnabled) || (gRfalDpoMeasureCallback == NULL)) { - return ERR_PARAM; - } - - /* Ensure that the current mode is Passive Poller */ - if(!rfalIsModePassivePoll(rfalGetMode())) { - return ERR_WRONG_STATE; - } - - /* Ensure a proper measure reference value */ - if(ERR_NONE != gRfalDpoMeasureCallback(&refValue)) { - return ERR_IO; - } - - if(refValue >= dpoTable[gRfalDpoTableEntry].inc) { /* Increase the output power */ - /* the top of the table represents the highest amplitude value*/ - if(gRfalDpoTableEntry == 0) { - /* maximum driver value has been reached */ - } else { - /* go up in the table to decrease the driver resistance */ - gRfalDpoTableEntry--; - } - } else if(refValue <= dpoTable[gRfalDpoTableEntry].dec) { /* decrease the output power */ - /* The bottom is the highest possible value */ - if((gRfalDpoTableEntry + 1) >= gRfalDpoTableEntries) { - /* minimum driver value has been reached */ - } else { - /* go down in the table to increase the driver resistance */ - gRfalDpoTableEntry++; - } - } else { - /* Fall through to always write dpo and its associated analog configs */ - } - - /* Get the new value for RFO resistance form the table and apply the new RFO resistance setting */ - rfalChipSetRFO(dpoTable[gRfalDpoTableEntry].rfoRes); - - /* Apply the DPO Analog Config according to this treshold */ - /* Technology field is being extended for DPO: 2msb are used for treshold step (only 4 allowed) */ - rfalGetBitRate(&br, NULL); /* Obtain current Tx bitrate */ - modeID = rfalAnalogConfigGenModeID( - rfalGetMode(), br, RFAL_ANALOG_CONFIG_DPO); /* Generate Analog Config mode ID */ - modeID |= - ((gRfalDpoTableEntry << RFAL_DPO_ANALOGCONFIG_SHIFT) & - RFAL_DPO_ANALOGCONFIG_MASK); /* Add DPO treshold step|level */ - rfalSetAnalogConfig(modeID); /* Apply DPO Analog Config */ - - return ERR_NONE; -} - -/*******************************************************************************/ -rfalDpoEntry* rfalDpoGetCurrentTableEntry(void) { - rfalDpoEntry* dpoTable = (rfalDpoEntry*)gRfalCurrentDpo; - return &dpoTable[gRfalDpoTableEntry]; -} - -/*******************************************************************************/ -void rfalDpoSetEnabled(bool enable) { - gRfalDpoIsEnabled = enable; -} - -/*******************************************************************************/ -bool rfalDpoIsEnabled(void) { - return gRfalDpoIsEnabled; -} - -#endif /* RFAL_FEATURE_DPO */ diff --git a/lib/ST25RFAL002/source/rfal_iso15693_2.c b/lib/ST25RFAL002/source/rfal_iso15693_2.c deleted file mode 100644 index 34ecd4111..000000000 --- a/lib/ST25RFAL002/source/rfal_iso15693_2.c +++ /dev/null @@ -1,514 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_iso15693_2.c - * - * \author Ulrich Herrmann - * - * \brief Implementation of ISO-15693-2 - * - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "rfal_iso15693_2.h" -#include "rfal_crc.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_NFCV -#define RFAL_FEATURE_NFCV false /* NFC-V module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_NFCV - -/* -****************************************************************************** -* LOCAL MACROS -****************************************************************************** -*/ - -#define ISO_15693_DEBUG(...) /*!< Macro for the log method */ - -/* -****************************************************************************** -* LOCAL DEFINES -****************************************************************************** -*/ -#define ISO15693_DAT_SOF_1_4 0x21 /* LSB constants */ -#define ISO15693_DAT_EOF_1_4 0x04 -#define ISO15693_DAT_00_1_4 0x02 -#define ISO15693_DAT_01_1_4 0x08 -#define ISO15693_DAT_10_1_4 0x20 -#define ISO15693_DAT_11_1_4 0x80 - -#define ISO15693_DAT_SOF_1_256 0x81 -#define ISO15693_DAT_EOF_1_256 0x04 -#define ISO15693_DAT_SLOT0_1_256 0x02 -#define ISO15693_DAT_SLOT1_1_256 0x08 -#define ISO15693_DAT_SLOT2_1_256 0x20 -#define ISO15693_DAT_SLOT3_1_256 0x80 - -#define ISO15693_PHY_DAT_MANCHESTER_1 0xaaaa - -#define ISO15693_PHY_BIT_BUFFER_SIZE \ - 1000 /*!< size of the receiving buffer. Might be adjusted if longer datastreams are expected. */ - -/* -****************************************************************************** -* LOCAL VARIABLES -****************************************************************************** -*/ -static iso15693PhyConfig_t iso15693PhyConfig; /*!< current phy configuration */ - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -static ReturnCode iso15693PhyVCDCode1Of4( - const uint8_t data, - uint8_t* outbuffer, - uint16_t maxOutBufLen, - uint16_t* outBufLen); -static ReturnCode iso15693PhyVCDCode1Of256( - const uint8_t data, - uint8_t* outbuffer, - uint16_t maxOutBufLen, - uint16_t* outBufLen); - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ -ReturnCode iso15693PhyConfigure( - const iso15693PhyConfig_t* config, - const struct iso15693StreamConfig** needed_stream_config) { - static struct iso15693StreamConfig stream_config = { - /* MISRA 8.9 */ - .useBPSK = 0, /* 0: subcarrier, 1:BPSK */ - .din = 5, /* 2^5*fc = 423750 Hz: divider for the in subcarrier frequency */ - .dout = 7, /*!< 2^7*fc = 105937 : divider for the in subcarrier frequency */ - .report_period_length = 3, /*!< 8=2^3 the length of the reporting period */ - }; - - /* make a copy of the configuration */ - ST_MEMCPY((uint8_t*)&iso15693PhyConfig, (const uint8_t*)config, sizeof(iso15693PhyConfig_t)); - - if(config->speedMode <= 3U) { /* If valid speed mode adjust report period accordingly */ - stream_config.report_period_length = (3U - (uint8_t)config->speedMode); - } else { /* If invalid default to normal (high) speed */ - stream_config.report_period_length = 3; - } - - *needed_stream_config = &stream_config; - - return ERR_NONE; -} - -ReturnCode iso15693PhyGetConfiguration(iso15693PhyConfig_t* config) { - ST_MEMCPY(config, &iso15693PhyConfig, sizeof(iso15693PhyConfig_t)); - - return ERR_NONE; -} - -ReturnCode iso15693VCDCode( - uint8_t* buffer, - uint16_t length, - bool sendCrc, - bool sendFlags, - bool picopassMode, - uint16_t* subbit_total_length, - uint16_t* offset, - uint8_t* outbuf, - uint16_t outBufSize, - uint16_t* actOutBufSize) { - ReturnCode err = ERR_NONE; - uint8_t eof, sof; - uint8_t transbuf[2]; - uint16_t crc = 0; - ReturnCode (*txFunc)( - const uint8_t data, uint8_t* outbuffer, uint16_t maxOutBufLen, uint16_t* outBufLen); - uint8_t crc_len; - uint8_t* outputBuf; - uint16_t outputBufSize; - - crc_len = (uint8_t)((sendCrc) ? 2 : 0); - - *actOutBufSize = 0; - - if(ISO15693_VCD_CODING_1_4 == iso15693PhyConfig.coding) { - sof = ISO15693_DAT_SOF_1_4; - eof = ISO15693_DAT_EOF_1_4; - txFunc = iso15693PhyVCDCode1Of4; - *subbit_total_length = - ((1U /* SOF */ - + ((length + (uint16_t)crc_len) * 4U) + 1U) /* EOF */ - ); - if(outBufSize < 5U) { /* 5 should be safe: enough for sof + 1byte data in 1of4 */ - return ERR_NOMEM; - } - } else { - sof = ISO15693_DAT_SOF_1_256; - eof = ISO15693_DAT_EOF_1_256; - txFunc = iso15693PhyVCDCode1Of256; - *subbit_total_length = - ((1U /* SOF */ - + ((length + (uint16_t)crc_len) * 64U) + 1U) /* EOF */ - ); - - if(*offset != 0U) { - if(outBufSize < 64U) { /* 64 should be safe: enough a single byte data in 1of256 */ - return ERR_NOMEM; - } - } else { - if(outBufSize < - 65U) { /* At beginning of a frame we need at least 65 bytes to start: enough for sof + 1byte data in 1of256 */ - return ERR_NOMEM; - } - } - } - - if(length == 0U) { - *subbit_total_length = 1; - } - - if((length != 0U) && (0U == *offset) && sendFlags && !picopassMode) { - /* set high datarate flag */ - buffer[0] |= (uint8_t)ISO15693_REQ_FLAG_HIGH_DATARATE; - /* clear sub-carrier flag - we only support single sub-carrier */ - buffer[0] = (uint8_t)(buffer[0] & ~ISO15693_REQ_FLAG_TWO_SUBCARRIERS); /* MISRA 10.3 */ - } - - outputBuf = outbuf; /* MISRA 17.8: Use intermediate variable */ - outputBufSize = outBufSize; /* MISRA 17.8: Use intermediate variable */ - - /* Send SOF if at 0 offset */ - if((length != 0U) && (0U == *offset)) { - *outputBuf = sof; - (*actOutBufSize)++; - outputBufSize--; - outputBuf++; - } - - while((*offset < length) && (err == ERR_NONE)) { - uint16_t filled_size; - /* send data */ - err = txFunc(buffer[*offset], outputBuf, outputBufSize, &filled_size); - (*actOutBufSize) += filled_size; - outputBuf = &outputBuf[filled_size]; /* MISRA 18.4: Avoid pointer arithmetic */ - outputBufSize -= filled_size; - if(err == ERR_NONE) { - (*offset)++; - } - } - if(err != ERR_NONE) { - return ERR_AGAIN; - } - - while((err == ERR_NONE) && sendCrc && (*offset < (length + 2U))) { - uint16_t filled_size; - if(0U == crc) { - crc = rfalCrcCalculateCcitt( - (uint16_t)((picopassMode) ? 0xE012U : 0xFFFFU), /* In PicoPass Mode a different Preset Value is used */ - ((picopassMode) ? - (buffer + 1U) : - buffer), /* CMD byte is not taken into account in PicoPass mode */ - ((picopassMode) ? - (length - 1U) : - length)); /* CMD byte is not taken into account in PicoPass mode */ - - crc = (uint16_t)((picopassMode) ? crc : ~crc); - } - /* send crc */ - transbuf[0] = (uint8_t)(crc & 0xffU); - transbuf[1] = (uint8_t)((crc >> 8) & 0xffU); - err = txFunc(transbuf[*offset - length], outputBuf, outputBufSize, &filled_size); - (*actOutBufSize) += filled_size; - outputBuf = &outputBuf[filled_size]; /* MISRA 18.4: Avoid pointer arithmetic */ - outputBufSize -= filled_size; - if(err == ERR_NONE) { - (*offset)++; - } - } - if(err != ERR_NONE) { - return ERR_AGAIN; - } - - if((!sendCrc && (*offset == length)) || (sendCrc && (*offset == (length + 2U)))) { - *outputBuf = eof; - (*actOutBufSize)++; - outputBufSize--; - outputBuf++; - } else { - return ERR_AGAIN; - } - - return err; -} - -ReturnCode iso15693VICCDecode( - const uint8_t* inBuf, - uint16_t inBufLen, - uint8_t* outBuf, - uint16_t outBufLen, - uint16_t* outBufPos, - uint16_t* bitsBeforeCol, - uint16_t ignoreBits, - bool picopassMode) { - ReturnCode err = ERR_NONE; - uint16_t crc; - uint16_t mp; /* Current bit position in manchester bit inBuf*/ - uint16_t bp; /* Current bit position in outBuf */ - - *bitsBeforeCol = 0; - *outBufPos = 0; - - /* first check for valid SOF. Since it starts with 3 unmodulated pulses it is 0x17. */ - if((inBuf[0] & 0x1fU) != 0x17U) { - ISO_15693_DEBUG("0x%x\n", iso15693PhyBitBuffer[0]); - return ERR_FRAMING; - } - ISO_15693_DEBUG("SOF\n"); - - if(outBufLen == 0U) { - return ERR_NONE; - } - - mp = 5; /* 5 bits were SOF, now manchester starts: 2 bits per payload bit */ - bp = 0; - - ST_MEMSET(outBuf, 0, outBufLen); - - if(inBufLen == 0U) { - return ERR_CRC; - } - - for(; mp < ((inBufLen * 8U) - 2U); mp += 2U) { - bool isEOF = false; - - uint8_t man; - man = (inBuf[mp / 8U] >> (mp % 8U)) & 0x1U; - man |= ((inBuf[(mp + 1U) / 8U] >> ((mp + 1U) % 8U)) & 0x1U) << 1; - if(1U == man) { - bp++; - } - if(2U == man) { - outBuf[bp / 8U] = (uint8_t)(outBuf[bp / 8U] | (1U << (bp % 8U))); /* MISRA 10.3 */ - bp++; - } - if((bp % 8U) == 0U) { /* Check for EOF */ - ISO_15693_DEBUG("ceof %hhx %hhx\n", inBuf[mp / 8U], inBuf[mp / 8 + 1]); - if(((inBuf[mp / 8U] & 0xe0U) == 0xa0U) && - (inBuf[(mp / 8U) + 1U] == 0x03U)) { /* Now we know that it was 10111000 = EOF */ - ISO_15693_DEBUG("EOF\n"); - isEOF = true; - } - } - if(((0U == man) || (3U == man)) && !isEOF) { - if(bp >= ignoreBits) { - err = ERR_RF_COLLISION; - } else { - /* ignored collision: leave as 0 */ - bp++; - } - } - if((bp >= (outBufLen * 8U)) || (err == ERR_RF_COLLISION) || - isEOF) { /* Don't write beyond the end */ - break; - } - } - - *outBufPos = (bp / 8U); - *bitsBeforeCol = bp; - - if(err != ERR_NONE) { - return err; - } - - if((bp % 8U) != 0U) { - return ERR_CRC; - } - - if(*outBufPos > 2U) { - /* finally, check crc */ - ISO_15693_DEBUG("Calculate CRC, val: 0x%x, outBufLen: ", *outBuf); - ISO_15693_DEBUG("0x%x ", *outBufPos - 2); - - crc = rfalCrcCalculateCcitt(((picopassMode) ? 0xE012U : 0xFFFFU), outBuf, *outBufPos - 2U); - crc = (uint16_t)((picopassMode) ? crc : ~crc); - - if(((crc & 0xffU) == outBuf[*outBufPos - 2U]) && - (((crc >> 8U) & 0xffU) == outBuf[*outBufPos - 1U])) { - err = ERR_NONE; - ISO_15693_DEBUG("OK\n"); - } else { - ISO_15693_DEBUG("error! Expected: 0x%x, got ", crc); - ISO_15693_DEBUG("0x%hhx 0x%hhx\n", outBuf[*outBufPos - 2], outBuf[*outBufPos - 1]); - err = ERR_CRC; - } - } else { - err = ERR_CRC; - } - - return err; -} - -/* -****************************************************************************** -* LOCAL FUNCTIONS -****************************************************************************** -*/ -/*! - ***************************************************************************** - * \brief Perform 1 of 4 coding and send coded data - * - * This function takes \a length bytes from \a buffer, perform 1 of 4 coding - * (see ISO15693-2 specification) and sends the data using stream mode. - * - * \param[in] sendSof : send SOF prior to data. - * \param[in] buffer : data to send. - * \param[in] length : number of bytes to send. - * - * \return ERR_IO : Error during communication. - * \return ERR_NONE : No error. - * - ***************************************************************************** - */ -static ReturnCode iso15693PhyVCDCode1Of4( - const uint8_t data, - uint8_t* outbuffer, - uint16_t maxOutBufLen, - uint16_t* outBufLen) { - uint8_t tmp; - ReturnCode err = ERR_NONE; - uint16_t a; - uint8_t* outbuf = outbuffer; - - *outBufLen = 0; - - if(maxOutBufLen < 4U) { - return ERR_NOMEM; - } - - tmp = data; - for(a = 0; a < 4U; a++) { - switch(tmp & 0x3U) { - case 0: - *outbuf = ISO15693_DAT_00_1_4; - break; - case 1: - *outbuf = ISO15693_DAT_01_1_4; - break; - case 2: - *outbuf = ISO15693_DAT_10_1_4; - break; - case 3: - *outbuf = ISO15693_DAT_11_1_4; - break; - default: - /* MISRA 16.4: mandatory default statement */ - break; - } - outbuf++; - (*outBufLen)++; - tmp >>= 2; - } - return err; -} - -/*! - ***************************************************************************** - * \brief Perform 1 of 256 coding and send coded data - * - * This function takes \a length bytes from \a buffer, perform 1 of 256 coding - * (see ISO15693-2 specification) and sends the data using stream mode. - * \note This function sends SOF prior to the data. - * - * \param[in] sendSof : send SOF prior to data. - * \param[in] buffer : data to send. - * \param[in] length : number of bytes to send. - * - * \return ERR_IO : Error during communication. - * \return ERR_NONE : No error. - * - ***************************************************************************** - */ -static ReturnCode iso15693PhyVCDCode1Of256( - const uint8_t data, - uint8_t* outbuffer, - uint16_t maxOutBufLen, - uint16_t* outBufLen) { - uint8_t tmp; - ReturnCode err = ERR_NONE; - uint16_t a; - uint8_t* outbuf = outbuffer; - - *outBufLen = 0; - - if(maxOutBufLen < 64U) { - return ERR_NOMEM; - } - - tmp = data; - for(a = 0; a < 64U; a++) { - switch(tmp) { - case 0: - *outbuf = ISO15693_DAT_SLOT0_1_256; - break; - case 1: - *outbuf = ISO15693_DAT_SLOT1_1_256; - break; - case 2: - *outbuf = ISO15693_DAT_SLOT2_1_256; - break; - case 3: - *outbuf = ISO15693_DAT_SLOT3_1_256; - break; - default: - *outbuf = 0; - break; - } - outbuf++; - (*outBufLen)++; - tmp -= 4U; - } - - return err; -} - -#endif /* RFAL_FEATURE_NFCV */ diff --git a/lib/ST25RFAL002/source/rfal_isoDep.c b/lib/ST25RFAL002/source/rfal_isoDep.c deleted file mode 100644 index 13674788e..000000000 --- a/lib/ST25RFAL002/source/rfal_isoDep.c +++ /dev/null @@ -1,3032 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: NFCC firmware - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_isoDep.c - * - * \author Gustavo Patricio - * - * \brief Implementation of ISO-DEP protocol - * - * This implementation was based on the following specs: - * - ISO/IEC 14443-4 2nd Edition 2008-07-15 - * - NFC Forum Digital Protocol 1.1 2014-01-14 - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ - -#include "rfal_isoDep.h" -#include "rfal_rf.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#if RFAL_FEATURE_ISO_DEP - -#if(!RFAL_FEATURE_ISO_DEP_POLL && !RFAL_FEATURE_ISO_DEP_LISTEN) -#error \ - " RFAL: Invalid ISO-DEP Configuration. Please select at least one mode: Poller and/or Listener. " -#endif - -/* Check for valid I-Block length [RFAL_ISODEP_FSX_16 ; RFAL_ISODEP_FSX_4096]*/ -#if((RFAL_FEATURE_ISO_DEP_IBLOCK_MAX_LEN > 4096) || (RFAL_FEATURE_ISO_DEP_IBLOCK_MAX_LEN < 16)) -#error \ - " RFAL: Invalid ISO-DEP IBlock Max length. Please change RFAL_FEATURE_ISO_DEP_IBLOCK_MAX_LEN. " -#endif - -/* Check for valid APDU length. */ -#if((RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN < RFAL_FEATURE_ISO_DEP_IBLOCK_MAX_LEN)) -#error " RFAL: Invalid ISO-DEP APDU Max length. Please change RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN. " -#endif - -/* - ****************************************************************************** - * DEFINES - ****************************************************************************** - */ -#define ISODEP_CRC_LEN RFAL_CRC_LEN /*!< ISO1443 CRC Length */ - -#define ISODEP_PCB_POS (0U) /*!< PCB position on message header*/ -#define ISODEP_SWTX_INF_POS (1U) /*!< INF position in a S-WTX */ - -#define ISODEP_DID_POS (1U) /*!< DID position on message header*/ -#define ISODEP_SWTX_PARAM_LEN (1U) /*!< SWTX parameter length */ - -#define ISODEP_DSL_MAX_LEN \ - (RFAL_ISODEP_PCB_LEN + RFAL_ISODEP_DID_LEN) /*!< Deselect Req/Res length */ - -#define ISODEP_PCB_xBLOCK_MASK (0xC0U) /*!< Bit mask for Block type */ -#define ISODEP_PCB_IBLOCK (0x00U) /*!< Bit mask indicating a I-Block */ -#define ISODEP_PCB_RBLOCK (0x80U) /*!< Bit mask indicating a R-Block */ -#define ISODEP_PCB_SBLOCK (0xC0U) /*!< Bit mask indicating a S-Block */ -#define ISODEP_PCB_INVALID (0x40U) /*!< Bit mask of an Invalid PCB */ - -#define ISODEP_HDR_MAX_LEN \ - (RFAL_ISODEP_PCB_LEN + RFAL_ISODEP_DID_LEN + \ - RFAL_ISODEP_NAD_LEN) /*!< Max header length (PCB + DID + NAD) */ - -#define ISODEP_PCB_IB_VALID_MASK \ - (ISODEP_PCB_B6_BIT | ISODEP_PCB_B2_BIT) /*!< Bit mask for the MUST bits on I-Block */ -#define ISODEP_PCB_IB_VALID_VAL \ - (ISODEP_PCB_B2_BIT) /*!< Value for the MUST bits on I-Block */ -#define ISODEP_PCB_RB_VALID_MASK \ - (ISODEP_PCB_B6_BIT | ISODEP_PCB_B3_BIT | \ - ISODEP_PCB_B2_BIT) /*!< Bit mask for the MUST bits on R-Block */ -#define ISODEP_PCB_RB_VALID_VAL \ - (ISODEP_PCB_B6_BIT | ISODEP_PCB_B2_BIT) /*!< Value for the MUST bits on R-Block */ -#define ISODEP_PCB_SB_VALID_MASK \ - (ISODEP_PCB_B3_BIT | ISODEP_PCB_B2_BIT | \ - ISODEP_PCB_B1_BIT) /*!< Bit mask for the MUST bits on I-Block */ -#define ISODEP_PCB_SB_VALID_VAL \ - (ISODEP_PCB_B2_BIT) /*!< Value for the MUST bits on I-Block */ - -#define ISODEP_PCB_B1_BIT \ - (0x01U) /*!< Bit mask for the RFU S Blocks */ -#define ISODEP_PCB_B2_BIT \ - (0x02U) /*!< Bit mask for the RFU bit2 in I,S,R Blocks */ -#define ISODEP_PCB_B3_BIT \ - (0x04U) /*!< Bit mask for the RFU bit3 in R Blocks */ -#define ISODEP_PCB_B6_BIT \ - (0x20U) /*!< Bit mask for the RFU bit2 in R Blocks */ -#define ISODEP_PCB_CHAINING_BIT \ - (0x10U) /*!< Bit mask for the chaining bit of an ISO DEP I-Block in PCB. */ -#define ISODEP_PCB_DID_BIT \ - (0x08U) /*!< Bit mask for the DID presence bit of an ISO DEP I,S,R Blocks PCB. */ -#define ISODEP_PCB_NAD_BIT \ - (0x04U) /*!< Bit mask for the NAD presence bit of an ISO DEP I,S,R Blocks in PCB */ -#define ISODEP_PCB_BN_MASK \ - (0x01U) /*!< Bit mask for the block number of an ISO DEP I,R Block in PCB */ - -#define ISODEP_SWTX_PL_MASK \ - (0xC0U) /*!< Bit mask for the Power Level bits of the inf byte of an WTX request or response */ -#define ISODEP_SWTX_WTXM_MASK \ - (0x3FU) /*!< Bit mask for the WTXM bits of the inf byte of an WTX request or response */ - -#define ISODEP_RBLOCK_INF_LEN (0U) /*!< INF length of R-Block Digital 1.1 15.1.3 */ -#define ISODEP_SDSL_INF_LEN (0U) /*!< INF length of S(DSL) Digital 1.1 15.1.3 */ -#define ISODEP_SWTX_INF_LEN (1U) /*!< INF length of S(WTX) Digital 1.1 15.2.2 */ - -#define ISODEP_WTXM_MIN (1U) /*!< Minimum allowed value for the WTXM, Digital 1.0 13.2.2 */ -#define ISODEP_WTXM_MAX (59U) /*!< Maximum allowed value for the WTXM, Digital 1.0 13.2.2 */ - -#define ISODEP_PCB_Sxx_MASK (0x30U) /*!< Bit mask for the S-Block type */ -#define ISODEP_PCB_DESELECT (0x00U) /*!< Bit mask for S-Block indicating Deselect */ -#define ISODEP_PCB_WTX (0x30U) /*!< Bit mask for S-Block indicating Waiting Time eXtension */ - -#define ISODEP_PCB_Rx_MASK (0x10U) /*!< Bit mask for the R-Block type */ -#define ISODEP_PCB_ACK (0x00U) /*!< Bit mask for R-Block indicating ACK */ -#define ISODEP_PCB_NAK (0x10U) /*!< Bit mask for R-Block indicating NAK */ - -/*! Maximum length of control message (no INF) */ -#define ISODEP_CONTROLMSG_BUF_LEN \ - (RFAL_ISODEP_PCB_LEN + RFAL_ISODEP_DID_LEN + RFAL_ISODEP_NAD_LEN + ISODEP_SWTX_PARAM_LEN) - -#define ISODEP_FWT_DEACTIVATION \ - (71680U) /*!< FWT used for DESELECT Digital 2.2 B10 ISO1444-4 7.2 & 8.1 */ -#define ISODEP_MAX_RERUNS (0x0FFFFFFFU) /*!< Maximum rerun retrys for a blocking protocol run*/ - -#define ISODEP_PCBSBLOCK \ - (0x00U | ISODEP_PCB_SBLOCK | ISODEP_PCB_B2_BIT) /*!< PCB Value of a S-Block */ -#define ISODEP_PCB_SDSL \ - (ISODEP_PCBSBLOCK | ISODEP_PCB_DESELECT) /*!< PCB Value of a S-Block with DESELECT */ -#define ISODEP_PCB_SWTX \ - (ISODEP_PCBSBLOCK | ISODEP_PCB_WTX) /*!< PCB Value of a S-Block with WTX */ -#define ISODEP_PCB_SPARAMETERS \ - (ISODEP_PCB_SBLOCK | ISODEP_PCB_WTX) /*!< PCB Value of a S-Block with PARAMETERS */ - -#define ISODEP_FWI_LIS_MAX_NFC \ - 8U /*!< FWT Listener Max FWIT4ATmax FWIBmax Digital 1.1 A6 & A3 */ -#define ISODEP_FWI_LIS_MAX_EMVCO \ - 7U /*!< FWT Listener Max FWIMAX EMVCo 2.6 A.5 */ -#define ISODEP_FWI_LIS_MAX \ - (uint8_t)( \ - (gIsoDep.compMode == RFAL_COMPLIANCE_MODE_EMV) ? \ - ISODEP_FWI_LIS_MAX_EMVCO : \ - ISODEP_FWI_LIS_MAX_NFC) /*!< FWI Listener Max as NFC / EMVCo */ -#define ISODEP_FWT_LIS_MAX \ - rfalIsoDepFWI2FWT(ISODEP_FWI_LIS_MAX) /*!< FWT Listener Max */ - -#define ISODEP_FWI_MIN_10 (1U) /*!< Minimum value for FWI Digital 1.0 11.6.2.17 */ -#define ISODEP_FWI_MIN_11 (0U) /*!< Default value for FWI Digital 1.1 13.6.2 */ -#define ISODEP_FWI_MAX (14U) /*!< Maximum value for FWI Digital 1.0 11.6.2.17 */ -#define ISODEP_SFGI_MIN (0U) /*!< Default value for FWI Digital 1.1 13.6.2.22 */ -#define ISODEP_SFGI_MAX (14U) /*!< Maximum value for FWI Digital 1.1 13.6.2.22 */ - -#define RFAL_ISODEP_SPARAM_TVL_HDR_LEN (2U) /*!< S(PARAMETERS) TVL header length: Tag + Len */ -#define RFAL_ISODEP_SPARAM_HDR_LEN \ - (RFAL_ISODEP_PCB_LEN + \ - RFAL_ISODEP_SPARAM_TVL_HDR_LEN) /*!< S(PARAMETERS) header length: PCB + Tag + Len */ - -/**********************************************************************************************************************/ -/**********************************************************************************************************************/ -#define RFAL_ISODEP_NO_PARAM (0U) /*!< No parameter flag for isoDepHandleControlMsg() */ - -#define RFAL_ISODEP_CMD_RATS (0xE0U) /*!< RATS command Digital 1.1 13.6.1 */ - -#define RFAL_ISODEP_ATS_MIN_LEN (1U) /*!< Minimum ATS length Digital 1.1 13.6.2 */ -#define RFAL_ISODEP_ATS_HDR_LEN (5U) /*!< ATS headerlength Digital 1.1 13.6.2 */ -#define RFAL_ISODEP_ATS_MAX_LEN \ - (RFAL_ISODEP_ATS_HDR_LEN + \ - RFAL_ISODEP_ATS_HB_MAX_LEN) /*!< Maximum ATS length Digital 1.1 13.6.2 */ -#define RFAL_ISODEP_ATS_T0_FSCI_MASK (0x0FU) /*!< ATS T0's FSCI mask Digital 1.1 13.6.2 */ -#define RFAL_ISODEP_ATS_TB_FWI_SHIFT (4U) /*!< ATS TB's FWI shift Digital 1.1 13.6.2 */ -#define RFAL_ISODEP_ATS_FWI_MASK (0x0FU) /*!< ATS TB's FWI shift Digital 1.1 13.6.2 */ -#define RFAL_ISODEP_ATS_TL_POS (0x00U) /*!< ATS TL's position Digital 1.1 13.6.2 */ - -#define RFAL_ISODEP_PPS_SB (0xD0U) /*!< PPS REQ PPSS's SB value (no CID) ISO14443-4 5.3 */ -#define RFAL_ISODEP_PPS_MASK (0xF0U) /*!< PPS REQ PPSS's SB mask ISO14443-4 5.3 */ -#define RFAL_ISODEP_PPS_SB_DID_MASK \ - (0x0FU) /*!< PPS REQ PPSS's DID|CID mask ISO14443-4 5.3 */ -#define RFAL_ISODEP_PPS_PPS0_PPS1_PRESENT \ - (0x11U) /*!< PPS REQ PPS0 indicating that PPS1 is present */ -#define RFAL_ISODEP_PPS_PPS1 (0x00U) /*!< PPS REQ PPS1 fixed value ISO14443-4 5.3 */ -#define RFAL_ISODEP_PPS_PPS1_DSI_SHIFT \ - (2U) /*!< PPS REQ PPS1 fixed value ISO14443-4 5.3 */ -#define RFAL_ISODEP_PPS_PPS1_DXI_MASK \ - (0x0FU) /*!< PPS REQ PPS1 fixed value ISO14443-4 5.3 */ -#define RFAL_ISODEP_PPS_RES_LEN (1U) /*!< PPS Response length ISO14443-4 5.4 */ -#define RFAL_ISODEP_PPS_STARTBYTE_POS \ - (0U) /*!< PPS REQ PPSS's byte position ISO14443-4 5.4 */ -#define RFAL_ISODEP_PPS_PPS0_POS (1U) /*!< PPS REQ PPS0's byte position ISO14443-4 5.4 */ -#define RFAL_ISODEP_PPS_PPS1_POS (2U) /*!< PPS REQ PPS1's byte position ISO14443-4 5.4 */ -#define RFAL_ISODEP_PPS0_VALID_MASK \ - (0xEFU) /*!< PPS REQ PPS0 valid coding mask ISO14443-4 5.4 */ - -#define RFAL_ISODEP_CMD_ATTRIB (0x1DU) /*!< ATTRIB command Digital 1.1 14.6.1 */ -#define RFAL_ISODEP_ATTRIB_PARAM2_DSI_SHIFT \ - (6U) /*!< ATTRIB PARAM2 DSI shift Digital 1.1 14.6.1 */ -#define RFAL_ISODEP_ATTRIB_PARAM2_DRI_SHIFT \ - (4U) /*!< ATTRIB PARAM2 DRI shift Digital 1.1 14.6.1 */ -#define RFAL_ISODEP_ATTRIB_PARAM2_DXI_MASK \ - (0xF0U) /*!< ATTRIB PARAM2 DxI mask Digital 1.1 14.6.1 */ -#define RFAL_ISODEP_ATTRIB_PARAM2_FSDI_MASK \ - (0x0FU) /*!< ATTRIB PARAM2 FSDI mask Digital 1.1 14.6.1 */ -#define RFAL_ISODEP_ATTRIB_PARAM4_DID_MASK \ - (0x0FU) /*!< ATTRIB PARAM4 DID mask Digital 1.1 14.6.1 */ -#define RFAL_ISODEP_ATTRIB_HDR_LEN (9U) /*!< ATTRIB REQ header length Digital 1.1 14.6.1 */ - -#define RFAL_ISODEP_ATTRIB_RES_HDR_LEN \ - (1U) /*!< ATTRIB RES header length Digital 1.1 14.6.2 */ -#define RFAL_ISODEP_ATTRIB_RES_MBLIDID_POS \ - (0U) /*!< ATTRIB RES MBLI|DID position Digital 1.1 14.6.2 */ -#define RFAL_ISODEP_ATTRIB_RES_DID_MASK \ - (0x0FU) /*!< ATTRIB RES DID mask Digital 1.1 14.6.2 */ -#define RFAL_ISODEP_ATTRIB_RES_MBLI_MASK \ - (0x0FU) /*!< ATTRIB RES MBLI mask Digital 1.1 14.6.2 */ -#define RFAL_ISODEP_ATTRIB_RES_MBLI_SHIFT \ - (4U) /*!< ATTRIB RES MBLI shift Digital 1.1 14.6.2 */ - -#define RFAL_ISODEP_DID_MASK (0x0FU) /*!< ISODEP's DID mask */ -#define RFAL_ISODEP_DID_00 (0U) /*!< ISODEP's DID value 0 */ - -#define RFAL_ISODEP_FSDI_MAX_NFC (8U) /*!< Max FSDI value Digital 2.0 14.6.1.9 & B7 & B8 */ -#define RFAL_ISODEP_FSDI_MAX_NFC_21 \ - (0x0CU) /*!< Max FSDI value Digital 2.1 14.6.1.9 & Table 72 */ -#define RFAL_ISODEP_FSDI_MAX_EMV (0x0CU) /*!< Max FSDI value EMVCo 3.0 5.7.2.5 */ - -#define RFAL_ISODEP_RATS_PARAM_FSDI_MASK \ - (0xF0U) /*!< Mask bits for FSDI in RATS */ -#define RFAL_ISODEP_RATS_PARAM_FSDI_SHIFT \ - (4U) /*!< Shift for FSDI in RATS */ -#define RFAL_ISODEP_RATS_PARAM_DID_MASK \ - (0x0FU) /*!< Mask bits for DID in RATS */ - -#define RFAL_ISODEP_ATS_TL_OFFSET \ - (0x00U) /*!< Offset of TL on ATS */ -#define RFAL_ISODEP_ATS_TA_OFFSET \ - (0x02U) /*!< Offset of TA if it is present on ATS */ -#define RFAL_ISODEP_ATS_TB_OFFSET \ - (0x03U) /*!< Offset of TB if both TA and TB is present on ATS */ -#define RFAL_ISODEP_ATS_TC_OFFSET \ - (0x04U) /*!< Offset of TC if both TA,TB & TC are present on ATS */ -#define RFAL_ISODEP_ATS_HIST_OFFSET \ - (0x05U) /*!< Offset of Historical Bytes if TA, TB & TC are present on ATS */ -#define RFAL_ISODEP_ATS_TC_ADV_FEAT \ - (0x10U) /*!< Bit mask indicating support for Advanced protocol features: DID & NAD */ -#define RFAL_ISODEP_ATS_TC_DID (0x02U) /*!< Bit mask indicating support for DID */ -#define RFAL_ISODEP_ATS_TC_NAD (0x01U) /*!< Bit mask indicating support for NAD */ - -#define RFAL_ISODEP_PPS0_PPS1_PRESENT \ - (0x11U) /*!< PPS0 byte indicating that PPS1 is present */ -#define RFAL_ISODEP_PPS0_PPS1_NOT_PRESENT \ - (0x01U) /*!< PPS0 byte indicating that PPS1 is NOT present */ -#define RFAL_ISODEP_PPS1_DRI_MASK \ - (0x03U) /*!< PPS1 byte DRI mask bits */ -#define RFAL_ISODEP_PPS1_DSI_MASK \ - (0x0CU) /*!< PPS1 byte DSI mask bits */ -#define RFAL_ISODEP_PPS1_DSI_SHIFT \ - (2U) /*!< PPS1 byte DSI shift */ -#define RFAL_ISODEP_PPS1_DxI_MASK \ - (0x03U) /*!< PPS1 byte DSI/DRS mask bits */ - -/*! Delta Time for polling during Activation (ATS) : 20ms Digital 1.0 11.7.1.1 & A.7 */ -#define RFAL_ISODEP_T4T_DTIME_POLL_10 rfalConvMsTo1fc(20) - -/*! Delta Time for polling during Activation (ATS) : 16.4ms Digital 1.1 13.8.1.1 & A.6 - * Use 16 ms as testcase T4AT_BI_10_03 sends a frame exactly at the border */ -#define RFAL_ISODEP_T4T_DTIME_POLL_11 216960U - -/*! Activation frame waiting time FWT(act) = 71680/fc (~5286us) Digital 1.1 13.8.1.1 & A.6 */ -#define RFAL_ISODEP_T4T_FWT_ACTIVATION (71680U + RFAL_ISODEP_T4T_DTIME_POLL_11) - -/*! Delta frame waiting time = 16/fc Digital 1.0 11.7.1.3 & A.7*/ -#define RFAL_ISODEP_DFWT_10 16U - -/*! Delta frame waiting time = 16/fc Digital 2.0 14.8.1.3 & B.7*/ -#define RFAL_ISODEP_DFWT_20 49152U - -/* - ****************************************************************************** - * MACROS - ****************************************************************************** - */ - -#define isoDep_PCBisIBlock(pcb) \ - (((pcb) & (ISODEP_PCB_xBLOCK_MASK | ISODEP_PCB_IB_VALID_MASK)) == \ - (ISODEP_PCB_IBLOCK | ISODEP_PCB_IB_VALID_VAL)) /*!< Checks if pcb is a I-Block */ -#define isoDep_PCBisRBlock(pcb) \ - (((pcb) & (ISODEP_PCB_xBLOCK_MASK | ISODEP_PCB_RB_VALID_MASK)) == \ - (ISODEP_PCB_RBLOCK | ISODEP_PCB_RB_VALID_VAL)) /*!< Checks if pcb is a R-Block */ -#define isoDep_PCBisSBlock(pcb) \ - (((pcb) & (ISODEP_PCB_xBLOCK_MASK | ISODEP_PCB_SB_VALID_MASK)) == \ - (ISODEP_PCB_SBLOCK | ISODEP_PCB_SB_VALID_VAL)) /*!< Checks if pcb is a S-Block */ - -#define isoDep_PCBisChaining(pcb) \ - (((pcb)&ISODEP_PCB_CHAINING_BIT) == \ - ISODEP_PCB_CHAINING_BIT) /*!< Checks if pcb is indicating chaining */ - -#define isoDep_PCBisDeselect(pcb) \ - (((pcb)&ISODEP_PCB_Sxx_MASK) == \ - ISODEP_PCB_DESELECT) /*!< Checks if pcb is indicating DESELECT */ -#define isoDep_PCBisWTX(pcb) \ - (((pcb)&ISODEP_PCB_Sxx_MASK) == ISODEP_PCB_WTX) /*!< Checks if pcb is indicating WTX */ - -#define isoDep_PCBisACK(pcb) \ - (((pcb)&ISODEP_PCB_Rx_MASK) == ISODEP_PCB_ACK) /*!< Checks if pcb is indicating ACK */ -#define isoDep_PCBisNAK(pcb) \ - (((pcb)&ISODEP_PCB_Rx_MASK) == ISODEP_PCB_NAK) /*!< Checks if pcb is indicating ACK */ - -#define isoDep_PCBhasDID(pcb) \ - (((pcb)&ISODEP_PCB_DID_BIT) == ISODEP_PCB_DID_BIT) /*!< Checks if pcb is indicating DID */ -#define isoDep_PCBhasNAD(pcb) \ - (((pcb)&ISODEP_PCB_NAD_BIT) == ISODEP_PCB_NAD_BIT) /*!< Checks if pcb is indicating NAD */ - -#define isoDep_PCBisIChaining(pcb) \ - (isoDep_PCBisIBlock(pcb) && \ - isoDep_PCBisChaining(pcb)) /*!< Checks if pcb is I-Block indicating chaining*/ - -#define isoDep_PCBisSDeselect(pcb) \ - (isoDep_PCBisSBlock(pcb) && \ - isoDep_PCBisDeselect(pcb)) /*!< Checks if pcb is S-Block indicating DESELECT*/ -#define isoDep_PCBisSWTX(pcb) \ - (isoDep_PCBisSBlock(pcb) && \ - isoDep_PCBisWTX(pcb)) /*!< Checks if pcb is S-Block indicating WTX */ - -#define isoDep_PCBisRACK(pcb) \ - (isoDep_PCBisRBlock(pcb) && \ - isoDep_PCBisACK(pcb)) /*!< Checks if pcb is R-Block indicating ACK */ -#define isoDep_PCBisRNAK(pcb) \ - (isoDep_PCBisRBlock(pcb) && \ - isoDep_PCBisNAK(pcb)) /*!< Checks if pcb is R-Block indicating NAK */ - -#define isoDep_PCBIBlock(bn) \ - ((uint8_t)(0x00U | ISODEP_PCB_IBLOCK | ISODEP_PCB_B2_BIT | ((bn)&ISODEP_PCB_BN_MASK))) /*!< Returns an I-Block with the given block number (bn) */ -#define isoDep_PCBIBlockChaining(bn) \ - ((uint8_t)(isoDep_PCBIBlock(bn) | ISODEP_PCB_CHAINING_BIT)) /*!< Returns an I-Block with the given block number (bn) indicating chaining */ - -#define isoDep_PCBRBlock(bn) \ - ((uint8_t)(0x00U | ISODEP_PCB_RBLOCK | ISODEP_PCB_B6_BIT | ISODEP_PCB_B2_BIT | ((bn)&ISODEP_PCB_BN_MASK))) /*!< Returns an R-Block with the given block number (bn) */ -#define isoDep_PCBRACK(bn) \ - ((uint8_t)(isoDep_PCBRBlock(bn) | ISODEP_PCB_ACK)) /*!< Returns an R-Block with the given block number (bn) indicating ACK */ -#define isoDep_PCBRNAK(bn) \ - ((uint8_t)(isoDep_PCBRBlock(bn) | ISODEP_PCB_NAK)) /*!< Returns an R-Block with the given block number (bn) indicating NAK */ - -#define isoDep_GetBN(pcb) \ - ((uint8_t)((pcb)&ISODEP_PCB_BN_MASK)) /*!< Returns the block number (bn) from the given pcb */ -#define isoDep_GetWTXM(inf) \ - ((uint8_t)(( \ - inf)&ISODEP_SWTX_WTXM_MASK)) /*!< Returns the WTX value from the given inf byte */ -#define isoDep_isWTXMValid(wtxm) \ - (((wtxm) >= ISODEP_WTXM_MIN) && \ - ((wtxm) <= ISODEP_WTXM_MAX)) /*!< Checks if the given wtxm is valid */ - -#define isoDep_WTXMListenerMax(fwt) \ - (MIN( \ - (uint8_t)(ISODEP_FWT_LIS_MAX / (fwt)), \ - ISODEP_WTXM_MAX)) /*!< Calculates the Max WTXM value for the given fwt as a Listener */ - -#define isoDepCalcdSGFT(s) \ - (384U * ((uint32_t)1U \ - << (s))) /*!< Calculates the dSFGT with given SFGI Digital 1.1 13.8.2.1 & A.6*/ -#define isoDepCalcSGFT(s) \ - (4096U * ((uint32_t)1U \ - << (s))) /*!< Calculates the SFGT with given SFGI Digital 1.1 13.8.2 */ - -#define isoDep_PCBNextBN(bn) \ - (((uint8_t)(bn) ^ 0x01U) & \ - ISODEP_PCB_BN_MASK) /*!< Returns the value of the next block number based on bn */ -#define isoDep_PCBPrevBN(bn) \ - isoDep_PCBNextBN(bn) /*!< Returns the value of the previous block number based on bn */ -#define isoDep_ToggleBN(bn) \ - ((bn) = \ - (((bn) ^ 0x01U) & \ - ISODEP_PCB_BN_MASK)) /*!< Toggles the block number value of the given bn */ - -#define isoDep_WTXAdjust(v) \ - ((v) - ((v) >> 3)) /*!< Adjust WTX timer value to a percentage of the total, current 88% */ - -/*! ISO 14443-4 7.5.6.2 & Digital 1.1 - 15.2.6.2 The CE SHALL NOT attempt error recovery and remains in Rx mode upon Transmission or a Protocol Error */ -#define isoDepReEnableRx(rxB, rxBL, rxL) \ - rfalTransceiveBlockingTx(NULL, 0, rxB, rxBL, rxL, RFAL_TXRX_FLAGS_DEFAULT, RFAL_FWT_NONE) - -/*! Macro used for the blocking methods */ -#define rfalIsoDepRunBlocking(e, fn) \ - do { \ - (e) = (fn); \ - rfalWorker(); \ - } while((e) == ERR_BUSY) - -#define isoDepTimerStart(timer, time_ms) \ - do { \ - platformTimerDestroy(timer); \ - (timer) = platformTimerCreate((uint16_t)(time_ms)); \ - } while(0) /*!< Configures and starts the WTX timer */ -#define isoDepTimerisExpired(timer) \ - platformTimerIsExpired(timer) /*!< Checks WTX timer has expired */ -#define isoDepTimerDestroy(timer) \ - platformTimerDestroy(timer) /*!< Destroys WTX timer */ - -/* - ****************************************************************************** - * LOCAL DATA TYPES - ****************************************************************************** - */ - -/*! Internal structure to be used in handling of S(PARAMETERS) only */ -typedef struct { - uint8_t pcb; /*!< PCB byte */ - rfalIsoDepSParameter sParam; /*!< S(PARAMETERS) */ -} rfalIsoDepControlMsgSParam; - -/*! Enumeration of the possible control message types */ -typedef enum { - ISODEP_R_ACK, /*!< R-ACK Acknowledge */ - ISODEP_R_NAK, /*!< R-NACK Negative acknowledge */ - ISODEP_S_WTX, /*!< S-WTX Waiting Time Extension */ - ISODEP_S_DSL /*!< S-DSL Deselect */ -} rfalIsoDepControlMsg; - -/*! Enumeration of the IsoDep roles */ -typedef enum { - ISODEP_ROLE_PCD, /*!< Perform as Reader/PCD */ - ISODEP_ROLE_PICC /*!< Perform as Card/PICC */ -} rfalIsoDepRole; - -/*! ISO-DEP layer states */ -typedef enum { - ISODEP_ST_IDLE, /*!< Idle State */ - ISODEP_ST_PCD_TX, /*!< PCD Transmission State */ - ISODEP_ST_PCD_RX, /*!< PCD Reception State */ - ISODEP_ST_PCD_WAIT_DSL, /*!< PCD Wait for DSL response */ - - ISODEP_ST_PICC_ACT_ATS, /*!< PICC has replied to RATS (ATS) */ - ISODEP_ST_PICC_ACT_ATTRIB, /*!< PICC has replied to ATTRIB */ - ISODEP_ST_PICC_RX, /*!< PICC Reception State */ - ISODEP_ST_PICC_SWTX, /*!< PICC Waiting Time eXtension */ - ISODEP_ST_PICC_SDSL, /*!< PICC S(DSL) response ongoing */ - ISODEP_ST_PICC_TX, /*!< PICC Transmission State */ - - ISODEP_ST_PCD_ACT_RATS, /*!< PCD activation (RATS) */ - ISODEP_ST_PCD_ACT_PPS, /*!< PCD activation (PPS) */ - -} rfalIsoDepState; - -/*! Holds all ISO-DEP data(counters, buffers, ID, timeouts, frame size) */ -typedef struct { - rfalIsoDepState state; /*!< ISO-DEP module state */ - rfalIsoDepRole role; /*!< Current ISO-DEP role */ - - uint8_t blockNumber; /*!< Current block number */ - uint8_t did; /*!< Current DID */ - uint8_t nad; /*!< Current DID */ - uint8_t cntIRetrys; /*!< I-Block retry counter */ - uint8_t cntRRetrys; /*!< R-Block retry counter */ - uint8_t cntSDslRetrys; /*!< S(DESELECT) retry counter */ - uint8_t cntSWtxRetrys; /*!< Overall S(WTX) retry counter */ - uint8_t cntSWtxNack; /*!< R(NACK) answered with S(WTX) counter */ - uint32_t fwt; /*!< Current FWT (Frame Waiting Time) */ - uint32_t dFwt; /*!< Current delta FWT */ - uint16_t fsx; /*!< Current FSx FSC or FSD (max Frame size) */ - bool isTxChaining; /*!< Flag for chaining on Tx */ - bool isRxChaining; /*!< Flag for chaining on Rx */ - uint8_t* txBuf; /*!< Tx buffer pointer */ - uint8_t* rxBuf; /*!< Rx buffer pointer */ - uint16_t txBufLen; /*!< Tx buffer length */ - uint16_t rxBufLen; /*!< Rx buffer length */ - uint8_t txBufInfPos; /*!< Start of payload in txBuf */ - uint8_t rxBufInfPos; /*!< Start of payload in rxBuf */ - - uint16_t ourFsx; /*!< Our current FSx FSC or FSD (Frame size) */ - uint8_t lastPCB; /*!< Last PCB sent */ - uint8_t lastWTXM; /*!< Last WTXM sent */ - uint8_t atsTA; /*!< TA on ATS */ - uint8_t hdrLen; /*!< Current ISO-DEP length */ - rfalBitRate txBR; /*!< Current Tx Bit Rate */ - rfalBitRate rxBR; /*!< Current Rx Bit Rate */ - uint16_t* rxLen; /*!< Output parameter ptr to Rx length */ - bool* rxChaining; /*!< Output parameter ptr to Rx chaining flag */ - uint32_t WTXTimer; /*!< Timer used for WTX */ - bool lastDID00; /*!< Last PCD block had DID flag (for DID = 0) */ - - bool isTxPending; /*!< Flag pending Block while waiting WTX Ack */ - bool isWait4WTX; /*!< Flag for waiting WTX Ack */ - - uint8_t maxRetriesI; /*!< Number of retries for a I-Block */ - uint8_t maxRetriesR; /*!< Number of retries for a R-Block */ - uint8_t maxRetriesSDSL; /*!< Number of retries for S(DESELECT) errors */ - uint8_t maxRetriesSWTX; /*!< Number of retries for S(WTX) errors */ - uint8_t maxRetriesSnWTX; /*!< Number of retries S(WTX) replied w NACK */ - uint8_t maxRetriesRATS; /*!< Number of retries for RATS */ - - rfalComplianceMode compMode; /*!< Compliance mode */ - - uint8_t ctrlBuf[ISODEP_CONTROLMSG_BUF_LEN]; /*!< Control msg buf */ - uint16_t ctrlRxLen; /*!< Control msg rcvd len */ - - union { /* PRQA S 0750 # MISRA 19.2 - Members of the union will not be used concurrently, only one frame at a time */ -#if RFAL_FEATURE_NFCA - rfalIsoDepRats ratsReq; - rfalIsoDepPpsReq ppsReq; -#endif /* RFAL_FEATURE_NFCA */ - -#if RFAL_FEATURE_NFCB - rfalIsoDepAttribCmd attribReq; -#endif /* RFAL_FEATURE_NFCB */ - } actv; /*!< Activation buffer */ - - uint8_t* rxLen8; /*!< Receive length (8-bit) */ - rfalIsoDepDevice* actvDev; /*!< Activation Device Info */ - rfalIsoDepListenActvParam actvParam; /*!< Listen Activation context */ - - rfalIsoDepApduTxRxParam APDUParam; /*!< APDU TxRx params */ - uint16_t APDUTxPos; /*!< APDU Tx position */ - uint16_t APDURxPos; /*!< APDU Rx position */ - bool isAPDURxChaining; /*!< APDU Transceive chaining flag */ - -} rfalIsoDep; - -/* - ****************************************************************************** - * LOCAL VARIABLES - ****************************************************************************** - */ - -static rfalIsoDep gIsoDep; /*!< ISO-DEP Module instance */ - -/* - ****************************************************************************** - * LOCAL FUNCTION PROTOTYPES - ****************************************************************************** - */ -static void isoDepClearCounters(void); -static ReturnCode - isoDepTx(uint8_t pcb, const uint8_t* txBuf, uint8_t* infBuf, uint16_t infLen, uint32_t fwt); -static ReturnCode isoDepHandleControlMsg(rfalIsoDepControlMsg controlMsg, uint8_t param); -static void rfalIsoDepApdu2IBLockParam( - rfalIsoDepApduTxRxParam apduParam, - rfalIsoDepTxRxParam* iBlockParam, - uint16_t txPos, - uint16_t rxPos); - -#if RFAL_FEATURE_ISO_DEP_POLL -static ReturnCode isoDepDataExchangePCD(uint16_t* outActRxLen, bool* outIsChaining); -static void rfalIsoDepCalcBitRate( - rfalBitRate maxAllowedBR, - uint8_t piccBRCapability, - rfalBitRate* dsi, - rfalBitRate* dri); -static uint32_t rfalIsoDepSFGI2SFGT(uint8_t sfgi); - -#if RFAL_FEATURE_NFCA -static ReturnCode - rfalIsoDepStartRATS(rfalIsoDepFSxI FSDI, uint8_t DID, rfalIsoDepAts* ats, uint8_t* atsLen); -static ReturnCode rfalIsoDepGetRATSStatus(void); -static ReturnCode - rfalIsoDepStartPPS(uint8_t DID, rfalBitRate DSI, rfalBitRate DRI, rfalIsoDepPpsRes* ppsRes); -static ReturnCode rfalIsoDepGetPPSSTatus(void); -#endif /* RFAL_FEATURE_NFCA */ - -#if RFAL_FEATURE_NFCB -static ReturnCode rfalIsoDepStartATTRIB( - const uint8_t* nfcid0, - uint8_t PARAM1, - rfalBitRate DSI, - rfalBitRate DRI, - rfalIsoDepFSxI FSDI, - uint8_t PARAM3, - uint8_t DID, - const uint8_t* HLInfo, - uint8_t HLInfoLen, - uint32_t fwt, - rfalIsoDepAttribRes* attribRes, - uint8_t* attribResLen); -static ReturnCode rfalIsoDepGetATTRIBStatus(void); -#endif /* RFAL_FEATURE_NFCB */ - -#endif /* RFAL_FEATURE_ISO_DEP_POLL */ - -#if RFAL_FEATURE_ISO_DEP_LISTEN -static ReturnCode isoDepDataExchangePICC(void); -static ReturnCode isoDepReSendControlMsg(void); -#endif - -/* - ****************************************************************************** - * LOCAL FUNCTIONS - ****************************************************************************** - */ - -/*******************************************************************************/ -static void isoDepClearCounters(void) { - gIsoDep.cntIRetrys = 0; - gIsoDep.cntRRetrys = 0; - gIsoDep.cntSDslRetrys = 0; - gIsoDep.cntSWtxRetrys = 0; - gIsoDep.cntSWtxNack = 0; -} - -/*******************************************************************************/ -static ReturnCode - isoDepTx(uint8_t pcb, const uint8_t* txBuf, uint8_t* infBuf, uint16_t infLen, uint32_t fwt) { - uint8_t* txBlock; - uint16_t txBufLen; - uint8_t computedPcb; - rfalTransceiveContext ctx; - - txBlock = infBuf; /* Point to beginning of the INF, and go backwards */ - gIsoDep.lastPCB = pcb; /* Store the last PCB sent */ - - if(infLen > 0U) { - if(((uint32_t)infBuf - (uint32_t)txBuf) < - gIsoDep.hdrLen) /* Check that we can fit the header in the given space */ - { - return ERR_NOMEM; - } - } - - /*******************************************************************************/ - /* Compute optional PCB bits */ - computedPcb = pcb; - if((gIsoDep.did != RFAL_ISODEP_NO_DID) || - ((gIsoDep.did == RFAL_ISODEP_DID_00) && gIsoDep.lastDID00)) { - computedPcb |= ISODEP_PCB_DID_BIT; - } - if(gIsoDep.nad != RFAL_ISODEP_NO_NAD) { - computedPcb |= ISODEP_PCB_NAD_BIT; - } - if((gIsoDep.isTxChaining) && (isoDep_PCBisIBlock(computedPcb))) { - computedPcb |= ISODEP_PCB_CHAINING_BIT; - } - - /*******************************************************************************/ - /* Compute Payload on the given txBuf, start by the PCB | DID | NAD | before INF */ - - if(gIsoDep.nad != RFAL_ISODEP_NO_NAD) { - *(--txBlock) = gIsoDep.nad; /* NAD is optional */ - } - - if((gIsoDep.did != RFAL_ISODEP_NO_DID) || - ((gIsoDep.did == RFAL_ISODEP_DID_00) && gIsoDep.lastDID00)) { - *(--txBlock) = gIsoDep.did; /* DID is optional */ - } - - *(--txBlock) = computedPcb; /* PCB always present */ - - txBufLen = - (infLen + - (uint16_t)((uint32_t)infBuf - (uint32_t)txBlock)); /* Calculate overall buffer size */ - - if(txBufLen > (gIsoDep.fsx - - ISODEP_CRC_LEN)) /* Check if msg length violates the maximum frame size FSC */ - { - return ERR_NOTSUPP; - } - - rfalCreateByteFlagsTxRxContext( - ctx, - txBlock, - txBufLen, - gIsoDep.rxBuf, - gIsoDep.rxBufLen, - gIsoDep.rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - ((gIsoDep.role == ISODEP_ROLE_PICC) ? RFAL_FWT_NONE : fwt)); - return rfalStartTransceive(&ctx); -} - -/*******************************************************************************/ -static ReturnCode isoDepHandleControlMsg(rfalIsoDepControlMsg controlMsg, uint8_t param) { - uint8_t pcb; - uint8_t infLen; - uint32_t fwtTemp; - - infLen = 0; - fwtTemp = (gIsoDep.fwt + gIsoDep.dFwt); - ST_MEMSET(gIsoDep.ctrlBuf, 0x00, ISODEP_CONTROLMSG_BUF_LEN); - - switch(controlMsg) { - /*******************************************************************************/ - case ISODEP_R_ACK: - - if(gIsoDep.cntRRetrys++ > gIsoDep.maxRetriesR) { - return ERR_TIMEOUT; /* NFC Forum mandates timeout or transmission error depending on previous errors */ - } - - pcb = isoDep_PCBRACK(gIsoDep.blockNumber); - break; - - /*******************************************************************************/ - case ISODEP_R_NAK: - - if((gIsoDep.cntRRetrys++ > gIsoDep.maxRetriesR) || /* Max R Block retries reached */ - (gIsoDep.cntSWtxNack >= - gIsoDep - .maxRetriesSnWTX)) /* Max number PICC is allowed to respond with S(WTX) to R(NAK) */ - { - return ERR_TIMEOUT; - } - - pcb = isoDep_PCBRNAK(gIsoDep.blockNumber); - break; - - /*******************************************************************************/ - case ISODEP_S_WTX: - - if((gIsoDep.cntSWtxRetrys++ > gIsoDep.maxRetriesSWTX) && - (gIsoDep.maxRetriesSWTX != RFAL_ISODEP_MAX_WTX_RETRYS_ULTD)) { - return ERR_PROTO; - } - - /* Check if WTXM is valid */ - if(!isoDep_isWTXMValid(param)) { - return ERR_PROTO; - } - - if(gIsoDep.role == ISODEP_ROLE_PCD) { - /* Calculate temp Wait Time eXtension */ - fwtTemp = (gIsoDep.fwt * param); - fwtTemp = MIN(RFAL_ISODEP_MAX_FWT, fwtTemp); - fwtTemp += gIsoDep.dFwt; - } - - pcb = ISODEP_PCB_SWTX; - gIsoDep.ctrlBuf[RFAL_ISODEP_PCB_LEN + RFAL_ISODEP_DID_LEN + infLen++] = param; - break; - - /*******************************************************************************/ - case ISODEP_S_DSL: - - if(gIsoDep.cntSDslRetrys++ > gIsoDep.maxRetriesSDSL) { - return ERR_TIMEOUT; /* NFC Forum mandates timeout or transmission error depending on previous errors */ - } - - if(gIsoDep.role == ISODEP_ROLE_PCD) { - /* Digital 1.0 - 13.2.7.3 Poller must wait fwtDEACTIVATION */ - fwtTemp = ISODEP_FWT_DEACTIVATION; - gIsoDep.state = ISODEP_ST_PCD_WAIT_DSL; - } - pcb = ISODEP_PCB_SDSL; - break; - - /*******************************************************************************/ - default: - return ERR_INTERNAL; - } - - return isoDepTx( - pcb, - gIsoDep.ctrlBuf, - &gIsoDep.ctrlBuf[RFAL_ISODEP_PCB_LEN + RFAL_ISODEP_DID_LEN], - infLen, - fwtTemp); -} - -#if RFAL_FEATURE_ISO_DEP_LISTEN -/*******************************************************************************/ -static ReturnCode isoDepReSendControlMsg(void) { - if(isoDep_PCBisRACK(gIsoDep.lastPCB)) { - return isoDepHandleControlMsg(ISODEP_R_ACK, RFAL_ISODEP_NO_PARAM); - } - - if(isoDep_PCBisRNAK(gIsoDep.lastPCB)) { - return isoDepHandleControlMsg(ISODEP_R_NAK, RFAL_ISODEP_NO_PARAM); - } - - if(isoDep_PCBisSDeselect(gIsoDep.lastPCB)) { - return isoDepHandleControlMsg(ISODEP_S_DSL, RFAL_ISODEP_NO_PARAM); - } - - if(isoDep_PCBisSWTX(gIsoDep.lastPCB)) { - return isoDepHandleControlMsg(ISODEP_S_WTX, gIsoDep.lastWTXM); - } - return ERR_WRONG_STATE; -} -#endif /* RFAL_FEATURE_ISO_DEP_LISTEN */ - -/* - ****************************************************************************** - * GLOBAL FUNCTIONS - ****************************************************************************** - */ - -/*******************************************************************************/ -void rfalIsoDepInitialize(void) { - gIsoDep.state = ISODEP_ST_IDLE; - gIsoDep.role = ISODEP_ROLE_PCD; - gIsoDep.did = RFAL_ISODEP_NO_DID; - gIsoDep.nad = RFAL_ISODEP_NO_NAD; - gIsoDep.blockNumber = 0; - gIsoDep.isTxChaining = false; - gIsoDep.isRxChaining = false; - gIsoDep.lastDID00 = false; - gIsoDep.lastPCB = ISODEP_PCB_INVALID; - gIsoDep.fsx = (uint16_t)RFAL_ISODEP_FSX_16; - gIsoDep.ourFsx = (uint16_t)RFAL_ISODEP_FSX_16; - gIsoDep.hdrLen = RFAL_ISODEP_PCB_LEN; - - gIsoDep.rxLen = NULL; - gIsoDep.rxBuf = NULL; - gIsoDep.rxBufInfPos = 0U; - gIsoDep.txBufInfPos = 0U; - - gIsoDep.isTxPending = false; - gIsoDep.isWait4WTX = false; - - gIsoDep.compMode = RFAL_COMPLIANCE_MODE_NFC; - gIsoDep.maxRetriesR = RFAL_ISODEP_MAX_R_RETRYS; - gIsoDep.maxRetriesI = RFAL_ISODEP_MAX_I_RETRYS; - gIsoDep.maxRetriesSDSL = RFAL_ISODEP_MAX_DSL_RETRYS; - gIsoDep.maxRetriesSWTX = RFAL_ISODEP_MAX_WTX_RETRYS; - gIsoDep.maxRetriesSnWTX = RFAL_ISODEP_MAX_WTX_NACK_RETRYS; - gIsoDep.maxRetriesRATS = RFAL_ISODEP_RATS_RETRIES; - - gIsoDep.APDURxPos = 0; - gIsoDep.APDUTxPos = 0; - gIsoDep.APDUParam.rxLen = NULL; - gIsoDep.APDUParam.rxBuf = NULL; - gIsoDep.APDUParam.txBuf = NULL; - - isoDepClearCounters(); - - /* Destroy any ongoing WTX timer */ - isoDepTimerDestroy(gIsoDep.WTXTimer); - gIsoDep.WTXTimer = 0U; -} - -/*******************************************************************************/ -void rfalIsoDepInitializeWithParams( - rfalComplianceMode compMode, - uint8_t maxRetriesR, - uint8_t maxRetriesSnWTX, - uint8_t maxRetriesSWTX, - uint8_t maxRetriesSDSL, - uint8_t maxRetriesI, - uint8_t maxRetriesRATS) { - rfalIsoDepInitialize(); - - gIsoDep.compMode = compMode; - gIsoDep.maxRetriesR = maxRetriesR; - gIsoDep.maxRetriesSnWTX = maxRetriesSnWTX; - gIsoDep.maxRetriesSWTX = maxRetriesSWTX; - gIsoDep.maxRetriesSDSL = maxRetriesSDSL; - gIsoDep.maxRetriesI = maxRetriesI; - gIsoDep.maxRetriesRATS = maxRetriesRATS; -} - -#if RFAL_FEATURE_ISO_DEP_POLL -/*******************************************************************************/ -static ReturnCode isoDepDataExchangePCD(uint16_t* outActRxLen, bool* outIsChaining) { - ReturnCode ret; - uint8_t rxPCB; - - /* Check out parameters */ - if((outActRxLen == NULL) || (outIsChaining == NULL)) { - return ERR_PARAM; - } - - *outIsChaining = false; - - /* Calculate header required and check if the buffers InfPositions are suitable */ - gIsoDep.hdrLen = RFAL_ISODEP_PCB_LEN; - if(gIsoDep.did != RFAL_ISODEP_NO_DID) { - gIsoDep.hdrLen += RFAL_ISODEP_DID_LEN; - } - if(gIsoDep.nad != RFAL_ISODEP_NO_NAD) { - gIsoDep.hdrLen += RFAL_ISODEP_NAD_LEN; - } - - /* Check if there is enough space before the infPos to append ISO-DEP headers on rx and tx */ - if((gIsoDep.rxBufInfPos < gIsoDep.hdrLen) || (gIsoDep.txBufInfPos < gIsoDep.hdrLen)) { - return ERR_PARAM; - } - - /*******************************************************************************/ - switch(gIsoDep.state) { - /*******************************************************************************/ - case ISODEP_ST_IDLE: - return ERR_NONE; - - /*******************************************************************************/ - case ISODEP_ST_PCD_TX: - ret = isoDepTx( - isoDep_PCBIBlock(gIsoDep.blockNumber), - gIsoDep.txBuf, - &gIsoDep.txBuf[gIsoDep.txBufInfPos], - gIsoDep.txBufLen, - (gIsoDep.fwt + gIsoDep.dFwt)); - switch(ret) { - case ERR_NONE: - gIsoDep.state = ISODEP_ST_PCD_RX; - break; - - default: - return ret; - } - /* fall through */ - - /*******************************************************************************/ - case ISODEP_ST_PCD_WAIT_DSL: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - case ISODEP_ST_PCD_RX: - - ret = rfalGetTransceiveStatus(); - switch(ret) { - /* Data rcvd with error or timeout -> Send R-NAK */ - case ERR_TIMEOUT: - case ERR_CRC: - case ERR_PAR: - case ERR_FRAMING: /* added to handle test cases scenario TC_POL_NFCB_T4AT_BI_82_x_y & TC_POL_NFCB_T4BT_BI_82_x_y */ - case ERR_INCOMPLETE_BYTE: /* added to handle test cases scenario TC_POL_NFCB_T4AT_BI_82_x_y & TC_POL_NFCB_T4BT_BI_82_x_y */ - - if(gIsoDep - .isRxChaining) { /* Rule 5 - In PICC chaining when a invalid/timeout occurs -> R-ACK */ - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_R_ACK, RFAL_ISODEP_NO_PARAM)); - } else if( - gIsoDep.state == - ISODEP_ST_PCD_WAIT_DSL) { /* Rule 8 - If s-Deselect response fails MAY retransmit */ - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_S_DSL, RFAL_ISODEP_NO_PARAM)); - } else { /* Rule 4 - When a invalid block or timeout occurs -> R-NACK */ - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_R_NAK, RFAL_ISODEP_NO_PARAM)); - } - return ERR_BUSY; - - case ERR_NONE: - break; - - case ERR_BUSY: - return ERR_BUSY; /* Debug purposes */ - - default: - return ret; - } - - /*******************************************************************************/ - /* No error, process incoming msg */ - /*******************************************************************************/ - - (*outActRxLen) = rfalConvBitsToBytes(*outActRxLen); - - /* Check rcvd msg length, cannot be less then the expected header */ - if(((*outActRxLen) < gIsoDep.hdrLen) || ((*outActRxLen) >= gIsoDep.ourFsx)) { - return ERR_PROTO; - } - - /* Grab rcvd PCB */ - rxPCB = gIsoDep.rxBuf[ISODEP_PCB_POS]; - - /* EMVCo doesn't allow usage of for CID or NAD EMVCo 2.6 TAble 10.2 */ - if((gIsoDep.compMode == RFAL_COMPLIANCE_MODE_EMV) && - (isoDep_PCBhasDID(rxPCB) || isoDep_PCBhasNAD(rxPCB))) { - return ERR_PROTO; - } - - /* If we are expecting DID, check if PCB signals its presence and if device ID match*/ - if((gIsoDep.did != RFAL_ISODEP_NO_DID) && - (!isoDep_PCBhasDID(rxPCB) || (gIsoDep.did != gIsoDep.rxBuf[ISODEP_DID_POS]))) { - return ERR_PROTO; - } - - /*******************************************************************************/ - /* Process S-Block */ - /*******************************************************************************/ - if(isoDep_PCBisSBlock(rxPCB)) { - /* Check if is a Wait Time eXtension */ - if(isoDep_PCBisSWTX(rxPCB)) { - /* Check if PICC has requested S(WTX) as response to R(NAK) EMVCo 3.0 10.3.5.5 / Digital 2.0 16.2.6.5 */ - if(isoDep_PCBisRNAK(gIsoDep.lastPCB)) { - gIsoDep.cntSWtxNack++; /* Count S(WTX) upon R(NAK) */ - gIsoDep.cntRRetrys = 0; /* Reset R-Block counter has PICC has responded */ - } else { - gIsoDep.cntSWtxNack = 0; /* Reset R(NACK)->S(WTX) counter */ - } - - /* Rule 3 - respond to S-block: get 1st INF byte S(STW): Power + WTXM */ - EXIT_ON_ERR( - ret, - isoDepHandleControlMsg( - ISODEP_S_WTX, isoDep_GetWTXM(gIsoDep.rxBuf[gIsoDep.hdrLen]))); - return ERR_BUSY; - } - - /* Check if is a deselect response */ - if(isoDep_PCBisSDeselect(rxPCB)) { - if(gIsoDep.state == ISODEP_ST_PCD_WAIT_DSL) { - rfalIsoDepInitialize(); /* Session finished reInit vars */ - return ERR_NONE; - } - - /* Deselect response not expected */ - /* fall through to PROTO error */ - } - /* Unexpected S-Block */ - return ERR_PROTO; - } - - /*******************************************************************************/ - /* Process R-Block */ - /*******************************************************************************/ - else if(isoDep_PCBisRBlock(rxPCB)) { - if(isoDep_PCBisRACK(rxPCB)) /* Check if is a R-ACK */ - { - if(isoDep_GetBN(rxPCB) == gIsoDep.blockNumber) /* Expected block number */ - { - /* Rule B - ACK with expected bn -> Increment block number */ - gIsoDep.blockNumber = isoDep_PCBNextBN(gIsoDep.blockNumber); - - /* R-ACK only allowed when PCD chaining */ - if(!gIsoDep.isTxChaining) { - return ERR_PROTO; - } - - /* Rule 7 - Chaining transaction done, continue chaining */ - isoDepClearCounters(); - return ERR_NONE; /* This block has been transmitted */ - } else { - /* Rule 6 - R-ACK with wrong block number retransmit */ - /* Digital 2.0 16.2.5.4 - Retransmit maximum two times */ - /* EMVCo 3.0 10.3.4.3 - PCD may re-transmit the last I-Block or report error */ - if(gIsoDep.cntIRetrys++ < gIsoDep.maxRetriesI) { - gIsoDep.cntRRetrys = 0; /* Clear R counter only */ - gIsoDep.state = ISODEP_ST_PCD_TX; - return ERR_BUSY; - } - return ERR_TIMEOUT; /* NFC Forum mandates timeout or transmission error depending on previous errors */ - } - } else /* Unexpected R-Block */ - { - return ERR_PROTO; - } - } - - /*******************************************************************************/ - /* Process I-Block */ - /*******************************************************************************/ - else if(isoDep_PCBisIBlock(rxPCB)) { - /*******************************************************************************/ - /* is PICC performing chaining */ - if(isoDep_PCBisChaining(rxPCB)) { - gIsoDep.isRxChaining = true; - *outIsChaining = true; - - if(isoDep_GetBN(rxPCB) == gIsoDep.blockNumber) { - /* Rule B - ACK with correct block number -> Increase Block number */ - isoDep_ToggleBN(gIsoDep.blockNumber); - - isoDepClearCounters(); /* Clear counters in case R counter is already at max */ - - /* Rule 2 - Send ACK */ - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_R_ACK, RFAL_ISODEP_NO_PARAM)); - - /* Received I-Block with chaining, send current data to DH */ - - /* remove ISO DEP header, check is necessary to move the INF data on the buffer */ - *outActRxLen -= gIsoDep.hdrLen; - if((gIsoDep.hdrLen != gIsoDep.rxBufInfPos) && (*outActRxLen > 0U)) { - ST_MEMMOVE( - &gIsoDep.rxBuf[gIsoDep.rxBufInfPos], - &gIsoDep.rxBuf[gIsoDep.hdrLen], - *outActRxLen); - } - - isoDepClearCounters(); - return ERR_AGAIN; /* Send Again signalling to run again, but some chaining data has arrived */ - } else { - /* Rule 5 - PICC chaining invalid I-Block -> R-ACK */ - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_R_ACK, RFAL_ISODEP_NO_PARAM)); - } - return ERR_BUSY; - } - - gIsoDep.isRxChaining = false; /* clear PICC chaining flag */ - - if(isoDep_GetBN(rxPCB) == gIsoDep.blockNumber) { - /* Rule B - I-Block with correct block number -> Increase Block number */ - isoDep_ToggleBN(gIsoDep.blockNumber); - - /* I-Block transaction done successfully */ - - /* remove ISO DEP header, check is necessary to move the INF data on the buffer */ - *outActRxLen -= gIsoDep.hdrLen; - if((gIsoDep.hdrLen != gIsoDep.rxBufInfPos) && (*outActRxLen > 0U)) { - ST_MEMMOVE( - &gIsoDep.rxBuf[gIsoDep.rxBufInfPos], - &gIsoDep.rxBuf[gIsoDep.hdrLen], - *outActRxLen); - } - - gIsoDep.state = ISODEP_ST_IDLE; - isoDepClearCounters(); - return ERR_NONE; - } else { - if((gIsoDep.compMode != RFAL_COMPLIANCE_MODE_ISO)) { - /* Invalid Block (not chaining) -> Raise error Digital 1.1 15.2.6.4 EMVCo 2.6 10.3.5.4 */ - return ERR_PROTO; - } - - /* Rule 4 - Invalid Block -> R-NAK */ - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_R_NAK, RFAL_ISODEP_NO_PARAM)); - return ERR_BUSY; - } - } else /* not S/R/I - Block */ - { - return ERR_PROTO; - } - /* fall through */ - - /*******************************************************************************/ - default: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - /* MISRA 16.4: no empty default (comment will suffice) */ - break; - } - - return ERR_INTERNAL; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepDeselect(void) { - ReturnCode ret; - uint32_t cntRerun; - bool dummyB; - - /*******************************************************************************/ - /* Using local static vars and static config to cope with a Deselect after * - * RATS\ATTRIB without any I-Block exchanged */ - gIsoDep.rxLen = &gIsoDep.ctrlRxLen; - gIsoDep.rxBuf = gIsoDep.ctrlBuf; - gIsoDep.rxBufLen = ISODEP_CONTROLMSG_BUF_LEN - (RFAL_ISODEP_PCB_LEN + RFAL_ISODEP_DID_LEN); - gIsoDep.rxBufInfPos = (RFAL_ISODEP_PCB_LEN + RFAL_ISODEP_DID_LEN); - gIsoDep.txBufInfPos = (RFAL_ISODEP_PCB_LEN + RFAL_ISODEP_DID_LEN); - - /*******************************************************************************/ - /* The Deselect process is being done blocking, Digital 1.0 - 13.2.7.1 MUST wait response and retry*/ - /* Set the maximum reruns while we will wait for a response */ - cntRerun = ISODEP_MAX_RERUNS; - - /* Send DSL request and run protocol until get a response, error or "timeout" */ - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_S_DSL, RFAL_ISODEP_NO_PARAM)); - do { - ret = isoDepDataExchangePCD(gIsoDep.rxLen, &dummyB); - rfalWorker(); - } while(((cntRerun--) != 0U) && (ret == ERR_BUSY)); - - rfalIsoDepInitialize(); - return ((cntRerun == 0U) ? ERR_TIMEOUT : ret); -} - -#endif /* RFAL_FEATURE_ISO_DEP_POLL */ - -/*******************************************************************************/ -uint32_t rfalIsoDepFWI2FWT(uint8_t fwi) { - uint32_t result; - uint8_t tmpFWI; - - tmpFWI = fwi; - - /* RFU values -> take the default value - * Digital 1.0 11.6.2.17 FWI[1,14] - * Digital 1.1 7.6.2.22 FWI[0,14] - * EMVCo 2.6 Table A.5 FWI[0,14] */ - if(tmpFWI > ISODEP_FWI_MAX) { - tmpFWI = RFAL_ISODEP_FWI_DEFAULT; - } - - /* FWT = (256 x 16/fC) x 2^FWI => 2^(FWI+12) Digital 1.1 13.8.1 & 7.9.1 */ - - result = ((uint32_t)1U << (tmpFWI + 12U)); - result = MIN(RFAL_ISODEP_MAX_FWT, result); /* Maximum Frame Waiting Time must be fulfilled */ - - return result; -} - -/*******************************************************************************/ -uint16_t rfalIsoDepFSxI2FSx(uint8_t FSxI) { - uint16_t fsx; - uint8_t fsi; - - /* Enforce maximum FSxI/FSx allowed - NFC Forum and EMVCo differ */ - fsi = - ((gIsoDep.compMode == RFAL_COMPLIANCE_MODE_EMV) ? MIN(FSxI, RFAL_ISODEP_FSDI_MAX_EMV) : - MIN(FSxI, RFAL_ISODEP_FSDI_MAX_NFC)); - - switch(fsi) { - case(uint8_t)RFAL_ISODEP_FSXI_16: - fsx = (uint16_t)RFAL_ISODEP_FSX_16; - break; - case(uint8_t)RFAL_ISODEP_FSXI_24: - fsx = (uint16_t)RFAL_ISODEP_FSX_24; - break; - case(uint8_t)RFAL_ISODEP_FSXI_32: - fsx = (uint16_t)RFAL_ISODEP_FSX_32; - break; - case(uint8_t)RFAL_ISODEP_FSXI_40: - fsx = (uint16_t)RFAL_ISODEP_FSX_40; - break; - case(uint8_t)RFAL_ISODEP_FSXI_48: - fsx = (uint16_t)RFAL_ISODEP_FSX_48; - break; - case(uint8_t)RFAL_ISODEP_FSXI_64: - fsx = (uint16_t)RFAL_ISODEP_FSX_64; - break; - case(uint8_t)RFAL_ISODEP_FSXI_96: - fsx = (uint16_t)RFAL_ISODEP_FSX_96; - break; - case(uint8_t)RFAL_ISODEP_FSXI_128: - fsx = (uint16_t)RFAL_ISODEP_FSX_128; - break; - case(uint8_t)RFAL_ISODEP_FSXI_256: - fsx = (uint16_t)RFAL_ISODEP_FSX_256; - break; - case(uint8_t)RFAL_ISODEP_FSXI_512: - fsx = (uint16_t)RFAL_ISODEP_FSX_512; - break; - case(uint8_t)RFAL_ISODEP_FSXI_1024: - fsx = (uint16_t)RFAL_ISODEP_FSX_1024; - break; - case(uint8_t)RFAL_ISODEP_FSXI_2048: - fsx = (uint16_t)RFAL_ISODEP_FSX_2048; - break; - case(uint8_t)RFAL_ISODEP_FSXI_4096: - fsx = (uint16_t)RFAL_ISODEP_FSX_4096; - break; - default: - fsx = (uint16_t)RFAL_ISODEP_FSX_256; - break; - } - return fsx; -} - -#if RFAL_FEATURE_ISO_DEP_LISTEN - -/*******************************************************************************/ -bool rfalIsoDepIsRats(const uint8_t* buf, uint8_t bufLen) { - if(buf != NULL) { - if((RFAL_ISODEP_CMD_RATS == (uint8_t)*buf) && (sizeof(rfalIsoDepRats) == bufLen)) { - return true; - } - } - return false; -} - -/*******************************************************************************/ -bool rfalIsoDepIsAttrib(const uint8_t* buf, uint8_t bufLen) { - if(buf != NULL) { - if((RFAL_ISODEP_CMD_ATTRIB == (uint8_t)*buf) && - (RFAL_ISODEP_ATTRIB_REQ_MIN_LEN <= bufLen) && - ((RFAL_ISODEP_ATTRIB_REQ_MIN_LEN + RFAL_ISODEP_ATTRIB_HLINFO_LEN) >= bufLen)) { - return true; - } - } - return false; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepListenStartActivation( - rfalIsoDepAtsParam* atsParam, - const rfalIsoDepAttribResParam* attribResParam, - const uint8_t* buf, - uint16_t bufLen, - rfalIsoDepListenActvParam actParam) { - uint8_t* txBuf; - uint8_t bufIt; - const uint8_t* buffer = buf; - - /*******************************************************************************/ - bufIt = 0; - txBuf = - (uint8_t*)actParam - .rxBuf; /* Use the rxBuf as TxBuf as well, the struct enforces a size enough MAX( NFCA_ATS_MAX_LEN, NFCB_ATTRIB_RES_MAX_LEN ) */ - gIsoDep.txBR = RFAL_BR_106; - gIsoDep.rxBR = RFAL_BR_106; - - /* Check for a valid buffer pointer */ - if(buffer == NULL) { - return ERR_PARAM; - } - - /*******************************************************************************/ - if(*buffer == RFAL_ISODEP_CMD_RATS) { - /* Check ATS parameters */ - if(atsParam == NULL) { - return ERR_PARAM; - } - - /* If requested copy RATS to device info */ - if(actParam.isoDepDev != NULL) { - ST_MEMCPY( - (uint8_t*)&actParam.isoDepDev->activation.A.Poller.RATS, - buffer, - sizeof(rfalIsoDepRats)); /* Copy RATS' CMD + PARAM */ - } - - /*******************************************************************************/ - /* Process RATS */ - buffer++; - gIsoDep.fsx = rfalIsoDepFSxI2FSx( - (((*buffer) & RFAL_ISODEP_RATS_PARAM_FSDI_MASK) >> RFAL_ISODEP_RATS_PARAM_FSDI_SHIFT)); - gIsoDep.did = (*buffer & RFAL_ISODEP_DID_MASK); - - /*******************************************************************************/ - /* Digital 1.1 13.6.1.8 - DID as to between 0 and 14 */ - if(gIsoDep.did > RFAL_ISODEP_DID_MAX) { - return ERR_PROTO; - } - - /* Check if we are configured to support DID */ - if((gIsoDep.did != RFAL_ISODEP_DID_00) && (!atsParam->didSupport)) { - return ERR_NOTSUPP; - } - - /*******************************************************************************/ - /* Check RFAL supported bit rates */ - if((!(RFAL_SUPPORT_BR_CE_A_212) && - (((atsParam->ta & RFAL_ISODEP_ATS_TA_DPL_212) != 0U) || - ((atsParam->ta & RFAL_ISODEP_ATS_TA_DLP_212) != 0U))) || - (!(RFAL_SUPPORT_BR_CE_A_424) && - (((atsParam->ta & RFAL_ISODEP_ATS_TA_DPL_424) != 0U) || - ((atsParam->ta & RFAL_ISODEP_ATS_TA_DLP_424) != 0U))) || - (!(RFAL_SUPPORT_BR_CE_A_848) && - (((atsParam->ta & RFAL_ISODEP_ATS_TA_DPL_848) != 0U) || - ((atsParam->ta & RFAL_ISODEP_ATS_TA_DLP_848) != 0U)))) { - return ERR_NOTSUPP; - } - - /* Enforce proper FWI configuration */ - if(atsParam->fwi > ISODEP_FWI_LIS_MAX) { - atsParam->fwi = ISODEP_FWI_LIS_MAX; - } - - gIsoDep.atsTA = atsParam->ta; - gIsoDep.fwt = rfalIsoDepFWI2FWT(atsParam->fwi); - gIsoDep.ourFsx = rfalIsoDepFSxI2FSx(atsParam->fsci); - - /* Ensure proper/maximum Historical Bytes length */ - atsParam->hbLen = MIN(RFAL_ISODEP_ATS_HB_MAX_LEN, atsParam->hbLen); - - /*******************************************************************************/ - /* Compute ATS */ - - txBuf[bufIt++] = (RFAL_ISODEP_ATS_HIST_OFFSET + atsParam->hbLen); /* TL */ - txBuf[bufIt++] = - ((RFAL_ISODEP_ATS_T0_TA_PRESENCE_MASK | RFAL_ISODEP_ATS_T0_TB_PRESENCE_MASK | - RFAL_ISODEP_ATS_T0_TC_PRESENCE_MASK) | - atsParam->fsci); /* T0 */ - txBuf[bufIt++] = atsParam->ta; /* TA */ - txBuf[bufIt++] = - ((atsParam->fwi << RFAL_ISODEP_RATS_PARAM_FSDI_SHIFT) | - (atsParam->sfgi & RFAL_ISODEP_RATS_PARAM_FSDI_MASK)); /* TB */ - txBuf[bufIt++] = (uint8_t)((atsParam->didSupport) ? RFAL_ISODEP_ATS_TC_DID : 0U); /* TC */ - - if(atsParam->hbLen > 0U) /* MISRA 21.18 */ - { - ST_MEMCPY(&txBuf[bufIt], atsParam->hb, atsParam->hbLen); /* T1-Tk */ - bufIt += atsParam->hbLen; - } - - gIsoDep.state = ISODEP_ST_PICC_ACT_ATS; - - } - /*******************************************************************************/ - else if(*buffer == RFAL_ISODEP_CMD_ATTRIB) { - /* Check ATTRIB parameters */ - if(attribResParam == NULL) { - return ERR_PARAM; - } - - /* REMARK: ATTRIB handling */ - NO_WARNING(attribResParam); - NO_WARNING(bufLen); - return ERR_NOT_IMPLEMENTED; - } else { - return ERR_PARAM; - } - - gIsoDep.actvParam = actParam; - - /*******************************************************************************/ - /* If requested copy to ISO-DEP device info */ - if(actParam.isoDepDev != NULL) { - actParam.isoDepDev->info.DID = gIsoDep.did; - actParam.isoDepDev->info.FSx = gIsoDep.fsx; - actParam.isoDepDev->info.FWT = gIsoDep.fwt; - actParam.isoDepDev->info.dFWT = 0; - actParam.isoDepDev->info.DSI = gIsoDep.txBR; - actParam.isoDepDev->info.DRI = gIsoDep.rxBR; - } - - return rfalTransceiveBlockingTx( - txBuf, - bufIt, - (uint8_t*)actParam.rxBuf, - sizeof(rfalIsoDepBufFormat), - actParam.rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_FWT_NONE); -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepListenGetActivationStatus(void) { - ReturnCode err; - uint8_t* txBuf; - uint8_t bufIt; - - rfalBitRate dsi; - rfalBitRate dri; - - /* Check if Activation is running */ - if(gIsoDep.state < ISODEP_ST_PICC_ACT_ATS) { - return ERR_WRONG_STATE; - } - - /* Check if Activation has finished already */ - if(gIsoDep.state >= ISODEP_ST_PICC_RX) { - return ERR_NONE; - } - - /*******************************************************************************/ - /* Check for incoming msg */ - err = rfalGetTransceiveStatus(); - switch(err) { - /*******************************************************************************/ - case ERR_NONE: - break; - - /*******************************************************************************/ - case ERR_LINK_LOSS: - case ERR_BUSY: - return err; - - /*******************************************************************************/ - case ERR_CRC: - case ERR_PAR: - case ERR_FRAMING: - - /* ISO14443 4 5.6.2.2 2 If ATS has been replied upon a invalid block, PICC disables the PPS responses */ - if(gIsoDep.state == ISODEP_ST_PICC_ACT_ATS) { - gIsoDep.state = ISODEP_ST_PICC_RX; - break; - } - /* fall through */ - - /*******************************************************************************/ - default: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - /* ReEnable the receiver and wait for another frame */ - isoDepReEnableRx( - (uint8_t*)gIsoDep.actvParam.rxBuf, - sizeof(rfalIsoDepBufFormat), - gIsoDep.actvParam.rxLen); - - return ERR_BUSY; - } - - txBuf = - (uint8_t*)gIsoDep.actvParam - .rxBuf; /* Use the rxBuf as TxBuf as well, the struct enforces a size enough MAX(NFCA_PPS_RES_LEN, ISODEP_DSL_MAX_LEN) */ - dri = RFAL_BR_KEEP; /* The RFAL_BR_KEEP is used to check if PPS with BR change was requested */ - dsi = RFAL_BR_KEEP; /* MISRA 9.1 */ - bufIt = 0; - - /*******************************************************************************/ - gIsoDep.role = ISODEP_ROLE_PICC; - - /*******************************************************************************/ - if(gIsoDep.state == ISODEP_ST_PICC_ACT_ATS) { - /* Check for a PPS ISO 14443-4 5.3 */ - if((((uint8_t*)gIsoDep.actvParam.rxBuf)[RFAL_ISODEP_PPS_STARTBYTE_POS] & - RFAL_ISODEP_PPS_MASK) == RFAL_ISODEP_PPS_SB) { - /* ISO 14443-4 5.3.1 Check if the we are the addressed DID/CID */ - /* ISO 14443-4 5.3.2 Check for a valid PPS0 */ - if(((((uint8_t*)gIsoDep.actvParam.rxBuf)[RFAL_ISODEP_PPS_STARTBYTE_POS] & - RFAL_ISODEP_DID_MASK) != gIsoDep.did) || - ((((uint8_t*)gIsoDep.actvParam.rxBuf)[RFAL_ISODEP_PPS_PPS0_POS] & - RFAL_ISODEP_PPS0_VALID_MASK) != RFAL_ISODEP_PPS0_PPS1_NOT_PRESENT)) { - /* Invalid DID on PPS request or Invalid PPS0, reEnable the receiver and wait another frame */ - isoDepReEnableRx( - (uint8_t*)gIsoDep.actvParam.rxBuf, - sizeof(rfalIsoDepBufFormat), - gIsoDep.actvParam.rxLen); - - return ERR_BUSY; - } - - /*******************************************************************************/ - /* Check PPS1 presence */ - if(((uint8_t*)gIsoDep.actvParam.rxBuf)[RFAL_ISODEP_PPS_PPS0_POS] == - RFAL_ISODEP_PPS0_PPS1_PRESENT) { - uint8_t newdri = ((uint8_t*)gIsoDep.actvParam.rxBuf)[RFAL_ISODEP_PPS_PPS1_POS] & - RFAL_ISODEP_PPS1_DxI_MASK; /* MISRA 10.8 */ - uint8_t newdsi = (((uint8_t*)gIsoDep.actvParam.rxBuf)[RFAL_ISODEP_PPS_PPS1_POS] >> - RFAL_ISODEP_PPS1_DSI_SHIFT) & - RFAL_ISODEP_PPS1_DxI_MASK; /* MISRA 10.8 */ - /* PRQA S 4342 2 # MISRA 10.5 - Layout of enum rfalBitRate and above masks guarantee no invalid enum values to be created */ - dri = (rfalBitRate)(newdri); - dsi = (rfalBitRate)(newdsi); - - if((!(RFAL_SUPPORT_BR_CE_A_106) && - ((dsi == RFAL_BR_106) || (dri == RFAL_BR_106))) || - (!(RFAL_SUPPORT_BR_CE_A_212) && - ((dsi == RFAL_BR_212) || (dri == RFAL_BR_212))) || - (!(RFAL_SUPPORT_BR_CE_A_424) && - ((dsi == RFAL_BR_424) || (dri == RFAL_BR_424))) || - (!(RFAL_SUPPORT_BR_CE_A_848) && - ((dsi == RFAL_BR_848) || (dri == RFAL_BR_848)))) { - return ERR_PROTO; - } - } - - /*******************************************************************************/ - /* Compute and send PPS RES / Ack */ - txBuf[bufIt++] = ((uint8_t*)gIsoDep.actvParam.rxBuf)[RFAL_ISODEP_PPS_STARTBYTE_POS]; - - rfalTransceiveBlockingTx( - txBuf, - bufIt, - (uint8_t*)gIsoDep.actvParam.rxBuf, - sizeof(rfalIsoDepBufFormat), - gIsoDep.actvParam.rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_FWT_NONE); - - /*******************************************************************************/ - /* Exchange the bit rates if requested */ - if(dri != RFAL_BR_KEEP) { - rfalSetBitRate( - dsi, - dri); /* PRQA S 2880 # MISRA 2.1 - Unreachable code due to configuration option being set/unset above (RFAL_SUPPORT_BR_CE_A_xxx) */ - - gIsoDep.txBR = dsi; /* DSI codes the divisor from PICC to PCD */ - gIsoDep.rxBR = dri; /* DRI codes the divisor from PCD to PICC */ - - if(gIsoDep.actvParam.isoDepDev != NULL) { - gIsoDep.actvParam.isoDepDev->info.DSI = dsi; - gIsoDep.actvParam.isoDepDev->info.DRI = dri; - } - } - } - /* Check for a S-Deselect is done on Data Exchange Activity */ - } - - /*******************************************************************************/ - gIsoDep.hdrLen = RFAL_ISODEP_PCB_LEN; - gIsoDep.hdrLen += - RFAL_ISODEP_DID_LEN; /* Always assume DID to be aligned with Digital 1.1 15.1.2 and ISO14443 4 5.6.3 #454 */ - gIsoDep.hdrLen += (uint8_t)((gIsoDep.nad != RFAL_ISODEP_NO_NAD) ? RFAL_ISODEP_NAD_LEN : 0U); - - /*******************************************************************************/ - /* Rule C - The PICC block number shall be initialized to 1 at activation */ - gIsoDep.blockNumber = 1; - - /* Activation done, keep the rcvd data in, reMap the activation buffer to the global to be retrieved by the DEP method */ - gIsoDep.rxBuf = (uint8_t*)gIsoDep.actvParam.rxBuf; - gIsoDep.rxBufLen = sizeof(rfalIsoDepBufFormat); - gIsoDep.rxBufInfPos = - (uint8_t)((uint32_t)gIsoDep.actvParam.rxBuf->inf - (uint32_t)gIsoDep.actvParam.rxBuf->prologue); - gIsoDep.rxLen = gIsoDep.actvParam.rxLen; - gIsoDep.rxChaining = gIsoDep.actvParam.isRxChaining; - - gIsoDep.state = ISODEP_ST_PICC_RX; - return ERR_NONE; -} - -#endif /* RFAL_FEATURE_ISO_DEP_LISTEN */ - -/*******************************************************************************/ -uint16_t rfalIsoDepGetMaxInfLen(void) { - /* Check whether all parameters are valid, otherwise return minimum default value */ - if((gIsoDep.fsx < (uint16_t)RFAL_ISODEP_FSX_16) || - (gIsoDep.fsx > (uint16_t)RFAL_ISODEP_FSX_4096) || (gIsoDep.hdrLen > ISODEP_HDR_MAX_LEN)) { - uint16_t isodepFsx16 = (uint16_t)RFAL_ISODEP_FSX_16; /* MISRA 10.1 */ - return (isodepFsx16 - RFAL_ISODEP_PCB_LEN - ISODEP_CRC_LEN); - } - - return (gIsoDep.fsx - gIsoDep.hdrLen - ISODEP_CRC_LEN); -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepStartTransceive(rfalIsoDepTxRxParam param) { - gIsoDep.txBuf = param.txBuf->prologue; - gIsoDep.txBufInfPos = (uint8_t)((uint32_t)param.txBuf->inf - (uint32_t)param.txBuf->prologue); - gIsoDep.txBufLen = param.txBufLen; - gIsoDep.isTxChaining = param.isTxChaining; - - gIsoDep.rxBuf = param.rxBuf->prologue; - gIsoDep.rxBufInfPos = (uint8_t)((uint32_t)param.rxBuf->inf - (uint32_t)param.rxBuf->prologue); - gIsoDep.rxBufLen = sizeof(rfalIsoDepBufFormat); - - gIsoDep.rxLen = param.rxLen; - gIsoDep.rxChaining = param.isRxChaining; - - gIsoDep.fwt = param.FWT; - gIsoDep.dFwt = param.dFWT; - gIsoDep.fsx = param.FSx; - gIsoDep.did = param.DID; - - /* Only change the FSx from activation if no to Keep */ - gIsoDep.ourFsx = ((param.ourFSx != RFAL_ISODEP_FSX_KEEP) ? param.ourFSx : gIsoDep.ourFsx); - - /* Clear inner control params for next dataExchange */ - gIsoDep.isRxChaining = false; - isoDepClearCounters(); - - if(gIsoDep.role == ISODEP_ROLE_PICC) { - if(gIsoDep.txBufLen > 0U) { - /* Ensure that an RTOX Ack is not being expected at moment */ - if(!gIsoDep.isWait4WTX) { - gIsoDep.state = ISODEP_ST_PICC_TX; - return ERR_NONE; - } else { - /* If RTOX Ack is expected, signal a pending Tx to be transmitted right after */ - gIsoDep.isTxPending = true; - } - } - - /* Digital 1.1 15.2.5.1 The first block SHALL be sent by the Reader/Writer */ - gIsoDep.state = ISODEP_ST_PICC_RX; - return ERR_NONE; - } - - gIsoDep.state = ISODEP_ST_PCD_TX; - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepGetTransceiveStatus(void) { - if(gIsoDep.role == ISODEP_ROLE_PICC) { -#if RFAL_FEATURE_ISO_DEP_LISTEN - return isoDepDataExchangePICC(); -#else - return ERR_NOTSUPP; -#endif /* RFAL_FEATURE_ISO_DEP_LISTEN */ - } else { -#if RFAL_FEATURE_ISO_DEP_POLL - return isoDepDataExchangePCD(gIsoDep.rxLen, gIsoDep.rxChaining); -#else - return ERR_NOTSUPP; -#endif /* RFAL_FEATURE_ISO_DEP_POLL */ - } -} - -#if RFAL_FEATURE_ISO_DEP_LISTEN - -/*******************************************************************************/ -static ReturnCode isoDepDataExchangePICC(void) { - uint8_t rxPCB; - ReturnCode ret; - - switch(gIsoDep.state) { - /*******************************************************************************/ - case ISODEP_ST_IDLE: - return ERR_NONE; - - /*******************************************************************************/ - case ISODEP_ST_PICC_TX: - - ret = isoDepTx( - isoDep_PCBIBlock(gIsoDep.blockNumber), - gIsoDep.txBuf, - &gIsoDep.txBuf[gIsoDep.txBufInfPos], - gIsoDep.txBufLen, - RFAL_FWT_NONE); - - /* Clear pending Tx flag */ - gIsoDep.isTxPending = false; - - switch(ret) { - case ERR_NONE: - gIsoDep.state = ISODEP_ST_PICC_RX; - return ERR_BUSY; - - default: - /* MISRA 16.4: no empty default statement (a comment being enough) */ - break; - } - return ret; - - /*******************************************************************************/ - case ISODEP_ST_PICC_RX: - - ret = rfalGetTransceiveStatus(); - switch(ret) { - /*******************************************************************************/ - /* Data rcvd with error or timeout -> mute */ - case ERR_TIMEOUT: - case ERR_CRC: - case ERR_PAR: - case ERR_FRAMING: - - /* Digital 1.1 - 15.2.6.2 The CE SHALL NOT attempt error recovery and remains in Rx mode upon Transmission or a Protocol Error */ - isoDepReEnableRx((uint8_t*)gIsoDep.rxBuf, sizeof(rfalIsoDepBufFormat), gIsoDep.rxLen); - - return ERR_BUSY; - - /*******************************************************************************/ - case ERR_LINK_LOSS: - return ret; /* Debug purposes */ - - case ERR_BUSY: - return ret; /* Debug purposes */ - - /*******************************************************************************/ - case ERR_NONE: - *gIsoDep.rxLen = rfalConvBitsToBytes(*gIsoDep.rxLen); - break; - - /*******************************************************************************/ - default: - return ret; - } - break; - - /*******************************************************************************/ - case ISODEP_ST_PICC_SWTX: - - if(!isoDepTimerisExpired(gIsoDep.WTXTimer)) /* Do nothing until WTX timer has expired */ - { - return ERR_BUSY; - } - - /* Set waiting for WTX Ack Flag */ - gIsoDep.isWait4WTX = true; - - /* Digital 1.1 15.2.2.9 - Calculate the WTXM such that FWTtemp <= FWTmax */ - gIsoDep.lastWTXM = (uint8_t)isoDep_WTXMListenerMax(gIsoDep.fwt); - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_S_WTX, gIsoDep.lastWTXM)); - - gIsoDep.state = ISODEP_ST_PICC_RX; /* Go back to Rx to process WTX ack */ - return ERR_BUSY; - - /*******************************************************************************/ - case ISODEP_ST_PICC_SDSL: - - if(rfalIsTransceiveInRx()) /* Wait until DSL response has been sent */ - { - rfalIsoDepInitialize(); /* Session finished reInit vars */ - return ERR_SLEEP_REQ; /* Notify Deselect request */ - } - return ERR_BUSY; - - /*******************************************************************************/ - default: - return ERR_INTERNAL; - } - - /* ISO 14443-4 7.5.6.2 CE SHALL NOT attempt error recovery -> clear counters */ - isoDepClearCounters(); - - /*******************************************************************************/ - /* No error, process incoming msg */ - /*******************************************************************************/ - - /* Grab rcvd PCB */ - rxPCB = gIsoDep.rxBuf[ISODEP_PCB_POS]; - - /*******************************************************************************/ - /* When DID=0 PCD may or may not use DID, therefore check whether current PCD request - * has DID present to be reflected on max INF length #454 */ - - /* ReCalculate Header Length */ - gIsoDep.hdrLen = RFAL_ISODEP_PCB_LEN; - gIsoDep.hdrLen += (uint8_t)((isoDep_PCBhasDID(rxPCB)) ? RFAL_ISODEP_DID_LEN : 0U); - gIsoDep.hdrLen += (uint8_t)((isoDep_PCBhasNAD(rxPCB)) ? RFAL_ISODEP_NAD_LEN : 0U); - - /* Store whether last PCD block had DID. for PICC special handling of DID = 0 */ - if(gIsoDep.did == RFAL_ISODEP_DID_00) { - gIsoDep.lastDID00 = ((isoDep_PCBhasDID(rxPCB)) ? true : false); - } - - /*******************************************************************************/ - /* Check rcvd msg length, cannot be less then the expected header OR * - * if the rcvd msg exceeds our announced frame size (FSD) */ - if(((*gIsoDep.rxLen) < gIsoDep.hdrLen) || - ((*gIsoDep.rxLen) > (gIsoDep.ourFsx - ISODEP_CRC_LEN))) { - isoDepReEnableRx( - (uint8_t*)gIsoDep.actvParam.rxBuf, - sizeof(rfalIsoDepBufFormat), - gIsoDep.actvParam.rxLen); - return ERR_BUSY; /* ERR_PROTO Ignore this protocol request */ - } - - /* If we are expecting DID, check if PCB signals its presence and if device ID match OR - * If our DID=0 and DID is sent but with an incorrect value */ - if(((gIsoDep.did != RFAL_ISODEP_DID_00) && - (!isoDep_PCBhasDID(rxPCB) || (gIsoDep.did != gIsoDep.rxBuf[ISODEP_DID_POS]))) || - ((gIsoDep.did == RFAL_ISODEP_DID_00) && isoDep_PCBhasDID(rxPCB) && - (RFAL_ISODEP_DID_00 != gIsoDep.rxBuf[ISODEP_DID_POS]))) { - isoDepReEnableRx( - (uint8_t*)gIsoDep.actvParam.rxBuf, - sizeof(rfalIsoDepBufFormat), - gIsoDep.actvParam.rxLen); - return ERR_BUSY; /* Ignore a wrong DID request */ - } - - /* If we aren't expecting NAD and it's received */ - if((gIsoDep.nad == RFAL_ISODEP_NO_NAD) && isoDep_PCBhasNAD(rxPCB)) { - isoDepReEnableRx( - (uint8_t*)gIsoDep.actvParam.rxBuf, - sizeof(rfalIsoDepBufFormat), - gIsoDep.actvParam.rxLen); - return ERR_BUSY; /* Ignore a unexpected NAD request */ - } - - /*******************************************************************************/ - /* Process S-Block */ - /*******************************************************************************/ - if(isoDep_PCBisSBlock(rxPCB)) { - /* Check if is a Wait Time eXtension */ - if(isoDep_PCBisSWTX(rxPCB)) { - /* Check if we're expecting a S-WTX */ - if(isoDep_PCBisWTX(gIsoDep.lastPCB)) { - /* Digital 1.1 15.2.2.11 S(WTX) Ack with different WTXM -> Protocol Error * - * Power level indication also should be set to 0 */ - if((gIsoDep.rxBuf[gIsoDep.hdrLen] == gIsoDep.lastWTXM) && - ((*gIsoDep.rxLen - gIsoDep.hdrLen) == ISODEP_SWTX_INF_LEN)) { - /* Clear waiting for RTOX Ack Flag */ - gIsoDep.isWait4WTX = false; - - /* Check if a Tx is already pending */ - if(gIsoDep.isTxPending) { - /* Has a pending Tx, go immediately to TX */ - gIsoDep.state = ISODEP_ST_PICC_TX; - return ERR_BUSY; - } - - /* Set WTX timer */ - isoDepTimerStart( - gIsoDep.WTXTimer, - isoDep_WTXAdjust((gIsoDep.lastWTXM * rfalConv1fcToMs(gIsoDep.fwt)))); - - gIsoDep.state = ISODEP_ST_PICC_SWTX; - return ERR_BUSY; - } - } - /* Unexpected/Incorrect S-WTX, fall into reRenable */ - } - - /* Check if is a Deselect request */ - if(isoDep_PCBisSDeselect(rxPCB) && - ((*gIsoDep.rxLen - gIsoDep.hdrLen) == ISODEP_SDSL_INF_LEN)) { - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_S_DSL, RFAL_ISODEP_NO_PARAM)); - - /* S-DSL transmission ongoing, wait until complete */ - gIsoDep.state = ISODEP_ST_PICC_SDSL; - return ERR_BUSY; - } - - /* Unexpected S-Block, fall into reRenable */ - } - - /*******************************************************************************/ - /* Process R-Block */ - /*******************************************************************************/ - else if(isoDep_PCBisRBlock(rxPCB) && ((*gIsoDep.rxLen - gIsoDep.hdrLen) == ISODEP_RBLOCK_INF_LEN)) { - if(isoDep_PCBisRACK(rxPCB)) /* Check if is a R-ACK */ - { - if(isoDep_GetBN(rxPCB) == gIsoDep.blockNumber) /* Check block number */ - { - /* Rule 11 - R(ACK) with current bn -> re-transmit */ - if(!isoDep_PCBisIBlock(gIsoDep.lastPCB)) { - isoDepReSendControlMsg(); - } else { - gIsoDep.state = ISODEP_ST_PICC_TX; - } - - return ERR_BUSY; - } else { - if(!gIsoDep.isTxChaining) { - /* Rule 13 violation R(ACK) without performing chaining */ - isoDepReEnableRx( - (uint8_t*)gIsoDep.rxBuf, sizeof(rfalIsoDepBufFormat), gIsoDep.rxLen); - return ERR_BUSY; - } - - /* Rule E - R(ACK) with not current bn -> toggle bn */ - isoDep_ToggleBN(gIsoDep.blockNumber); - - /* This block has been transmitted and acknowledged, perform WTX until next data is provided */ - - /* Rule 9 - PICC is allowed to send an S(WTX) instead of an I-block or an R(ACK) */ - isoDepTimerStart(gIsoDep.WTXTimer, isoDep_WTXAdjust(rfalConv1fcToMs(gIsoDep.fwt))); - gIsoDep.state = ISODEP_ST_PICC_SWTX; - - /* Rule 13 - R(ACK) with not current bn -> continue chaining */ - return ERR_NONE; /* This block has been transmitted */ - } - } else if(isoDep_PCBisRNAK(rxPCB)) /* Check if is a R-NACK */ - { - if(isoDep_GetBN(rxPCB) == gIsoDep.blockNumber) /* Check block number */ - { - /* Rule 11 - R(NAK) with current bn -> re-transmit last x-Block */ - if(!isoDep_PCBisIBlock(gIsoDep.lastPCB)) { - isoDepReSendControlMsg(); - } else { - gIsoDep.state = ISODEP_ST_PICC_TX; - } - - return ERR_BUSY; - } else { - /* Rule 12 - R(NAK) with not current bn -> R(ACK) */ - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_R_ACK, RFAL_ISODEP_NO_PARAM)); - - return ERR_BUSY; - } - } else { - /* MISRA 15.7 - Empty else */ - } - - /* Unexpected R-Block, fall into reRenable */ - } - - /*******************************************************************************/ - /* Process I-Block */ - /*******************************************************************************/ - else if(isoDep_PCBisIBlock(rxPCB)) { - /* Rule D - When an I-block is received, the PICC shall toggle its block number before sending a block */ - isoDep_ToggleBN(gIsoDep.blockNumber); - - /*******************************************************************************/ - /* Check if the block number is the one expected */ - /* Check if PCD sent an I-Block instead ACK/NACK when we are chaining */ - if((isoDep_GetBN(rxPCB) != gIsoDep.blockNumber) || (gIsoDep.isTxChaining)) { - /* Remain in the same Block Number */ - isoDep_ToggleBN(gIsoDep.blockNumber); - - /* ISO 14443-4 7.5.6.2 & Digital 1.1 - 15.2.6.2 The CE SHALL NOT attempt error recovery and remains in Rx mode upon Transmission or a Protocol Error */ - isoDepReEnableRx((uint8_t*)gIsoDep.rxBuf, sizeof(rfalIsoDepBufFormat), gIsoDep.rxLen); - return ERR_BUSY; - } - - /*******************************************************************************/ - /* is PCD performing chaining ? */ - if(isoDep_PCBisChaining(rxPCB)) { - gIsoDep.isRxChaining = true; - *gIsoDep.rxChaining = true; /* Output Parameter*/ - - EXIT_ON_ERR(ret, isoDepHandleControlMsg(ISODEP_R_ACK, RFAL_ISODEP_NO_PARAM)); - - /* Received I-Block with chaining, send current data to DH */ - - /* remove ISO DEP header, check is necessary to move the INF data on the buffer */ - *gIsoDep.rxLen -= gIsoDep.hdrLen; - if((gIsoDep.hdrLen != gIsoDep.rxBufInfPos) && (*gIsoDep.rxLen > 0U)) { - ST_MEMMOVE( - &gIsoDep.rxBuf[gIsoDep.rxBufInfPos], - &gIsoDep.rxBuf[gIsoDep.hdrLen], - *gIsoDep.rxLen); - } - return ERR_AGAIN; /* Send Again signalling to run again, but some chaining data has arrived*/ - } - - /*******************************************************************************/ - /* PCD is not performing chaining */ - gIsoDep.isRxChaining = false; /* clear PCD chaining flag */ - *gIsoDep.rxChaining = false; /* Output Parameter */ - - /* remove ISO DEP header, check is necessary to move the INF data on the buffer */ - *gIsoDep.rxLen -= gIsoDep.hdrLen; - if((gIsoDep.hdrLen != gIsoDep.rxBufInfPos) && (*gIsoDep.rxLen > 0U)) { - ST_MEMMOVE( - &gIsoDep.rxBuf[gIsoDep.rxBufInfPos], - &gIsoDep.rxBuf[gIsoDep.hdrLen], - *gIsoDep.rxLen); - } - - /*******************************************************************************/ - /* Reception done, send data back and start WTX timer */ - isoDepTimerStart(gIsoDep.WTXTimer, isoDep_WTXAdjust(rfalConv1fcToMs(gIsoDep.fwt))); - - gIsoDep.state = ISODEP_ST_PICC_SWTX; - return ERR_NONE; - } else { - /* MISRA 15.7 - Empty else */ - } - - /* Unexpected/Unknown Block */ - /* ISO 14443-4 7.5.6.2 & Digital 1.1 - 15.2.6.2 The CE SHALL NOT attempt error recovery and remains in Rx mode upon Transmission or a Protocol Error */ - isoDepReEnableRx((uint8_t*)gIsoDep.rxBuf, sizeof(rfalIsoDepBufFormat), gIsoDep.rxLen); - - return ERR_BUSY; -} -#endif /* RFAL_FEATURE_ISO_DEP_LISTEN */ - -#if RFAL_FEATURE_ISO_DEP_POLL - -#if RFAL_FEATURE_NFCA - -/*******************************************************************************/ -static ReturnCode - rfalIsoDepStartRATS(rfalIsoDepFSxI FSDI, uint8_t DID, rfalIsoDepAts* ats, uint8_t* atsLen) { - rfalTransceiveContext ctx; - - if(ats == NULL) { - return ERR_PARAM; - } - - gIsoDep.rxBuf = (uint8_t*)ats; - gIsoDep.rxLen8 = atsLen; - gIsoDep.did = DID; - - /*******************************************************************************/ - /* Compose RATS */ - gIsoDep.actv.ratsReq.CMD = RFAL_ISODEP_CMD_RATS; - gIsoDep.actv.ratsReq.PARAM = - (((uint8_t)FSDI << RFAL_ISODEP_RATS_PARAM_FSDI_SHIFT) & RFAL_ISODEP_RATS_PARAM_FSDI_MASK) | - (DID & RFAL_ISODEP_RATS_PARAM_DID_MASK); - - rfalCreateByteFlagsTxRxContext( - ctx, - (uint8_t*)&gIsoDep.actv.ratsReq, - sizeof(rfalIsoDepRats), - (uint8_t*)ats, - sizeof(rfalIsoDepAts), - &gIsoDep.rxBufLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ISODEP_T4T_FWT_ACTIVATION); - return rfalStartTransceive(&ctx); -} - -/*******************************************************************************/ -static ReturnCode rfalIsoDepGetRATSStatus(void) { - ReturnCode ret; - - ret = rfalGetTransceiveStatus(); - if(ret == ERR_NONE) { - gIsoDep.rxBufLen = rfalConvBitsToBytes(gIsoDep.rxBufLen); - - /* Check for valid ATS length Digital 1.1 13.6.2.1 & 13.6.2.3 */ - if((gIsoDep.rxBufLen < RFAL_ISODEP_ATS_MIN_LEN) || - (gIsoDep.rxBufLen > RFAL_ISODEP_ATS_MAX_LEN) || - (gIsoDep.rxBuf[RFAL_ISODEP_ATS_TL_POS] != gIsoDep.rxBufLen)) { - return ERR_PROTO; - } - - /* Assign our FSx, in case the a Deselect is send without Transceive */ - gIsoDep.ourFsx = rfalIsoDepFSxI2FSx( - (uint8_t)(gIsoDep.actv.ratsReq.PARAM >> RFAL_ISODEP_RATS_PARAM_FSDI_SHIFT)); - - /* Check and assign if ATS length was requested (length also available on TL) */ - if(gIsoDep.rxLen8 != NULL) { - *gIsoDep.rxLen8 = (uint8_t)gIsoDep.rxBufLen; - } - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepRATS(rfalIsoDepFSxI FSDI, uint8_t DID, rfalIsoDepAts* ats, uint8_t* atsLen) { - ReturnCode ret; - - EXIT_ON_ERR(ret, rfalIsoDepStartRATS(FSDI, DID, ats, atsLen)); - rfalIsoDepRunBlocking(ret, rfalIsoDepGetRATSStatus()); - - return ret; -} - -/*******************************************************************************/ -static ReturnCode - rfalIsoDepStartPPS(uint8_t DID, rfalBitRate DSI, rfalBitRate DRI, rfalIsoDepPpsRes* ppsRes) { - rfalTransceiveContext ctx; - - if((ppsRes == NULL) || (DSI > RFAL_BR_848) || (DRI > RFAL_BR_848) || - (DID > RFAL_ISODEP_DID_MAX)) { - return ERR_PARAM; - } - - gIsoDep.rxBuf = (uint8_t*)ppsRes; - - /*******************************************************************************/ - /* Compose PPS Request */ - gIsoDep.actv.ppsReq.PPSS = (RFAL_ISODEP_PPS_SB | (DID & RFAL_ISODEP_PPS_SB_DID_MASK)); - gIsoDep.actv.ppsReq.PPS0 = RFAL_ISODEP_PPS_PPS0_PPS1_PRESENT; - gIsoDep.actv.ppsReq.PPS1 = - (RFAL_ISODEP_PPS_PPS1 | - ((((uint8_t)DSI << RFAL_ISODEP_PPS_PPS1_DSI_SHIFT) | (uint8_t)DRI) & - RFAL_ISODEP_PPS_PPS1_DXI_MASK)); - - rfalCreateByteFlagsTxRxContext( - ctx, - (uint8_t*)&gIsoDep.actv.ppsReq, - sizeof(rfalIsoDepPpsReq), - (uint8_t*)ppsRes, - sizeof(rfalIsoDepPpsRes), - &gIsoDep.rxBufLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ISODEP_T4T_FWT_ACTIVATION); - return rfalStartTransceive(&ctx); -} - -/*******************************************************************************/ -static ReturnCode rfalIsoDepGetPPSSTatus(void) { - ReturnCode ret; - - ret = rfalGetTransceiveStatus(); - if(ret == ERR_NONE) { - gIsoDep.rxBufLen = rfalConvBitsToBytes(gIsoDep.rxBufLen); - - /* Check for valid PPS Response */ - if((gIsoDep.rxBufLen != RFAL_ISODEP_PPS_RES_LEN) || - (*gIsoDep.rxBuf != gIsoDep.actv.ppsReq.PPSS)) { - return ERR_PROTO; - } - } - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepPPS(uint8_t DID, rfalBitRate DSI, rfalBitRate DRI, rfalIsoDepPpsRes* ppsRes) { - ReturnCode ret; - - EXIT_ON_ERR(ret, rfalIsoDepStartPPS(DID, DSI, DRI, ppsRes)); - rfalIsoDepRunBlocking(ret, rfalIsoDepGetPPSSTatus()); - - return ret; -} - -#endif /* RFAL_FEATURE_NFCA */ - -#if RFAL_FEATURE_NFCB - -static ReturnCode rfalIsoDepStartATTRIB( - const uint8_t* nfcid0, - uint8_t PARAM1, - rfalBitRate DSI, - rfalBitRate DRI, - rfalIsoDepFSxI FSDI, - uint8_t PARAM3, - uint8_t DID, - const uint8_t* HLInfo, - uint8_t HLInfoLen, - uint32_t fwt, - rfalIsoDepAttribRes* attribRes, - uint8_t* attribResLen) { - rfalTransceiveContext ctx; - - if((attribRes == NULL) || (attribResLen == NULL) || (DSI > RFAL_BR_848) || - (DRI > RFAL_BR_848) || (DID > RFAL_ISODEP_DID_MAX)) { - return ERR_NONE; - } - - gIsoDep.rxBuf = (uint8_t*)attribRes; - gIsoDep.rxLen8 = attribResLen; - gIsoDep.did = DID; - - /*******************************************************************************/ - /* Compose ATTRIB command */ - gIsoDep.actv.attribReq.cmd = RFAL_ISODEP_CMD_ATTRIB; - gIsoDep.actv.attribReq.Param.PARAM1 = PARAM1; - gIsoDep.actv.attribReq.Param.PARAM2 = - (((((uint8_t)DSI << RFAL_ISODEP_ATTRIB_PARAM2_DSI_SHIFT) | - ((uint8_t)DRI << RFAL_ISODEP_ATTRIB_PARAM2_DRI_SHIFT)) & - RFAL_ISODEP_ATTRIB_PARAM2_DXI_MASK) | - ((uint8_t)FSDI & RFAL_ISODEP_ATTRIB_PARAM2_FSDI_MASK)); - gIsoDep.actv.attribReq.Param.PARAM3 = PARAM3; - gIsoDep.actv.attribReq.Param.PARAM4 = (DID & RFAL_ISODEP_ATTRIB_PARAM4_DID_MASK); - ST_MEMCPY(gIsoDep.actv.attribReq.nfcid0, nfcid0, RFAL_NFCB_NFCID0_LEN); - - /* Append the Higher layer Info if provided */ - if((HLInfo != NULL) && (HLInfoLen > 0U)) { - ST_MEMCPY( - gIsoDep.actv.attribReq.HLInfo, HLInfo, MIN(HLInfoLen, RFAL_ISODEP_ATTRIB_HLINFO_LEN)); - } - - rfalCreateByteFlagsTxRxContext( - ctx, - (uint8_t*)&gIsoDep.actv.attribReq, - (uint16_t)(RFAL_ISODEP_ATTRIB_HDR_LEN + MIN((uint16_t)HLInfoLen, RFAL_ISODEP_ATTRIB_HLINFO_LEN)), - (uint8_t*)gIsoDep.rxBuf, - sizeof(rfalIsoDepAttribRes), - &gIsoDep.rxBufLen, - RFAL_TXRX_FLAGS_DEFAULT, - fwt); - return rfalStartTransceive(&ctx); -} - -/*******************************************************************************/ -static ReturnCode rfalIsoDepGetATTRIBStatus(void) { - ReturnCode ret; - - ret = rfalGetTransceiveStatus(); - if(ret == ERR_NONE) { - gIsoDep.rxBufLen = rfalConvBitsToBytes(gIsoDep.rxBufLen); - - /* Check a for valid ATTRIB Response Digital 1.1 15.6.2.1 */ - if((gIsoDep.rxBufLen < RFAL_ISODEP_ATTRIB_RES_HDR_LEN) || - ((gIsoDep.rxBuf[RFAL_ISODEP_ATTRIB_RES_MBLIDID_POS] & - RFAL_ISODEP_ATTRIB_RES_DID_MASK) != gIsoDep.did)) { - return ERR_PROTO; - } - - if(gIsoDep.rxLen8 != NULL) { - *gIsoDep.rxLen8 = (uint8_t)gIsoDep.rxBufLen; - } - - gIsoDep.ourFsx = rfalIsoDepFSxI2FSx( - (uint8_t)(gIsoDep.actv.attribReq.Param.PARAM2 & RFAL_ISODEP_ATTRIB_PARAM2_FSDI_MASK)); - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepATTRIB( - const uint8_t* nfcid0, - uint8_t PARAM1, - rfalBitRate DSI, - rfalBitRate DRI, - rfalIsoDepFSxI FSDI, - uint8_t PARAM3, - uint8_t DID, - const uint8_t* HLInfo, - uint8_t HLInfoLen, - uint32_t fwt, - rfalIsoDepAttribRes* attribRes, - uint8_t* attribResLen) { - ReturnCode ret; - - EXIT_ON_ERR( - ret, - rfalIsoDepStartATTRIB( - nfcid0, - PARAM1, - DSI, - DRI, - FSDI, - PARAM3, - DID, - HLInfo, - HLInfoLen, - fwt, - attribRes, - attribResLen)); - rfalIsoDepRunBlocking(ret, rfalIsoDepGetATTRIBStatus()); - - return ret; -} - -#endif /* RFAL_FEATURE_NFCB */ - -#if RFAL_FEATURE_NFCA - -/*******************************************************************************/ -ReturnCode rfalIsoDepPollAHandleActivation( - rfalIsoDepFSxI FSDI, - uint8_t DID, - rfalBitRate maxBR, - rfalIsoDepDevice* isoDepDev) { - ReturnCode ret; - - EXIT_ON_ERR(ret, rfalIsoDepPollAStartActivation(FSDI, DID, maxBR, isoDepDev)); - rfalIsoDepRunBlocking(ret, rfalIsoDepPollAGetActivationStatus()); - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepPollAStartActivation( - rfalIsoDepFSxI FSDI, - uint8_t DID, - rfalBitRate maxBR, - rfalIsoDepDevice* isoDepDev) { - ReturnCode ret; - - if(isoDepDev == NULL) { - return ERR_PARAM; - } - - /* Enable EMD handling according Digital 1.1 4.1.1.1 ; EMVCo 2.6 4.9.2 */ - rfalSetErrorHandling(RFAL_ERRORHANDLING_EMVCO); - - /* Start RATS Transceive */ - EXIT_ON_ERR( - ret, - rfalIsoDepStartRATS( - FSDI, - DID, - &isoDepDev->activation.A.Listener.ATS, - &isoDepDev->activation.A.Listener.ATSLen)); - - isoDepDev->info.DSI = maxBR; - gIsoDep.actvDev = isoDepDev; - gIsoDep.cntRRetrys = gIsoDep.maxRetriesRATS; - gIsoDep.state = ISODEP_ST_PCD_ACT_RATS; - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepPollAGetActivationStatus(void) { - ReturnCode ret; - uint8_t msgIt; - rfalBitRate maxBR; - - switch(gIsoDep.state) { - /*******************************************************************************/ - case ISODEP_ST_PCD_ACT_RATS: - - ret = rfalIsoDepGetRATSStatus(); - if(ret != ERR_BUSY) { - if(ret != ERR_NONE) { - /* EMVCo 2.6 9.6.1.1 & 9.6.1.2 If a timeout error is detected retransmit, on transmission error abort */ - if((gIsoDep.compMode == RFAL_COMPLIANCE_MODE_EMV) && (ret != ERR_TIMEOUT)) { - break; - } - - if(gIsoDep.cntRRetrys != 0U) { - /* Ensure FDT before retransmission (reuse RFAL GT timer) */ - rfalSetGT(rfalGetFDTPoll()); - rfalFieldOnAndStartGT(); - - /* Send RATS retransmission */ /* PRQA S 4342 1 # MISRA 10.5 - Layout of enum rfalIsoDepFSxI is guaranteed within 4bit range */ - EXIT_ON_ERR( - ret, - rfalIsoDepStartRATS( - (rfalIsoDepFSxI)(uint8_t)(gIsoDep.actv.ratsReq.PARAM >> RFAL_ISODEP_RATS_PARAM_FSDI_SHIFT), - gIsoDep.did, - &gIsoDep.actvDev->activation.A.Listener.ATS, - &gIsoDep.actvDev->activation.A.Listener.ATSLen)); - gIsoDep.cntRRetrys--; - ret = ERR_BUSY; - } - /* Switch between NFC Forum and ISO14443-4 behaviour #595 - * ISO14443-4 5.6.1 If RATS fails, a Deactivation sequence should be performed as defined on clause 8 - * Activity 1.1 9.6 Device Deactivation Activity is to be only performed when there's an active device */ - else if(gIsoDep.compMode == RFAL_COMPLIANCE_MODE_ISO) { - rfalIsoDepDeselect(); - } else { - /* MISRA 15.7 - Empty else */ - } - } else /* ATS received */ - { - maxBR = gIsoDep.actvDev->info.DSI; /* Retrieve requested max bitrate */ - - /*******************************************************************************/ - /* Process ATS Response */ - gIsoDep.actvDev->info.FWI = - RFAL_ISODEP_FWI_DEFAULT; /* Default value EMVCo 2.6 5.7.2.6 */ - gIsoDep.actvDev->info.SFGI = 0U; - gIsoDep.actvDev->info.MBL = 0U; - gIsoDep.actvDev->info.DSI = RFAL_BR_106; - gIsoDep.actvDev->info.DRI = RFAL_BR_106; - gIsoDep.actvDev->info.FSxI = (uint8_t) - RFAL_ISODEP_FSXI_32; /* FSC default value is 32 bytes ISO14443-A 5.2.3 */ - - /*******************************************************************************/ - /* Check for ATS optional fields */ - if(gIsoDep.actvDev->activation.A.Listener.ATS.TL > RFAL_ISODEP_ATS_MIN_LEN) { - msgIt = RFAL_ISODEP_ATS_MIN_LEN; - - /* Format byte T0 is optional, if present assign FSDI */ - gIsoDep.actvDev->info.FSxI = - (gIsoDep.actvDev->activation.A.Listener.ATS.T0 & - RFAL_ISODEP_ATS_T0_FSCI_MASK); - - /* T0 has already been processed, always the same position */ - msgIt++; - - /* Check if TA is present */ - if((gIsoDep.actvDev->activation.A.Listener.ATS.T0 & - RFAL_ISODEP_ATS_T0_TA_PRESENCE_MASK) != 0U) { - rfalIsoDepCalcBitRate( - maxBR, - ((uint8_t*)&gIsoDep.actvDev->activation.A.Listener.ATS)[msgIt++], - &gIsoDep.actvDev->info.DSI, - &gIsoDep.actvDev->info.DRI); - } - - /* Check if TB is present */ - if((gIsoDep.actvDev->activation.A.Listener.ATS.T0 & - RFAL_ISODEP_ATS_T0_TB_PRESENCE_MASK) != 0U) { - gIsoDep.actvDev->info.SFGI = - ((uint8_t*)&gIsoDep.actvDev->activation.A.Listener.ATS)[msgIt++]; - gIsoDep.actvDev->info.FWI = - (uint8_t)((gIsoDep.actvDev->info.SFGI >> RFAL_ISODEP_ATS_TB_FWI_SHIFT) & RFAL_ISODEP_ATS_FWI_MASK); - gIsoDep.actvDev->info.SFGI &= RFAL_ISODEP_ATS_TB_SFGI_MASK; - } - - /* Check if TC is present */ - if((gIsoDep.actvDev->activation.A.Listener.ATS.T0 & - RFAL_ISODEP_ATS_T0_TC_PRESENCE_MASK) != 0U) { - /* Check for Protocol features support */ - /* Advanced protocol features defined on Digital 1.0 Table 69, removed after */ - gIsoDep.actvDev->info.supAdFt = - (((((uint8_t*)&gIsoDep.actvDev->activation.A.Listener.ATS)[msgIt] & - RFAL_ISODEP_ATS_TC_ADV_FEAT) != 0U) ? - true : - false); - gIsoDep.actvDev->info.supDID = - (((((uint8_t*)&gIsoDep.actvDev->activation.A.Listener.ATS)[msgIt] & - RFAL_ISODEP_ATS_TC_DID) != 0U) ? - true : - false); - gIsoDep.actvDev->info.supNAD = - (((((uint8_t*)&gIsoDep.actvDev->activation.A.Listener.ATS)[msgIt++] & - RFAL_ISODEP_ATS_TC_NAD) != 0U) ? - true : - false); - } - } - - gIsoDep.actvDev->info.FSx = rfalIsoDepFSxI2FSx(gIsoDep.actvDev->info.FSxI); - gIsoDep.fsx = gIsoDep.actvDev->info.FSx; - - gIsoDep.actvDev->info.SFGT = - rfalIsoDepSFGI2SFGT((uint8_t)gIsoDep.actvDev->info.SFGI); - - /* Ensure SFGT before following frame (reuse RFAL GT timer) */ - rfalSetGT(rfalConvMsTo1fc(gIsoDep.actvDev->info.SFGT)); - rfalFieldOnAndStartGT(); - - gIsoDep.actvDev->info.FWT = rfalIsoDepFWI2FWT(gIsoDep.actvDev->info.FWI); - gIsoDep.actvDev->info.dFWT = RFAL_ISODEP_DFWT_20; - - gIsoDep.actvDev->info.DID = - ((gIsoDep.actvDev->info.supDID) ? gIsoDep.did : RFAL_ISODEP_NO_DID); - gIsoDep.actvDev->info.NAD = RFAL_ISODEP_NO_NAD; - - /*******************************************************************************/ - /* If higher bit rates are supported by both devices, send PPS */ - if((gIsoDep.actvDev->info.DSI != RFAL_BR_106) || - (gIsoDep.actvDev->info.DRI != RFAL_BR_106)) { - /* Send PPS */ /* PRQA S 0310 1 # MISRA 11.3 - Intentional safe cast to avoiding buffer duplication */ - EXIT_ON_ERR( - ret, - rfalIsoDepStartPPS( - gIsoDep.actvDev->info.DID, - gIsoDep.actvDev->info.DSI, - gIsoDep.actvDev->info.DRI, - (rfalIsoDepPpsRes*)&gIsoDep.ctrlBuf)); - - gIsoDep.state = ISODEP_ST_PCD_ACT_PPS; - return ERR_BUSY; - } - - return ERR_NONE; - } - } - break; - - /*******************************************************************************/ - case ISODEP_ST_PCD_ACT_PPS: - ret = rfalIsoDepGetPPSSTatus(); - if(ret != ERR_BUSY) { - /* Check whether PPS has been acknowledge */ - if(ret == ERR_NONE) { - /* DSI code the divisor from PICC to PCD */ - /* DRI code the divisor from PCD to PICC */ - rfalSetBitRate(gIsoDep.actvDev->info.DRI, gIsoDep.actvDev->info.DSI); - } else { - /* If PPS has faled keep activation bit rate */ - gIsoDep.actvDev->info.DSI = RFAL_BR_106; - gIsoDep.actvDev->info.DRI = RFAL_BR_106; - } - } - break; - - /*******************************************************************************/ - default: - ret = ERR_WRONG_STATE; - break; - } - - return ret; -} -#endif /* RFAL_FEATURE_NFCA */ - -#if RFAL_FEATURE_NFCB - -/*******************************************************************************/ -ReturnCode rfalIsoDepPollBHandleActivation( - rfalIsoDepFSxI FSDI, - uint8_t DID, - rfalBitRate maxBR, - uint8_t PARAM1, - const rfalNfcbListenDevice* nfcbDev, - const uint8_t* HLInfo, - uint8_t HLInfoLen, - rfalIsoDepDevice* isoDepDev) { - ReturnCode ret; - - EXIT_ON_ERR( - ret, - rfalIsoDepPollBStartActivation( - FSDI, DID, maxBR, PARAM1, nfcbDev, HLInfo, HLInfoLen, isoDepDev)); - rfalIsoDepRunBlocking(ret, rfalIsoDepPollBGetActivationStatus()); - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepPollBStartActivation( - rfalIsoDepFSxI FSDI, - uint8_t DID, - rfalBitRate maxBR, - uint8_t PARAM1, - const rfalNfcbListenDevice* nfcbDev, - const uint8_t* HLInfo, - uint8_t HLInfoLen, - rfalIsoDepDevice* isoDepDev) { - ReturnCode ret; - - /***************************************************************************/ - /* Initialize ISO-DEP Device with info from SENSB_RES */ - isoDepDev->info.FWI = - ((nfcbDev->sensbRes.protInfo.FwiAdcFo >> RFAL_NFCB_SENSB_RES_FWI_SHIFT) & - RFAL_NFCB_SENSB_RES_FWI_MASK); - isoDepDev->info.FWT = rfalIsoDepFWI2FWT(isoDepDev->info.FWI); - isoDepDev->info.dFWT = RFAL_NFCB_DFWT; - isoDepDev->info.SFGI = - (((uint32_t)nfcbDev->sensbRes.protInfo.SFGI >> RFAL_NFCB_SENSB_RES_SFGI_SHIFT) & - RFAL_NFCB_SENSB_RES_SFGI_MASK); - isoDepDev->info.SFGT = rfalIsoDepSFGI2SFGT((uint8_t)isoDepDev->info.SFGI); - isoDepDev->info.FSxI = - ((nfcbDev->sensbRes.protInfo.FsciProType >> RFAL_NFCB_SENSB_RES_FSCI_SHIFT) & - RFAL_NFCB_SENSB_RES_FSCI_MASK); - isoDepDev->info.FSx = rfalIsoDepFSxI2FSx(isoDepDev->info.FSxI); - isoDepDev->info.DID = DID; - isoDepDev->info.supDID = - (((nfcbDev->sensbRes.protInfo.FwiAdcFo & RFAL_NFCB_SENSB_RES_FO_DID_MASK) != 0U) ? true : - false); - isoDepDev->info.supNAD = - (((nfcbDev->sensbRes.protInfo.FwiAdcFo & RFAL_NFCB_SENSB_RES_FO_NAD_MASK) != 0U) ? true : - false); - - /* Check if DID requested is supported by PICC */ - if((DID != RFAL_ISODEP_NO_DID) && (!isoDepDev->info.supDID)) { - return ERR_PARAM; - } - - /* Enable EMD handling according Digital 2.1 4.1.1.1 ; EMVCo 3.0 4.9.2 */ - rfalSetErrorHandling(RFAL_ERRORHANDLING_EMVCO); - - /***************************************************************************/ - /* Set FDT Poll to be used on upcoming communications */ - if(gIsoDep.compMode == RFAL_COMPLIANCE_MODE_EMV) { - /* Disregard Minimum TR2 returned by PICC, always use FDTb MIN EMVCo 3.0 6.3.2.10 */ - rfalSetFDTPoll(RFAL_FDT_POLL_NFCB_POLLER); - } else { - /* Apply minimum TR2 from SENSB_RES Digital 2.1 7.6.2.23 */ - rfalSetFDTPoll(rfalNfcbTR2ToFDT( - ((nfcbDev->sensbRes.protInfo.FsciProType >> RFAL_NFCB_SENSB_RES_PROTO_TR2_SHIFT) & - RFAL_NFCB_SENSB_RES_PROTO_TR2_MASK))); - } - - /* Calculate max Bit Rate */ - rfalIsoDepCalcBitRate( - maxBR, nfcbDev->sensbRes.protInfo.BRC, &isoDepDev->info.DSI, &isoDepDev->info.DRI); - - /***************************************************************************/ - /* Send ATTRIB Command */ - EXIT_ON_ERR( - ret, - rfalIsoDepStartATTRIB( - (const uint8_t*)&nfcbDev->sensbRes.nfcid0, - (((nfcbDev->sensbRes.protInfo.FwiAdcFo & RFAL_NFCB_SENSB_RES_ADC_ADV_FEATURE_MASK) != - 0U) ? - PARAM1 : - RFAL_ISODEP_ATTRIB_REQ_PARAM1_DEFAULT), - isoDepDev->info.DSI, - isoDepDev->info.DRI, - FSDI, - (gIsoDep.compMode == RFAL_COMPLIANCE_MODE_EMV) ? - RFAL_NFCB_SENSB_RES_PROTO_ISO_MASK : - (nfcbDev->sensbRes.protInfo.FsciProType & - ((RFAL_NFCB_SENSB_RES_PROTO_TR2_MASK << RFAL_NFCB_SENSB_RES_PROTO_TR2_SHIFT) | - RFAL_NFCB_SENSB_RES_PROTO_ISO_MASK)), /* EMVCo 2.6 6.4.1.9 */ - DID, - HLInfo, - HLInfoLen, - (isoDepDev->info.FWT + isoDepDev->info.dFWT), - &isoDepDev->activation.B.Listener.ATTRIB_RES, - &isoDepDev->activation.B.Listener.ATTRIB_RESLen)); - - gIsoDep.actvDev = isoDepDev; - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepPollBGetActivationStatus(void) { - ReturnCode ret; - uint8_t mbli; - - /***************************************************************************/ - /* Process ATTRIB Response */ - ret = rfalIsoDepGetATTRIBStatus(); - if(ret != ERR_BUSY) { - if(ret == ERR_NONE) { - /* Digital 1.1 14.6.2.3 - Check if received DID match */ - if((gIsoDep.actvDev->activation.B.Listener.ATTRIB_RES.mbliDid & - RFAL_ISODEP_ATTRIB_RES_DID_MASK) != gIsoDep.did) { - return ERR_PROTO; - } - - /* Retrieve MBLI and calculate new FDS/MBL (Maximum Buffer Length) */ - mbli = - ((gIsoDep.actvDev->activation.B.Listener.ATTRIB_RES.mbliDid >> - RFAL_ISODEP_ATTRIB_RES_MBLI_SHIFT) & - RFAL_ISODEP_ATTRIB_RES_MBLI_MASK); - if(mbli > 0U) { - /* Digital 1.1 14.6.2 Calculate Maximum Buffer Length MBL = FSC x 2^(MBLI-1) */ - gIsoDep.actvDev->info.MBL = - (gIsoDep.actvDev->info.FSx * ((uint32_t)1U << (mbli - 1U))); - } - - /* DSI code the divisor from PICC to PCD */ - /* DRI code the divisor from PCD to PICC */ - rfalSetBitRate(gIsoDep.actvDev->info.DRI, gIsoDep.actvDev->info.DSI); - - /* REMARK: SoF EoF TR0 and TR1 are not passed on to RF layer */ - - /* Start the SFGT timer (reuse RFAL GT timer) */ - rfalSetGT(rfalConvMsTo1fc(gIsoDep.actvDev->info.SFGT)); - rfalFieldOnAndStartGT(); - } else { - gIsoDep.actvDev->info.DSI = RFAL_BR_106; - gIsoDep.actvDev->info.DRI = RFAL_BR_106; - } - - /*******************************************************************************/ - /* Store already FS info, rfalIsoDepGetMaxInfLen() may be called before setting TxRx params */ - gIsoDep.fsx = gIsoDep.actvDev->info.FSx; - } - - return ret; -} - -#endif /* RFAL_FEATURE_NFCB */ - -/*******************************************************************************/ -ReturnCode rfalIsoDepPollHandleSParameters( - rfalIsoDepDevice* isoDepDev, - rfalBitRate maxTxBR, - rfalBitRate maxRxBR) { - uint8_t it; - uint8_t supPCD2PICC; - uint8_t supPICC2PCD; - uint8_t currenttxBR; - uint8_t currentrxBR; - rfalBitRate txBR; - rfalBitRate rxBR; - uint16_t rcvLen; - ReturnCode ret; - rfalIsoDepControlMsgSParam sParam; - - if((isoDepDev == NULL) || (maxTxBR > RFAL_BR_13560) || (maxRxBR > RFAL_BR_13560)) { - return ERR_PARAM; - } - - it = 0; - supPICC2PCD = 0x00; - supPCD2PICC = 0x00; - txBR = RFAL_BR_106; - rxBR = RFAL_BR_106; - sParam.pcb = ISODEP_PCB_SPARAMETERS; - - /*******************************************************************************/ - /* Send S(PARAMETERS) - Block Info */ - sParam.sParam.tag = RFAL_ISODEP_SPARAM_TAG_BLOCKINFO; - sParam.sParam.value[it++] = RFAL_ISODEP_SPARAM_TAG_BRREQ; - sParam.sParam.value[it++] = RFAL_ISODEP_SPARAM_TAG_BRREQ_LEN; - sParam.sParam.length = it; - - /* Send S(PARAMETERS). Use a fixed FWI of 4 ISO14443-4 2016 7.2 */ - EXIT_ON_ERR( - ret, - rfalTransceiveBlockingTxRx( - (uint8_t*)&sParam, - (RFAL_ISODEP_SPARAM_HDR_LEN + (uint16_t)it), - (uint8_t*)&sParam, - sizeof(rfalIsoDepControlMsgSParam), - &rcvLen, - RFAL_TXRX_FLAGS_DEFAULT, - ISODEP_FWT_DEACTIVATION)); - - it = 0; - - /*******************************************************************************/ - /* Check S(PARAMETERS) response */ - if((sParam.pcb != ISODEP_PCB_SPARAMETERS) || - (sParam.sParam.tag != RFAL_ISODEP_SPARAM_TAG_BLOCKINFO) || - (sParam.sParam.value[it] != RFAL_ISODEP_SPARAM_TAG_BRIND) || - (rcvLen < RFAL_ISODEP_SPARAM_HDR_LEN) || - (rcvLen != ((uint16_t)sParam.sParam.length + RFAL_ISODEP_SPARAM_HDR_LEN))) { - return ERR_PROTO; - } - - /* Retrieve PICC's bit rate PICC capabilities */ - for(it = 0; it < (rcvLen - (uint16_t)RFAL_ISODEP_SPARAM_TAG_LEN); it++) { - if((sParam.sParam.value[it] == RFAL_ISODEP_SPARAM_TAG_SUP_PCD2PICC) && - (sParam.sParam.value[it + (uint16_t)RFAL_ISODEP_SPARAM_TAG_LEN] == - RFAL_ISODEP_SPARAM_TAG_PCD2PICC_LEN)) { - supPCD2PICC = sParam.sParam.value[it + RFAL_ISODEP_SPARAM_TAG_PCD2PICC_LEN]; - } - - if((sParam.sParam.value[it] == RFAL_ISODEP_SPARAM_TAG_SUP_PICC2PCD) && - (sParam.sParam.value[it + (uint16_t)RFAL_ISODEP_SPARAM_TAG_LEN] == - RFAL_ISODEP_SPARAM_TAG_PICC2PCD_LEN)) { - supPICC2PCD = sParam.sParam.value[it + RFAL_ISODEP_SPARAM_TAG_PICC2PCD_LEN]; - } - } - - /*******************************************************************************/ - /* Check if requested bit rates are supported by PICC */ - if((supPICC2PCD == 0x00U) || (supPCD2PICC == 0x00U)) { - return ERR_PROTO; - } - - for(it = 0; it <= (uint8_t)maxTxBR; it++) { - if((supPCD2PICC & (0x01U << it)) != 0U) { - txBR = (rfalBitRate) - it; /* PRQA S 4342 # MISRA 10.5 - Layout of enum rfalBitRate and above clamping of maxTxBR guarantee no invalid enum values to be created */ - } - } - for(it = 0; it <= (uint8_t)maxRxBR; it++) { - if((supPICC2PCD & (0x01U << it)) != 0U) { - rxBR = (rfalBitRate) - it; /* PRQA S 4342 # MISRA 10.5 - Layout of enum rfalBitRate and above clamping of maxTxBR guarantee no invalid enum values to be created */ - } - } - - it = 0; - currenttxBR = (uint8_t)txBR; - currentrxBR = (uint8_t)rxBR; - - /*******************************************************************************/ - /* Send S(PARAMETERS) - Bit rates Activation */ - sParam.sParam.tag = RFAL_ISODEP_SPARAM_TAG_BLOCKINFO; - sParam.sParam.value[it++] = RFAL_ISODEP_SPARAM_TAG_BRACT; - sParam.sParam.value[it++] = - (RFAL_ISODEP_SPARAM_TVL_HDR_LEN + RFAL_ISODEP_SPARAM_TAG_PCD2PICC_LEN + - RFAL_ISODEP_SPARAM_TVL_HDR_LEN + RFAL_ISODEP_SPARAM_TAG_PICC2PCD_LEN); - sParam.sParam.value[it++] = RFAL_ISODEP_SPARAM_TAG_SEL_PCD2PICC; - sParam.sParam.value[it++] = RFAL_ISODEP_SPARAM_TAG_PCD2PICC_LEN; - sParam.sParam.value[it++] = ((uint8_t)0x01U << currenttxBR); - sParam.sParam.value[it++] = 0x00U; - sParam.sParam.value[it++] = RFAL_ISODEP_SPARAM_TAG_SEL_PICC2PCD; - sParam.sParam.value[it++] = RFAL_ISODEP_SPARAM_TAG_PICC2PCD_LEN; - sParam.sParam.value[it++] = ((uint8_t)0x01U << currentrxBR); - sParam.sParam.value[it++] = 0x00U; - sParam.sParam.length = it; - - EXIT_ON_ERR( - ret, - rfalTransceiveBlockingTxRx( - (uint8_t*)&sParam, - (RFAL_ISODEP_SPARAM_HDR_LEN + (uint16_t)it), - (uint8_t*)&sParam, - sizeof(rfalIsoDepControlMsgSParam), - &rcvLen, - RFAL_TXRX_FLAGS_DEFAULT, - (isoDepDev->info.FWT + isoDepDev->info.dFWT))); - - it = 0; - - /*******************************************************************************/ - /* Check S(PARAMETERS) Acknowledge */ - if((sParam.pcb != ISODEP_PCB_SPARAMETERS) || - (sParam.sParam.tag != RFAL_ISODEP_SPARAM_TAG_BLOCKINFO) || - (sParam.sParam.value[it] != RFAL_ISODEP_SPARAM_TAG_BRACK) || - (rcvLen < RFAL_ISODEP_SPARAM_HDR_LEN)) { - return ERR_PROTO; - } - - EXIT_ON_ERR(ret, rfalSetBitRate(txBR, rxBR)); - - isoDepDev->info.DRI = txBR; - isoDepDev->info.DSI = rxBR; - - return ERR_NONE; -} - -/*******************************************************************************/ -static void rfalIsoDepCalcBitRate( - rfalBitRate maxAllowedBR, - uint8_t piccBRCapability, - rfalBitRate* dsi, - rfalBitRate* dri) { - uint8_t driMask; - uint8_t dsiMask; - int8_t i; - bool bitrateFound; - rfalBitRate curMaxBR; - - curMaxBR = maxAllowedBR; - - do { - bitrateFound = true; - - (*dsi) = RFAL_BR_106; - (*dri) = RFAL_BR_106; - - /* Digital 1.0 5.6.2.5 & 11.6.2.14: A received RFU value of b4 = 1b MUST be interpreted as if b7 to b1 ? 0000000b (only 106 kbits/s in both direction) */ - if(((RFAL_ISODEP_BITRATE_RFU_MASK & piccBRCapability) != 0U) || (curMaxBR > RFAL_BR_848) || - (curMaxBR == RFAL_BR_KEEP)) { - return; - } - - /***************************************************************************/ - /* Determine Listen->Poll bit rate */ - dsiMask = (piccBRCapability & RFAL_ISODEP_BSI_MASK); - for(i = 2; i >= 0; i--) // Check supported bit rate from the highest - { - if(((dsiMask & (0x10U << (uint8_t)i)) != 0U) && - (((uint8_t)i + 1U) <= (uint8_t)curMaxBR)) { - uint8_t newdsi = ((uint8_t)i) + 1U; - (*dsi) = (rfalBitRate) - newdsi; /* PRQA S 4342 # MISRA 10.5 - Layout of enum rfalBitRate and range of loop variable guarantee no invalid enum values to be created */ - break; - } - } - - /***************************************************************************/ - /* Determine Poll->Listen bit rate */ - driMask = (piccBRCapability & RFAL_ISODEP_BRI_MASK); - for(i = 2; i >= 0; i--) /* Check supported bit rate from the highest */ - { - if(((driMask & (0x01U << (uint8_t)i)) != 0U) && - (((uint8_t)i + 1U) <= (uint8_t)curMaxBR)) { - uint8_t newdri = ((uint8_t)i) + 1U; - (*dri) = (rfalBitRate) - newdri; /* PRQA S 4342 # MISRA 10.5 - Layout of enum rfalBitRate and range of loop variable guarantee no invalid enum values to be created */ - break; - } - } - - /***************************************************************************/ - /* Check if different bit rate is supported */ - - /* Digital 1.0 Table 67: if b8=1b, then only the same bit rate divisor for both directions is supported */ - if((piccBRCapability & RFAL_ISODEP_SAME_BITRATE_MASK) != 0U) { - (*dsi) = MIN((*dsi), (*dri)); - (*dri) = (*dsi); - /* Check that the baudrate is supported */ - if((RFAL_BR_106 != (*dsi)) && - (!(((dsiMask & (0x10U << ((uint8_t)(*dsi) - 1U))) != 0U) && - ((driMask & (0x01U << ((uint8_t)(*dri) - 1U))) != 0U)))) { - bitrateFound = false; - curMaxBR = - (*dsi); /* set allowed bitrate to be lowest and determine bit rate again */ - } - } - } while(!(bitrateFound)); -} - -/*******************************************************************************/ -static uint32_t rfalIsoDepSFGI2SFGT(uint8_t sfgi) { - uint32_t sfgt; - uint8_t tmpSFGI; - - tmpSFGI = sfgi; - - if(tmpSFGI > ISODEP_SFGI_MAX) { - tmpSFGI = ISODEP_SFGI_MIN; - } - - if(tmpSFGI != ISODEP_SFGI_MIN) { - /* If sfgi != 0 wait SFGT + dSFGT Digital 1.1 13.8.2.1 */ - sfgt = isoDepCalcSGFT(sfgi) + isoDepCalcdSGFT(sfgi); - } - /* Otherwise use FDTPoll min Digital 1.1 13.8.2.3*/ - else { - sfgt = RFAL_FDT_POLL_NFCA_POLLER; - } - - /* Convert carrier cycles to milli seconds */ - return (rfalConv1fcToMs(sfgt) + 1U); -} - -#endif /* RFAL_FEATURE_ISO_DEP_POLL */ - -/*******************************************************************************/ -static void rfalIsoDepApdu2IBLockParam( - rfalIsoDepApduTxRxParam apduParam, - rfalIsoDepTxRxParam* iBlockParam, - uint16_t txPos, - uint16_t rxPos) { - NO_WARNING(rxPos); /* Keep this param for future use */ - - iBlockParam->DID = apduParam.DID; - iBlockParam->FSx = apduParam.FSx; - iBlockParam->ourFSx = apduParam.ourFSx; - iBlockParam->FWT = apduParam.FWT; - iBlockParam->dFWT = apduParam.dFWT; - - if((apduParam.txBufLen - txPos) > rfalIsoDepGetMaxInfLen()) { - iBlockParam->isTxChaining = true; - iBlockParam->txBufLen = rfalIsoDepGetMaxInfLen(); - } else { - iBlockParam->isTxChaining = false; - iBlockParam->txBufLen = (apduParam.txBufLen - txPos); - } - - /* TxBuf is moved to the beginning for every I-Block */ - iBlockParam->txBuf = - (rfalIsoDepBufFormat*)apduParam - .txBuf; /* PRQA S 0310 # MISRA 11.3 - Intentional safe cast to avoiding large buffer duplication */ - iBlockParam->rxBuf = - apduParam - .tmpBuf; /* Simply using the apdu buffer is not possible because of current ACK handling */ - iBlockParam->isRxChaining = &gIsoDep.isAPDURxChaining; - iBlockParam->rxLen = apduParam.rxLen; -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepStartApduTransceive(rfalIsoDepApduTxRxParam param) { - rfalIsoDepTxRxParam txRxParam; - - /* Initialize and store APDU context */ - gIsoDep.APDUParam = param; - gIsoDep.APDUTxPos = 0; - gIsoDep.APDURxPos = 0; - - /* Assign current FSx to calculate INF length (only change the FSx from activation if no to Keep) */ - gIsoDep.ourFsx = ((param.ourFSx != RFAL_ISODEP_FSX_KEEP) ? param.ourFSx : gIsoDep.ourFsx); - gIsoDep.fsx = param.FSx; - - /* Convert APDU TxRxParams to I-Block TxRxParams */ - rfalIsoDepApdu2IBLockParam( - gIsoDep.APDUParam, &txRxParam, gIsoDep.APDUTxPos, gIsoDep.APDURxPos); - - return rfalIsoDepStartTransceive(txRxParam); -} - -/*******************************************************************************/ -ReturnCode rfalIsoDepGetApduTransceiveStatus(void) { - ReturnCode ret; - rfalIsoDepTxRxParam txRxParam; - - ret = rfalIsoDepGetTransceiveStatus(); - switch(ret) { - /*******************************************************************************/ - case ERR_NONE: - - /* Check if we are still doing chaining on Tx */ - if(gIsoDep.isTxChaining) { - /* Add already Tx bytes */ - gIsoDep.APDUTxPos += gIsoDep.txBufLen; - - /* Convert APDU TxRxParams to I-Block TxRxParams */ - rfalIsoDepApdu2IBLockParam( - gIsoDep.APDUParam, &txRxParam, gIsoDep.APDUTxPos, gIsoDep.APDURxPos); - - if(txRxParam.txBufLen > 0U) /* MISRA 21.18 */ - { - /* Move next I-Block to beginning of APDU Tx buffer */ - ST_MEMCPY( - gIsoDep.APDUParam.txBuf->apdu, - &gIsoDep.APDUParam.txBuf->apdu[gIsoDep.APDUTxPos], - txRxParam.txBufLen); - } - - EXIT_ON_ERR(ret, rfalIsoDepStartTransceive(txRxParam)); - return ERR_BUSY; - } - - /* APDU TxRx is done */ - /* fall through */ - - /*******************************************************************************/ - case ERR_AGAIN: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - /* Check if no APDU transceive has been started before (data from rfalIsoDepListenStartActivation) */ - if(gIsoDep.APDUParam.rxLen == NULL) { - if(ret == ERR_AGAIN) { - /* In Listen mode first chained packet cannot be retrieved via APDU interface */ - return ERR_NOTSUPP; - } - - /* TxRx is complete and full data is already available */ - return ERR_NONE; - } - - if(*gIsoDep.APDUParam.rxLen > 0U) /* MISRA 21.18 */ - { - /* Ensure that data in tmpBuf still fits into APDU buffer */ - if((gIsoDep.APDURxPos + (*gIsoDep.APDUParam.rxLen)) > - (uint16_t)RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN) { - return ERR_NOMEM; - } - - /* Copy chained packet from tmp buffer to APDU buffer */ - ST_MEMCPY( - &gIsoDep.APDUParam.rxBuf->apdu[gIsoDep.APDURxPos], - gIsoDep.APDUParam.tmpBuf->inf, - *gIsoDep.APDUParam.rxLen); - gIsoDep.APDURxPos += *gIsoDep.APDUParam.rxLen; - } - - /* Update output param rxLen */ - *gIsoDep.APDUParam.rxLen = gIsoDep.APDURxPos * 8; - - /* Wait for following I-Block or APDU TxRx has finished */ - return ((ret == ERR_AGAIN) ? ERR_BUSY : ERR_NONE); - - /*******************************************************************************/ - default: - /* MISRA 16.4: no empty default statement (a comment being enough) */ - break; - } - - return ret; -} - -#endif /* RFAL_FEATURE_ISO_DEP */ diff --git a/lib/ST25RFAL002/source/rfal_nfc.c b/lib/ST25RFAL002/source/rfal_nfc.c deleted file mode 100644 index 57ff2e235..000000000 --- a/lib/ST25RFAL002/source/rfal_nfc.c +++ /dev/null @@ -1,2118 +0,0 @@ -/** - ****************************************************************************** - * - * COPYRIGHT(c) 2020 STMicroelectronics - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. Neither the name of STMicroelectronics nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - ****************************************************************************** - */ - -/*! \file rfal_nfc.c - * - * \author Gustavo Patricio - * - * \brief RFAL NFC device - * - * This module provides the required features to behave as an NFC Poller - * or Listener device. It grants an easy to use interface for the following - * activities: Technology Detection, Collision Resollution, Activation, - * Data Exchange, and Deactivation - * - * This layer is influenced by (but not fully aligned with) the NFC Forum - * specifications, in particular: Activity 2.0 and NCI 2.0 - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_nfc.h" -#include "utils.h" -#include "rfal_analogConfig.h" - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ -#define RFAL_NFC_MAX_DEVICES 5U /* Max number of devices supported */ - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ - -#define rfalNfcNfcNotify(st) \ - if(gNfcDev.disc.notifyCb != NULL) gNfcDev.disc.notifyCb(st) - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! Buffer union, only one interface is used at a time */ -typedef union { /* PRQA S 0750 # MISRA 19.2 - Members of the union will not be used concurrently, only one interface at a time */ - rfalIsoDepBufFormat isoDepBuf; /*!< ISO-DEP buffer format (with header/prologue) */ - rfalNfcDepBufFormat nfcDepBuf; /*!< NFC-DEP buffer format (with header/prologue) */ -} rfalNfcTmpBuffer; - -typedef struct { - rfalNfcState state; /* Main state */ - uint16_t techsFound; /* Technologies found bitmask */ - uint16_t techs2do; /* Technologies still to be performed */ - rfalBitRate ap2pBR; /* Bit rate to poll for AP2P */ - uint8_t selDevIdx; /* Selected device index */ - rfalNfcDevice* activeDev; /* Active device pointer */ - rfalNfcDiscoverParam disc; /* Discovery parameters */ - rfalNfcDevice devList[RFAL_NFC_MAX_DEVICES]; /*!< Location of device list */ - uint8_t devCnt; /* Devices found counter */ - uint32_t discTmr; /* Discovery Total duration timer */ - ReturnCode dataExErr; /* Last Data Exchange error */ - bool discRestart; /* Restart discover after deactivation flag */ - bool isRxChaining; /* Flag indicating Other device is chaining */ - uint32_t lmMask; /* Listen Mode mask */ - bool isTechInit; /* Flag indicating technology has been set */ - bool isOperOngoing; /* Flag indicating operation is ongoing */ - - rfalNfcBuffer txBuf; /* Tx buffer for Data Exchange */ - rfalNfcBuffer rxBuf; /* Rx buffer for Data Exchange */ - uint16_t rxLen; /* Length of received data on Data Exchange */ - -#if RFAL_FEATURE_NFC_DEP || RFAL_FEATURE_ISO_DEP - rfalNfcTmpBuffer tmpBuf; /* Tmp buffer for Data Exchange */ -#endif /* RFAL_FEATURE_NFC_DEP || RFAL_FEATURE_ISO_DEP */ - -} rfalNfc; - -/* - ****************************************************************************** - * LOCAL VARIABLES - ****************************************************************************** - */ -#ifdef RFAL_TEST_MODE -rfalNfc gNfcDev; -#else /* RFAL_TEST_MODE */ -static rfalNfc gNfcDev; -#endif /* RFAL_TEST_MODE */ - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -static ReturnCode rfalNfcPollTechDetetection(void); -static ReturnCode rfalNfcPollCollResolution(void); -static ReturnCode rfalNfcPollActivation(uint8_t devIt); -static ReturnCode rfalNfcDeactivation(void); - -#if RFAL_FEATURE_NFC_DEP -static ReturnCode rfalNfcNfcDepActivate( - rfalNfcDevice* device, - rfalNfcDepCommMode commMode, - const uint8_t* atrReq, - uint16_t atrReqLen); -#endif /* RFAL_FEATURE_NFC_DEP */ - -#if RFAL_FEATURE_LISTEN_MODE -static ReturnCode rfalNfcListenActivation(void); -#endif /* RFAL_FEATURE_LISTEN_MODE*/ - -/*******************************************************************************/ -ReturnCode rfalNfcInitialize(void) { - ReturnCode err; - - gNfcDev.state = RFAL_NFC_STATE_NOTINIT; - - rfalAnalogConfigInitialize(); /* Initialize RFAL's Analog Configs */ - EXIT_ON_ERR(err, rfalInitialize()); /* Initialize RFAL */ - - gNfcDev.state = RFAL_NFC_STATE_IDLE; /* Go to initialized */ - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDiscover(const rfalNfcDiscoverParam* disParams) { - /* Check if initialization has been performed */ - if(gNfcDev.state != RFAL_NFC_STATE_IDLE) { - return ERR_WRONG_STATE; - } - - /* Check valid parameters */ - if((disParams == NULL) || (disParams->devLimit > RFAL_NFC_MAX_DEVICES) || - (disParams->devLimit == 0U) || - ((disParams->maxBR > RFAL_BR_1695) && (disParams->maxBR != RFAL_BR_KEEP)) || - (((disParams->techs2Find & RFAL_NFC_POLL_TECH_F) != 0U) && - (disParams->nfcfBR != RFAL_BR_212) && (disParams->nfcfBR != RFAL_BR_424)) || - ((((disParams->techs2Find & RFAL_NFC_POLL_TECH_AP2P) != 0U) && - (disParams->ap2pBR > RFAL_BR_424)) || - (disParams->GBLen > RFAL_NFCDEP_GB_MAX_LEN))) { - return ERR_PARAM; - } - - if((((disParams->techs2Find & RFAL_NFC_POLL_TECH_A) != 0U) && !((bool)RFAL_FEATURE_NFCA)) || - (((disParams->techs2Find & RFAL_NFC_POLL_TECH_B) != 0U) && !((bool)RFAL_FEATURE_NFCB)) || - (((disParams->techs2Find & RFAL_NFC_POLL_TECH_F) != 0U) && !((bool)RFAL_FEATURE_NFCF)) || - (((disParams->techs2Find & RFAL_NFC_POLL_TECH_V) != 0U) && !((bool)RFAL_FEATURE_NFCV)) || - (((disParams->techs2Find & RFAL_NFC_POLL_TECH_ST25TB) != 0U) && - !((bool)RFAL_FEATURE_ST25TB)) || - (((disParams->techs2Find & RFAL_NFC_POLL_TECH_AP2P) != 0U) && - !((bool)RFAL_FEATURE_NFC_DEP)) || - (((disParams->techs2Find & RFAL_NFC_LISTEN_TECH_A) != 0U) && !((bool)RFAL_FEATURE_NFCA)) || - (((disParams->techs2Find & RFAL_NFC_LISTEN_TECH_B) != 0U) && !((bool)RFAL_FEATURE_NFCB)) || - (((disParams->techs2Find & RFAL_NFC_LISTEN_TECH_F) != 0U) && !((bool)RFAL_FEATURE_NFCF)) || - (((disParams->techs2Find & RFAL_NFC_LISTEN_TECH_AP2P) != 0U) && - !((bool)RFAL_FEATURE_NFC_DEP))) { - return ERR_DISABLED; /* PRQA S 2880 # MISRA 2.1 - Unreachable code due to configuration option being set/unset */ - } - - /* Initialize context for discovery */ - gNfcDev.activeDev = NULL; - gNfcDev.techsFound = RFAL_NFC_TECH_NONE; - gNfcDev.devCnt = 0; - gNfcDev.discRestart = true; - gNfcDev.isTechInit = false; - gNfcDev.disc = *disParams; - - /* Calculate Listen Mask */ - gNfcDev.lmMask = 0U; - gNfcDev.lmMask |= - (((gNfcDev.disc.techs2Find & RFAL_NFC_LISTEN_TECH_A) != 0U) ? RFAL_LM_MASK_NFCA : 0U); - gNfcDev.lmMask |= - (((gNfcDev.disc.techs2Find & RFAL_NFC_LISTEN_TECH_B) != 0U) ? RFAL_LM_MASK_NFCB : 0U); - gNfcDev.lmMask |= - (((gNfcDev.disc.techs2Find & RFAL_NFC_LISTEN_TECH_F) != 0U) ? RFAL_LM_MASK_NFCF : 0U); - gNfcDev.lmMask |= - (((gNfcDev.disc.techs2Find & RFAL_NFC_LISTEN_TECH_AP2P) != 0U) ? RFAL_LM_MASK_ACTIVE_P2P : - 0U); - -#if !RFAL_FEATURE_LISTEN_MODE - /* Check if Listen Mode is supported/Enabled */ - if(gNfcDev.lmMask != 0U) { - return ERR_DISABLED; - } -#endif - - gNfcDev.state = RFAL_NFC_STATE_START_DISCOVERY; - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDeactivate(bool discovery) { - /* Check for valid state */ - if(gNfcDev.state <= RFAL_NFC_STATE_IDLE) { - return ERR_WRONG_STATE; - } - - /* Check if discovery is to continue afterwards */ - if((discovery == true) && (gNfcDev.disc.techs2Find != RFAL_NFC_TECH_NONE)) { - /* If so let the state machine continue*/ - gNfcDev.discRestart = discovery; - gNfcDev.state = RFAL_NFC_STATE_DEACTIVATION; - } else { - /* Otherwise deactivate immediately and go to IDLE */ - rfalNfcDeactivation(); - gNfcDev.state = RFAL_NFC_STATE_IDLE; - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcSelect(uint8_t devIdx) { - /* Check for valid state */ - if(gNfcDev.state != RFAL_NFC_STATE_POLL_SELECT) { - return ERR_WRONG_STATE; - } - - gNfcDev.selDevIdx = devIdx; - gNfcDev.state = RFAL_NFC_STATE_POLL_ACTIVATION; - - return ERR_NONE; -} - -/*******************************************************************************/ -rfalNfcState rfalNfcGetState(void) { - return gNfcDev.state; -} - -/*******************************************************************************/ -ReturnCode rfalNfcGetDevicesFound(rfalNfcDevice** devList, uint8_t* devCnt) { - /* Check for valid state */ - if(gNfcDev.state < RFAL_NFC_STATE_POLL_SELECT) { - return ERR_WRONG_STATE; - } - - /* Check valid parameters */ - if((devList == NULL) || (devCnt == NULL)) { - return ERR_PARAM; - } - - *devCnt = gNfcDev.devCnt; - *devList = gNfcDev.devList; - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcGetActiveDevice(rfalNfcDevice** dev) { - /* Check for valid state */ - if(gNfcDev.state < RFAL_NFC_STATE_ACTIVATED) { - return ERR_WRONG_STATE; - } - - /* Check valid parameter */ - if(dev == NULL) { - return ERR_PARAM; - } - - /* Check for valid state */ - if((gNfcDev.devCnt == 0U) || (gNfcDev.activeDev == NULL)) { - return ERR_REQUEST; - } - - *dev = gNfcDev.activeDev; - return ERR_NONE; -} - -/*******************************************************************************/ -void rfalNfcWorker(void) { - ReturnCode err; - - rfalWorker(); /* Execute RFAL process */ - - switch(gNfcDev.state) { - /*******************************************************************************/ - case RFAL_NFC_STATE_NOTINIT: - case RFAL_NFC_STATE_IDLE: - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_START_DISCOVERY: - - /* Initialize context for discovery cycle */ - gNfcDev.devCnt = 0; - gNfcDev.selDevIdx = 0; - gNfcDev.techsFound = RFAL_NFC_TECH_NONE; - gNfcDev.techs2do = gNfcDev.disc.techs2Find; - gNfcDev.state = RFAL_NFC_STATE_POLL_TECHDETECT; - -#if RFAL_FEATURE_WAKEUP_MODE - /* Check if Low power Wake-Up is to be performed */ - if(gNfcDev.disc.wakeupEnabled) { - /* Initialize Low power Wake-up mode and wait */ - err = rfalWakeUpModeStart( - (gNfcDev.disc.wakeupConfigDefault ? NULL : &gNfcDev.disc.wakeupConfig)); - if(err == ERR_NONE) { - gNfcDev.state = RFAL_NFC_STATE_WAKEUP_MODE; - rfalNfcNfcNotify(gNfcDev.state); /* Notify caller that WU was started */ - } - } -#endif /* RFAL_FEATURE_WAKEUP_MODE */ - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_WAKEUP_MODE: - -#if RFAL_FEATURE_WAKEUP_MODE - /* Check if the Wake-up mode has woke */ - if(rfalWakeUpModeHasWoke()) { - rfalWakeUpModeStop(); /* Disable Wake-up mode */ - gNfcDev.state = RFAL_NFC_STATE_POLL_TECHDETECT; /* Go to Technology detection */ - - rfalNfcNfcNotify(gNfcDev.state); /* Notify caller that WU has woke */ - } -#endif /* RFAL_FEATURE_WAKEUP_MODE */ - - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_POLL_TECHDETECT: - - /* Start total duration timer */ - platformTimerDestroy(gNfcDev.discTmr); - gNfcDev.discTmr = (uint32_t)platformTimerCreate(gNfcDev.disc.totalDuration); - - err = - rfalNfcPollTechDetetection(); /* Perform Technology Detection */ - if(err != ERR_BUSY) /* Wait until all technologies are performed */ - { - if((err != ERR_NONE) || - (gNfcDev.techsFound == - RFAL_NFC_TECH_NONE)) /* Check if any error occurred or no techs were found */ - { - rfalFieldOff(); - gNfcDev.state = - RFAL_NFC_STATE_LISTEN_TECHDETECT; /* Nothing found as poller, go to listener */ - break; - } - - gNfcDev.techs2do = - gNfcDev.techsFound; /* Store the found technologies for collision resolution */ - gNfcDev.state = - RFAL_NFC_STATE_POLL_COLAVOIDANCE; /* One or more devices found, go to Collision Avoidance */ - } - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_POLL_COLAVOIDANCE: - - err = - rfalNfcPollCollResolution(); /* Resolve any eventual collision */ - if(err != ERR_BUSY) /* Wait until all technologies are performed */ - { - if((err != ERR_NONE) || - (gNfcDev.devCnt == 0U)) /* Check if any error occurred or no devices were found */ - { - gNfcDev.state = RFAL_NFC_STATE_DEACTIVATION; - break; /* Unable to retrieve any device, restart loop */ - } - - /* Check if more than one device has been found */ - if(gNfcDev.devCnt > 1U) { - /* If more than one device was found inform upper layer to choose which one to activate */ - if(gNfcDev.disc.notifyCb != NULL) { - gNfcDev.state = RFAL_NFC_STATE_POLL_SELECT; - gNfcDev.disc.notifyCb(gNfcDev.state); - break; - } - } - - /* If only one device or no callback has been set, activate the first device found */ - gNfcDev.selDevIdx = 0U; - gNfcDev.state = RFAL_NFC_STATE_POLL_ACTIVATION; - } - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_POLL_ACTIVATION: - - err = rfalNfcPollActivation(gNfcDev.selDevIdx); - if(err != ERR_BUSY) /* Wait until all Activation is complete */ - { - if(err != ERR_NONE) /* Activation failed selected device */ - { - gNfcDev.state = - RFAL_NFC_STATE_DEACTIVATION; /* If Activation failed, restart loop */ - break; - } - - gNfcDev.state = RFAL_NFC_STATE_ACTIVATED; /* Device has been properly activated */ - rfalNfcNfcNotify( - gNfcDev.state); /* Inform upper layer that a device has been activated */ - } - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_DATAEXCHANGE: - - rfalNfcDataExchangeGetStatus(); /* Run the internal state machine */ - - if(gNfcDev.dataExErr != ERR_BUSY) /* If Dataexchange has terminated */ - { - gNfcDev.state = RFAL_NFC_STATE_DATAEXCHANGE_DONE; /* Go to done state */ - rfalNfcNfcNotify(gNfcDev.state); /* And notify caller */ - } - if(gNfcDev.dataExErr == ERR_SLEEP_REQ) /* Check if Listen mode has to go to Sleep */ - { - gNfcDev.state = RFAL_NFC_STATE_LISTEN_SLEEP; /* Go to Listen Sleep state */ - rfalNfcNfcNotify(gNfcDev.state); /* And notify caller */ - } - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_DEACTIVATION: - - rfalNfcDeactivation(); /* Deactivate current device */ - - gNfcDev.state = - ((gNfcDev.discRestart) ? RFAL_NFC_STATE_START_DISCOVERY : RFAL_NFC_STATE_IDLE); - rfalNfcNfcNotify(gNfcDev.state); /* Notify caller */ - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_LISTEN_TECHDETECT: - - if(platformTimerIsExpired(gNfcDev.discTmr)) { -#if RFAL_FEATURE_LISTEN_MODE - rfalListenStop(); -#else - rfalFieldOff(); -#endif /* RFAL_FEATURE_LISTEN_MODE */ - - gNfcDev.state = RFAL_NFC_STATE_START_DISCOVERY; /* Restart the discovery loop */ - rfalNfcNfcNotify(gNfcDev.state); /* Notify caller */ - break; - } - -#if RFAL_FEATURE_LISTEN_MODE - - if(gNfcDev.lmMask != 0U) /* Check if configured to perform Listen mode */ - { - err = rfalListenStart( - gNfcDev.lmMask, - &gNfcDev.disc.lmConfigPA, - NULL, - &gNfcDev.disc.lmConfigPF, - (uint8_t*)&gNfcDev.rxBuf.rfBuf, - (uint16_t)rfalConvBytesToBits(sizeof(gNfcDev.rxBuf.rfBuf)), - &gNfcDev.rxLen); - if(err == ERR_NONE) { - gNfcDev.state = - RFAL_NFC_STATE_LISTEN_COLAVOIDANCE; /* Wait for listen mode to be activated */ - } - } - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_LISTEN_COLAVOIDANCE: - - if(platformTimerIsExpired( - gNfcDev.discTmr)) /* Check if the total duration has been reached */ - { - rfalListenStop(); - gNfcDev.state = RFAL_NFC_STATE_START_DISCOVERY; /* Restart the discovery loop */ - rfalNfcNfcNotify(gNfcDev.state); /* Notify caller */ - break; - } - - /* Check for external field */ - if(rfalListenGetState(NULL, NULL) >= RFAL_LM_STATE_IDLE) { - gNfcDev.state = - RFAL_NFC_STATE_LISTEN_ACTIVATION; /* Wait for listen mode to be activated */ - } - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_LISTEN_ACTIVATION: - case RFAL_NFC_STATE_LISTEN_SLEEP: - - err = rfalNfcListenActivation(); - if(err != ERR_BUSY) { - if(err == ERR_NONE) { - gNfcDev.activeDev = - gNfcDev.devList; /* Assign the active device to be used further on */ - gNfcDev.devCnt++; - - gNfcDev.state = RFAL_NFC_STATE_ACTIVATED; /* Device has been properly activated */ - rfalNfcNfcNotify( - gNfcDev.state); /* Inform upper layer that a device has been activated */ - } else { - rfalListenStop(); - gNfcDev.state = RFAL_NFC_STATE_START_DISCOVERY; /* Restart the discovery loop */ - rfalNfcNfcNotify(gNfcDev.state); /* Notify caller */ - } - } -#endif /* RFAL_FEATURE_LISTEN_MODE */ - break; - - /*******************************************************************************/ - case RFAL_NFC_STATE_ACTIVATED: - case RFAL_NFC_STATE_POLL_SELECT: - case RFAL_NFC_STATE_DATAEXCHANGE_DONE: - default: - return; - } -} - -/*******************************************************************************/ -ReturnCode rfalNfcDataExchangeStart( - uint8_t* txData, - uint16_t txDataLen, - uint8_t** rxData, - uint16_t** rvdLen, - uint32_t fwt, - uint32_t flags) { - ReturnCode err; - rfalTransceiveContext ctx; - - /*******************************************************************************/ - /* The Data Exchange is divided in two different moments, the trigger/Start of * - * the transfer followed by the check until its completion */ - if((gNfcDev.state >= RFAL_NFC_STATE_ACTIVATED) && (gNfcDev.activeDev != NULL)) { - /*******************************************************************************/ - /* In Listen mode is the Poller that initiates the communicatation */ - /* Assign output parameters and rfalNfcDataExchangeGetStatus will return */ - /* incoming data from Poller/Initiator */ - if((gNfcDev.state == RFAL_NFC_STATE_ACTIVATED) && - rfalNfcIsRemDevPoller(gNfcDev.activeDev->type)) { - if(txDataLen > 0U) { - return ERR_WRONG_STATE; - } - - *rvdLen = (uint16_t*)&gNfcDev.rxLen; - *rxData = (uint8_t*)( (gNfcDev.activeDev->rfInterface == RFAL_NFC_INTERFACE_ISODEP) ? gNfcDev.rxBuf.isoDepBuf.apdu : - ((gNfcDev.activeDev->rfInterface == RFAL_NFC_INTERFACE_NFCDEP) ? gNfcDev.rxBuf.nfcDepBuf.pdu : gNfcDev.rxBuf.rfBuf)); - if(gNfcDev.disc.activate_after_sak) { - gNfcDev.state = RFAL_NFC_STATE_DATAEXCHANGE_DONE; - } - return ERR_NONE; - } - - /*******************************************************************************/ - switch(gNfcDev.activeDev - ->rfInterface) /* Check which RF interface shall be used/has been activated */ - { - /*******************************************************************************/ - case RFAL_NFC_INTERFACE_RF: - - rfalCreateByteFlagsTxRxContext( - ctx, - (uint8_t*)txData, - txDataLen, - gNfcDev.rxBuf.rfBuf, - sizeof(gNfcDev.rxBuf.rfBuf), - &gNfcDev.rxLen, - flags, - fwt); - if(flags == RFAL_TXRX_FLAGS_RAW) { - ctx.txBufLen = txDataLen; - } - *rxData = (uint8_t*)gNfcDev.rxBuf.rfBuf; - *rvdLen = (uint16_t*)&gNfcDev.rxLen; - err = rfalStartTransceive(&ctx); - break; - -#if RFAL_FEATURE_ISO_DEP - /*******************************************************************************/ - case RFAL_NFC_INTERFACE_ISODEP: { - rfalIsoDepApduTxRxParam isoDepTxRx; - - if(txDataLen > sizeof(gNfcDev.txBuf.isoDepBuf.apdu)) { - return ERR_NOMEM; - } - - if(txDataLen > 0U) { - ST_MEMCPY((uint8_t*)gNfcDev.txBuf.isoDepBuf.apdu, txData, txDataLen); - } - - isoDepTxRx.DID = RFAL_ISODEP_NO_DID; - isoDepTxRx.ourFSx = RFAL_ISODEP_FSX_KEEP; - isoDepTxRx.FSx = gNfcDev.activeDev->proto.isoDep.info.FSx; - isoDepTxRx.dFWT = gNfcDev.activeDev->proto.isoDep.info.dFWT; - isoDepTxRx.FWT = gNfcDev.activeDev->proto.isoDep.info.FWT; - isoDepTxRx.txBuf = &gNfcDev.txBuf.isoDepBuf; - isoDepTxRx.txBufLen = txDataLen; - isoDepTxRx.rxBuf = &gNfcDev.rxBuf.isoDepBuf; - isoDepTxRx.rxLen = &gNfcDev.rxLen; - isoDepTxRx.tmpBuf = &gNfcDev.tmpBuf.isoDepBuf; - *rxData = (uint8_t*)gNfcDev.rxBuf.isoDepBuf.apdu; - *rvdLen = (uint16_t*)&gNfcDev.rxLen; - - /*******************************************************************************/ - /* Trigger a RFAL ISO-DEP Transceive */ - err = rfalIsoDepStartApduTransceive(isoDepTxRx); - break; - } -#endif /* RFAL_FEATURE_ISO_DEP */ - -#if RFAL_FEATURE_NFC_DEP - /*******************************************************************************/ - case RFAL_NFC_INTERFACE_NFCDEP: { - rfalNfcDepPduTxRxParam nfcDepTxRx; - - if(txDataLen > sizeof(gNfcDev.txBuf.nfcDepBuf.pdu)) { - return ERR_NOMEM; - } - - if(txDataLen > 0U) { - ST_MEMCPY((uint8_t*)gNfcDev.txBuf.nfcDepBuf.pdu, txData, txDataLen); - } - - nfcDepTxRx.DID = RFAL_NFCDEP_DID_KEEP; - nfcDepTxRx.FSx = - rfalNfcIsRemDevListener(gNfcDev.activeDev->type) ? - rfalNfcDepLR2FS((uint8_t)rfalNfcDepPP2LR( - gNfcDev.activeDev->proto.nfcDep.activation.Target.ATR_RES.PPt)) : - rfalNfcDepLR2FS((uint8_t)rfalNfcDepPP2LR( - gNfcDev.activeDev->proto.nfcDep.activation.Initiator.ATR_REQ.PPi)); - nfcDepTxRx.dFWT = gNfcDev.activeDev->proto.nfcDep.info.dFWT; - nfcDepTxRx.FWT = gNfcDev.activeDev->proto.nfcDep.info.FWT; - nfcDepTxRx.txBuf = &gNfcDev.txBuf.nfcDepBuf; - nfcDepTxRx.txBufLen = txDataLen; - nfcDepTxRx.rxBuf = &gNfcDev.rxBuf.nfcDepBuf; - nfcDepTxRx.rxLen = &gNfcDev.rxLen; - nfcDepTxRx.tmpBuf = &gNfcDev.tmpBuf.nfcDepBuf; - *rxData = (uint8_t*)gNfcDev.rxBuf.nfcDepBuf.pdu; - *rvdLen = (uint16_t*)&gNfcDev.rxLen; - - /*******************************************************************************/ - /* Trigger a RFAL NFC-DEP Transceive */ - err = rfalNfcDepStartPduTransceive(nfcDepTxRx); - break; - } -#endif /* RFAL_FEATURE_NFC_DEP */ - - /*******************************************************************************/ - default: - err = ERR_PARAM; - break; - } - - /* If a transceive has successfuly started flag Data Exchange as ongoing */ - if(err == ERR_NONE) { - gNfcDev.dataExErr = ERR_BUSY; - gNfcDev.state = RFAL_NFC_STATE_DATAEXCHANGE; - } - - return err; - } - - return ERR_WRONG_STATE; -} - -ReturnCode rfalNfcDataExchangeCustomStart( - uint8_t* txData, - uint16_t txDataLen, - uint8_t** rxData, - uint16_t** rvdLen, - uint32_t fwt, - uint32_t flags) { - ReturnCode err; - rfalTransceiveContext ctx; - - /*******************************************************************************/ - /* The Data Exchange is divided in two different moments, the trigger/Start of * - * the transfer followed by the check until its completion */ - if((gNfcDev.state >= RFAL_NFC_STATE_ACTIVATED) && (gNfcDev.activeDev != NULL)) { - /*******************************************************************************/ - /* In Listen mode is the Poller that initiates the communicatation */ - /* Assign output parameters and rfalNfcDataExchangeGetStatus will return */ - /* incoming data from Poller/Initiator */ - if((gNfcDev.state == RFAL_NFC_STATE_ACTIVATED) && - rfalNfcIsRemDevPoller(gNfcDev.activeDev->type)) { - if(txDataLen > 0U) { - return ERR_WRONG_STATE; - } - - *rvdLen = (uint16_t*)&gNfcDev.rxLen; - *rxData = (uint8_t*)( (gNfcDev.activeDev->rfInterface == RFAL_NFC_INTERFACE_ISODEP) ? gNfcDev.rxBuf.isoDepBuf.apdu : - ((gNfcDev.activeDev->rfInterface == RFAL_NFC_INTERFACE_NFCDEP) ? gNfcDev.rxBuf.nfcDepBuf.pdu : gNfcDev.rxBuf.rfBuf)); - if(gNfcDev.disc.activate_after_sak) { - gNfcDev.state = RFAL_NFC_STATE_DATAEXCHANGE_DONE; - } - return ERR_NONE; - } - - /*******************************************************************************/ - switch(gNfcDev.activeDev - ->rfInterface) /* Check which RF interface shall be used/has been activated */ - { - /*******************************************************************************/ - case RFAL_NFC_INTERFACE_RF: - ctx.rxBuf = gNfcDev.rxBuf.rfBuf; - ctx.rxBufLen = 8 * sizeof(gNfcDev.rxBuf.rfBuf); - ctx.rxRcvdLen = &gNfcDev.rxLen; - ctx.txBuf = txData; - ctx.txBufLen = txDataLen; - ctx.flags = flags; - ctx.fwt = fwt; - *rxData = (uint8_t*)gNfcDev.rxBuf.rfBuf; - *rvdLen = (uint16_t*)&gNfcDev.rxLen; - err = rfalStartTransceive(&ctx); - break; - -#if RFAL_FEATURE_ISO_DEP - /*******************************************************************************/ - case RFAL_NFC_INTERFACE_ISODEP: { - rfalIsoDepApduTxRxParam isoDepTxRx; - uint16_t tx_bytes = txDataLen / 8; - - if(tx_bytes > sizeof(gNfcDev.txBuf.isoDepBuf.apdu)) { - return ERR_NOMEM; - } - - if(tx_bytes > 0U) { - ST_MEMCPY((uint8_t*)gNfcDev.txBuf.isoDepBuf.apdu, txData, tx_bytes); - } - - isoDepTxRx.DID = RFAL_ISODEP_NO_DID; - isoDepTxRx.ourFSx = RFAL_ISODEP_FSX_KEEP; - isoDepTxRx.FSx = gNfcDev.activeDev->proto.isoDep.info.FSx; - isoDepTxRx.dFWT = gNfcDev.activeDev->proto.isoDep.info.dFWT; - isoDepTxRx.FWT = gNfcDev.activeDev->proto.isoDep.info.FWT; - isoDepTxRx.txBuf = &gNfcDev.txBuf.isoDepBuf; - isoDepTxRx.txBufLen = tx_bytes; - isoDepTxRx.rxBuf = &gNfcDev.rxBuf.isoDepBuf; - isoDepTxRx.rxLen = &gNfcDev.rxLen; - isoDepTxRx.tmpBuf = &gNfcDev.tmpBuf.isoDepBuf; - *rxData = (uint8_t*)gNfcDev.rxBuf.isoDepBuf.apdu; - *rvdLen = (uint16_t*)&gNfcDev.rxLen; - - /*******************************************************************************/ - /* Trigger a RFAL ISO-DEP Transceive */ - err = rfalIsoDepStartApduTransceive(isoDepTxRx); - break; - } -#endif /* RFAL_FEATURE_ISO_DEP */ - -#if RFAL_FEATURE_NFC_DEP - /*******************************************************************************/ - case RFAL_NFC_INTERFACE_NFCDEP: { - rfalNfcDepPduTxRxParam nfcDepTxRx; - - if(txDataLen > sizeof(gNfcDev.txBuf.nfcDepBuf.pdu)) { - return ERR_NOMEM; - } - - if(txDataLen > 0U) { - ST_MEMCPY((uint8_t*)gNfcDev.txBuf.nfcDepBuf.pdu, txData, txDataLen); - } - - nfcDepTxRx.DID = RFAL_NFCDEP_DID_KEEP; - nfcDepTxRx.FSx = - rfalNfcIsRemDevListener(gNfcDev.activeDev->type) ? - rfalNfcDepLR2FS((uint8_t)rfalNfcDepPP2LR( - gNfcDev.activeDev->proto.nfcDep.activation.Target.ATR_RES.PPt)) : - rfalNfcDepLR2FS((uint8_t)rfalNfcDepPP2LR( - gNfcDev.activeDev->proto.nfcDep.activation.Initiator.ATR_REQ.PPi)); - nfcDepTxRx.dFWT = gNfcDev.activeDev->proto.nfcDep.info.dFWT; - nfcDepTxRx.FWT = gNfcDev.activeDev->proto.nfcDep.info.FWT; - nfcDepTxRx.txBuf = &gNfcDev.txBuf.nfcDepBuf; - nfcDepTxRx.txBufLen = txDataLen; - nfcDepTxRx.rxBuf = &gNfcDev.rxBuf.nfcDepBuf; - nfcDepTxRx.rxLen = &gNfcDev.rxLen; - nfcDepTxRx.tmpBuf = &gNfcDev.tmpBuf.nfcDepBuf; - *rxData = (uint8_t*)gNfcDev.rxBuf.nfcDepBuf.pdu; - *rvdLen = (uint16_t*)&gNfcDev.rxLen; - - /*******************************************************************************/ - /* Trigger a RFAL NFC-DEP Transceive */ - err = rfalNfcDepStartPduTransceive(nfcDepTxRx); - break; - } -#endif /* RFAL_FEATURE_NFC_DEP */ - - /*******************************************************************************/ - default: - err = ERR_PARAM; - break; - } - - /* If a transceive has successfuly started flag Data Exchange as ongoing */ - if(err == ERR_NONE) { - gNfcDev.dataExErr = ERR_BUSY; - gNfcDev.state = RFAL_NFC_STATE_DATAEXCHANGE; - } - - return err; - } - - return ERR_WRONG_STATE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDataExchangeGetStatus(void) { - /*******************************************************************************/ - /* Check if it's the first frame received in Listen mode */ - if(gNfcDev.state == RFAL_NFC_STATE_ACTIVATED) { - /* Continue data exchange as normal */ - gNfcDev.dataExErr = ERR_BUSY; - gNfcDev.state = RFAL_NFC_STATE_DATAEXCHANGE; - - /* Check if we performing in T3T CE */ - if((gNfcDev.activeDev->type == RFAL_NFC_POLL_TYPE_NFCF) && - (gNfcDev.activeDev->rfInterface == RFAL_NFC_INTERFACE_RF)) { - /* The first frame has been retrieved by rfalListenMode, flag data immediately */ - /* Can only call rfalGetTransceiveStatus() after starting a transceive with rfalStartTransceive */ - gNfcDev.dataExErr = ERR_NONE; - } - } - - /*******************************************************************************/ - /* Check if we are in we have been placed to sleep, and return last error */ - if(gNfcDev.state == RFAL_NFC_STATE_LISTEN_SLEEP) { - return gNfcDev.dataExErr; /* ERR_SLEEP_REQ */ - } - - /*******************************************************************************/ - /* Check if Data exchange has been started */ - if((gNfcDev.state != RFAL_NFC_STATE_DATAEXCHANGE) && - (gNfcDev.state != RFAL_NFC_STATE_DATAEXCHANGE_DONE)) { - return ERR_WRONG_STATE; - } - - /* Check if Data exchange is still ongoing */ - if(gNfcDev.dataExErr == ERR_BUSY) { - switch(gNfcDev.activeDev->rfInterface) { - /*******************************************************************************/ - case RFAL_NFC_INTERFACE_RF: - gNfcDev.dataExErr = rfalGetTransceiveStatus(); - break; - -#if RFAL_FEATURE_ISO_DEP - /*******************************************************************************/ - case RFAL_NFC_INTERFACE_ISODEP: - gNfcDev.dataExErr = rfalIsoDepGetApduTransceiveStatus(); - break; -#endif /* RFAL_FEATURE_ISO_DEP */ - - /*******************************************************************************/ -#if RFAL_FEATURE_NFC_DEP - case RFAL_NFC_INTERFACE_NFCDEP: - gNfcDev.dataExErr = rfalNfcDepGetPduTransceiveStatus(); - break; -#endif /* RFAL_FEATURE_NFC_DEP */ - - /*******************************************************************************/ - default: - gNfcDev.dataExErr = ERR_PARAM; - break; - } - -#if RFAL_FEATURE_LISTEN_MODE - /*******************************************************************************/ - /* If a Sleep request has been received (Listen Mode) go to sleep immediately */ - if(gNfcDev.dataExErr == ERR_SLEEP_REQ) { - EXIT_ON_ERR( - gNfcDev.dataExErr, - rfalListenSleepStart( - RFAL_LM_STATE_SLEEP_A, - gNfcDev.rxBuf.rfBuf, - sizeof(gNfcDev.rxBuf.rfBuf), - &gNfcDev.rxLen)); - - /* If set Sleep was successful keep restore the Sleep request signal */ - gNfcDev.dataExErr = ERR_SLEEP_REQ; - } -#endif /* RFAL_FEATURE_LISTEN_MODE */ - } - - return gNfcDev.dataExErr; -} - -/*! - ****************************************************************************** - * \brief Poller Technology Detection - * - * This method implements the Technology Detection / Poll for different - * device technologies. - * - * \return ERR_NONE : Operation completed with no error - * \return ERR_BUSY : Operation ongoing - * \return ERR_XXXX : Error occurred - * - ****************************************************************************** - */ -static ReturnCode rfalNfcPollTechDetetection(void) { - ReturnCode err; - - err = ERR_NONE; - - /* Suppress warning when specific RFAL features have been disabled */ - NO_WARNING(err); - - /*******************************************************************************/ - /* AP2P Technology Detection */ - /*******************************************************************************/ - if(((gNfcDev.disc.techs2Find & RFAL_NFC_POLL_TECH_AP2P) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_AP2P) != 0U)) { -#if RFAL_FEATURE_NFC_DEP - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR( - err, - rfalSetMode(RFAL_MODE_POLL_ACTIVE_P2P, gNfcDev.disc.ap2pBR, gNfcDev.disc.ap2pBR)); - rfalSetErrorHandling(RFAL_ERRORHANDLING_NFC); - rfalSetFDTListen(RFAL_FDT_LISTEN_AP2P_POLLER); - rfalSetFDTPoll(RFAL_TIMING_NONE); - rfalSetGT(RFAL_GT_AP2P_ADJUSTED); - EXIT_ON_ERR(err, rfalFieldOnAndStartGT()); /* Turns the Field On and starts GT timer */ - gNfcDev.isTechInit = true; - } - - if(rfalIsGTExpired()) /* Wait until Guard Time is fulfilled */ - { - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_AP2P; - - err = rfalNfcNfcDepActivate( - gNfcDev.devList, RFAL_NFCDEP_COMM_ACTIVE, NULL, 0); /* Poll for NFC-A devices */ - if(err == ERR_NONE) { - gNfcDev.techsFound |= RFAL_NFC_POLL_TECH_AP2P; - - gNfcDev.devList->type = RFAL_NFC_LISTEN_TYPE_AP2P; - gNfcDev.devList->rfInterface = RFAL_NFC_INTERFACE_NFCDEP; - gNfcDev.devCnt++; - - return ERR_NONE; - } - - gNfcDev.isTechInit = false; - rfalFieldOff(); - } - return ERR_BUSY; - -#endif /* RFAL_FEATURE_NFC_DEP */ - } - - /*******************************************************************************/ - /* Passive NFC-A Technology Detection */ - /*******************************************************************************/ - if(((gNfcDev.disc.techs2Find & RFAL_NFC_POLL_TECH_A) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_A) != 0U)) { -#if RFAL_FEATURE_NFCA - - rfalNfcaSensRes sensRes; - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR(err, rfalNfcaPollerInitialize()); /* Initialize RFAL for NFC-A */ - EXIT_ON_ERR(err, rfalFieldOnAndStartGT()); /* Turns the Field On and starts GT timer */ - gNfcDev.isTechInit = true; - } - - if(rfalIsGTExpired()) /* Wait until Guard Time is fulfilled */ - { - err = rfalNfcaPollerTechnologyDetection( - gNfcDev.disc.compMode, &sensRes); /* Poll for NFC-A devices */ - if(err == ERR_NONE) { - gNfcDev.techsFound |= RFAL_NFC_POLL_TECH_A; - } - - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_A; - } - - return ERR_BUSY; - -#endif /* RFAL_FEATURE_NFCA */ - } - - /*******************************************************************************/ - /* Passive NFC-B Technology Detection */ - /*******************************************************************************/ - if(((gNfcDev.disc.techs2Find & RFAL_NFC_POLL_TECH_B) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_B) != 0U)) { -#if RFAL_FEATURE_NFCB - - rfalNfcbSensbRes sensbRes; - uint8_t sensbResLen; - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR(err, rfalNfcbPollerInitialize()); /* Initialize RFAL for NFC-B */ - EXIT_ON_ERR( - err, rfalFieldOnAndStartGT()); /* As field is already On only starts GT timer */ - gNfcDev.isTechInit = true; - } - - if(rfalIsGTExpired()) /* Wait until Guard Time is fulfilled */ - { - err = rfalNfcbPollerTechnologyDetection( - gNfcDev.disc.compMode, &sensbRes, &sensbResLen); /* Poll for NFC-B devices */ - if(err == ERR_NONE) { - gNfcDev.techsFound |= RFAL_NFC_POLL_TECH_B; - } - - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_B; - } - - return ERR_BUSY; - -#endif /* RFAL_FEATURE_NFCB */ - } - - /*******************************************************************************/ - /* Passive NFC-F Technology Detection */ - /*******************************************************************************/ - if(((gNfcDev.disc.techs2Find & RFAL_NFC_POLL_TECH_F) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_F) != 0U)) { -#if RFAL_FEATURE_NFCF - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR( - err, - rfalNfcfPollerInitialize(gNfcDev.disc.nfcfBR)); /* Initialize RFAL for NFC-F */ - EXIT_ON_ERR( - err, rfalFieldOnAndStartGT()); /* As field is already On only starts GT timer */ - gNfcDev.isTechInit = true; - } - - if(rfalIsGTExpired()) /* Wait until Guard Time is fulfilled */ - { - err = rfalNfcfPollerCheckPresence(); /* Poll for NFC-F devices */ - if(err == ERR_NONE) { - gNfcDev.techsFound |= RFAL_NFC_POLL_TECH_F; - } - - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_F; - } - - return ERR_BUSY; - -#endif /* RFAL_FEATURE_NFCF */ - } - - /*******************************************************************************/ - /* Passive NFC-V Technology Detection */ - /*******************************************************************************/ - if(((gNfcDev.disc.techs2Find & RFAL_NFC_POLL_TECH_V) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_V) != 0U)) { -#if RFAL_FEATURE_NFCV - - rfalNfcvInventoryRes invRes; - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR(err, rfalNfcvPollerInitialize()); /* Initialize RFAL for NFC-V */ - EXIT_ON_ERR( - err, rfalFieldOnAndStartGT()); /* As field is already On only starts GT timer */ - gNfcDev.isTechInit = true; - } - - if(rfalIsGTExpired()) /* Wait until Guard Time is fulfilled */ - { - err = rfalNfcvPollerCheckPresence(&invRes); /* Poll for NFC-V devices */ - if(err == ERR_NONE) { - gNfcDev.techsFound |= RFAL_NFC_POLL_TECH_V; - } - - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_V; - } - - return ERR_BUSY; - -#endif /* RFAL_FEATURE_NFCV */ - } - - /*******************************************************************************/ - /* Passive Proprietary Technology ST25TB */ - /*******************************************************************************/ - if(((gNfcDev.disc.techs2Find & RFAL_NFC_POLL_TECH_ST25TB) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_ST25TB) != 0U)) { -#if RFAL_FEATURE_ST25TB - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR(err, rfalSt25tbPollerInitialize()); /* Initialize RFAL for NFC-V */ - EXIT_ON_ERR( - err, rfalFieldOnAndStartGT()); /* As field is already On only starts GT timer */ - gNfcDev.isTechInit = true; - } - - if(rfalIsGTExpired()) /* Wait until Guard Time is fulfilled */ - { - err = rfalSt25tbPollerCheckPresence(NULL); /* Poll for ST25TB devices */ - if(err == ERR_NONE) { - gNfcDev.techsFound |= RFAL_NFC_POLL_TECH_ST25TB; - } - - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_ST25TB; - } - - return ERR_BUSY; - -#endif /* RFAL_FEATURE_ST25TB */ - } - - return ERR_NONE; -} - -/*! - ****************************************************************************** - * \brief Poller Collision Resolution - * - * This method implements the Collision Resolution on all technologies that - * have been detected before. - * - * \return ERR_NONE : Operation completed with no error - * \return ERR_BUSY : Operation ongoing - * \return ERR_XXXX : Error occurred - * - ****************************************************************************** - */ -static ReturnCode rfalNfcPollCollResolution(void) { - uint8_t i; - static uint8_t devCnt; - ReturnCode err; - - err = ERR_NONE; - i = 0; - - /* Suppress warning when specific RFAL features have been disabled */ - NO_WARNING(err); - NO_WARNING(devCnt); - NO_WARNING(i); - - /* Check if device limit has been reached */ - if(gNfcDev.devCnt >= gNfcDev.disc.devLimit) { - return ERR_NONE; - } - - /*******************************************************************************/ - /* NFC-A Collision Resolution */ - /*******************************************************************************/ -#if RFAL_FEATURE_NFCA - if(((gNfcDev.techsFound & RFAL_NFC_POLL_TECH_A) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_A) != - 0U)) /* If a NFC-A device was found/detected, perform Collision Resolution */ - { - static rfalNfcaListenDevice nfcaDevList[RFAL_NFC_MAX_DEVICES]; - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR(err, rfalNfcaPollerInitialize()); /* Initialize RFAL for NFC-A */ - EXIT_ON_ERR(err, rfalFieldOnAndStartGT()); /* Turns the Field On and starts GT timer */ - - gNfcDev.isTechInit = true; /* Technology has been initialized */ - gNfcDev.isOperOngoing = false; /* No operation currently ongoing */ - } - - if(!rfalIsGTExpired()) { - return ERR_BUSY; - } - - if(!gNfcDev.isOperOngoing) { - EXIT_ON_ERR( - err, - rfalNfcaPollerStartFullCollisionResolution( - gNfcDev.disc.compMode, - (gNfcDev.disc.devLimit - gNfcDev.devCnt), - nfcaDevList, - &devCnt)); - - gNfcDev.isOperOngoing = true; - return ERR_BUSY; - } - - err = rfalNfcaPollerGetFullCollisionResolutionStatus(); - if(err != ERR_BUSY) { - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_A; - - if((err == ERR_NONE) && (devCnt != 0U)) { - for(i = 0; i < devCnt; - i++) /* Copy devices found form local Nfca list into global device list */ - { - gNfcDev.devList[gNfcDev.devCnt].type = RFAL_NFC_LISTEN_TYPE_NFCA; - gNfcDev.devList[gNfcDev.devCnt].dev.nfca = nfcaDevList[i]; - gNfcDev.devCnt++; - } - } - } - - return ERR_BUSY; - } -#endif /* RFAL_FEATURE_NFCA */ - - /*******************************************************************************/ - /* NFC-B Collision Resolution */ - /*******************************************************************************/ -#if RFAL_FEATURE_NFCB - if(((gNfcDev.techsFound & RFAL_NFC_POLL_TECH_B) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_B) != - 0U)) /* If a NFC-B device was found/detected, perform Collision Resolution */ - { - rfalNfcbListenDevice nfcbDevList[RFAL_NFC_MAX_DEVICES]; - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR(err, rfalNfcbPollerInitialize()); /* Initialize RFAL for NFC-B */ - EXIT_ON_ERR( - err, - rfalFieldOnAndStartGT()); /* Ensure GT again as other technologies have also been polled */ - gNfcDev.isTechInit = true; - } - - if(!rfalIsGTExpired()) { - return ERR_BUSY; - } - - devCnt = 0; - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_B; - - err = rfalNfcbPollerCollisionResolution( - gNfcDev.disc.compMode, (gNfcDev.disc.devLimit - gNfcDev.devCnt), nfcbDevList, &devCnt); - if((err == ERR_NONE) && (devCnt != 0U)) { - for(i = 0; i < devCnt; - i++) /* Copy devices found form local Nfcb list into global device list */ - { - gNfcDev.devList[gNfcDev.devCnt].type = RFAL_NFC_LISTEN_TYPE_NFCB; - gNfcDev.devList[gNfcDev.devCnt].dev.nfcb = nfcbDevList[i]; - gNfcDev.devCnt++; - } - } - - return ERR_BUSY; - } -#endif /* RFAL_FEATURE_NFCB*/ - - /*******************************************************************************/ - /* NFC-F Collision Resolution */ - /*******************************************************************************/ -#if RFAL_FEATURE_NFCF - if(((gNfcDev.techsFound & RFAL_NFC_POLL_TECH_F) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_F) != - 0U)) /* If a NFC-F device was found/detected, perform Collision Resolution */ - { - rfalNfcfListenDevice nfcfDevList[RFAL_NFC_MAX_DEVICES]; - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR( - err, - rfalNfcfPollerInitialize(gNfcDev.disc.nfcfBR)); /* Initialize RFAL for NFC-F */ - EXIT_ON_ERR( - err, - rfalFieldOnAndStartGT()); /* Ensure GT again as other technologies have also been polled */ - gNfcDev.isTechInit = true; - } - - if(!rfalIsGTExpired()) { - return ERR_BUSY; - } - - devCnt = 0; - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_F; - - err = rfalNfcfPollerCollisionResolution( - gNfcDev.disc.compMode, (gNfcDev.disc.devLimit - gNfcDev.devCnt), nfcfDevList, &devCnt); - if((err == ERR_NONE) && (devCnt != 0U)) { - for(i = 0; i < devCnt; - i++) /* Copy devices found form local Nfcf list into global device list */ - { - gNfcDev.devList[gNfcDev.devCnt].type = RFAL_NFC_LISTEN_TYPE_NFCF; - gNfcDev.devList[gNfcDev.devCnt].dev.nfcf = nfcfDevList[i]; - gNfcDev.devCnt++; - } - } - - return ERR_BUSY; - } -#endif /* RFAL_FEATURE_NFCF */ - - /*******************************************************************************/ - /* NFC-V Collision Resolution */ - /*******************************************************************************/ -#if RFAL_FEATURE_NFCV - if(((gNfcDev.techsFound & RFAL_NFC_POLL_TECH_V) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_V) != - 0U)) /* If a NFC-V device was found/detected, perform Collision Resolution */ - { - rfalNfcvListenDevice nfcvDevList[RFAL_NFC_MAX_DEVICES]; - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR(err, rfalNfcvPollerInitialize()); /* Initialize RFAL for NFC-V */ - EXIT_ON_ERR( - err, - rfalFieldOnAndStartGT()); /* Ensure GT again as other technologies have also been polled */ - gNfcDev.isTechInit = true; - } - - if(!rfalIsGTExpired()) { - return ERR_BUSY; - } - - devCnt = 0; - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_V; - - err = rfalNfcvPollerCollisionResolution( - RFAL_COMPLIANCE_MODE_NFC, - (gNfcDev.disc.devLimit - gNfcDev.devCnt), - nfcvDevList, - &devCnt); - if((err == ERR_NONE) && (devCnt != 0U)) { - for(i = 0; i < devCnt; - i++) /* Copy devices found form local Nfcf list into global device list */ - { - gNfcDev.devList[gNfcDev.devCnt].type = RFAL_NFC_LISTEN_TYPE_NFCV; - gNfcDev.devList[gNfcDev.devCnt].dev.nfcv = nfcvDevList[i]; - gNfcDev.devCnt++; - } - } - - return ERR_BUSY; - } -#endif /* RFAL_FEATURE_NFCV */ - - /*******************************************************************************/ - /* ST25TB Collision Resolution */ - /*******************************************************************************/ -#if RFAL_FEATURE_ST25TB - if(((gNfcDev.techsFound & RFAL_NFC_POLL_TECH_ST25TB) != 0U) && - ((gNfcDev.techs2do & RFAL_NFC_POLL_TECH_ST25TB) != - 0U)) /* If a ST25TB device was found/detected, perform Collision Resolution */ - { - rfalSt25tbListenDevice st25tbDevList[RFAL_NFC_MAX_DEVICES]; - - if(!gNfcDev.isTechInit) { - EXIT_ON_ERR(err, rfalSt25tbPollerInitialize()); /* Initialize RFAL for ST25TB */ - EXIT_ON_ERR( - err, - rfalFieldOnAndStartGT()); /* Ensure GT again as other technologies have also been polled */ - gNfcDev.isTechInit = true; - } - - if(!rfalIsGTExpired()) { - return ERR_BUSY; - } - - devCnt = 0; - gNfcDev.isTechInit = false; - gNfcDev.techs2do &= ~RFAL_NFC_POLL_TECH_ST25TB; - - err = rfalSt25tbPollerCollisionResolution( - (gNfcDev.disc.devLimit - gNfcDev.devCnt), st25tbDevList, &devCnt); - if((err == ERR_NONE) && (devCnt != 0U)) { - for(i = 0; i < devCnt; - i++) /* Copy devices found form local Nfcf list into global device list */ - { - gNfcDev.devList[gNfcDev.devCnt].type = RFAL_NFC_LISTEN_TYPE_ST25TB; - gNfcDev.devList[gNfcDev.devCnt].dev.st25tb = st25tbDevList[i]; - gNfcDev.devCnt++; - } - } - - return ERR_BUSY; - } -#endif /* RFAL_FEATURE_ST25TB */ - - return ERR_NONE; /* All technologies have been performed */ -} - -/*! - ****************************************************************************** - * \brief Poller Activation - * - * This method Activates a given device according to it's type and - * protocols supported - * - * \param[in] devIt : device's position on the list to be activated - * - * \return ERR_NONE : Operation completed with no error - * \return ERR_BUSY : Operation ongoing - * \return ERR_XXXX : Error occurred - * - ****************************************************************************** - */ -static ReturnCode rfalNfcPollActivation(uint8_t devIt) { - ReturnCode err; - - err = ERR_NONE; - - /* Suppress warning when specific RFAL features have been disabled */ - NO_WARNING(err); - - if(devIt > gNfcDev.devCnt) { - return ERR_WRONG_STATE; - } - - switch(gNfcDev.devList[devIt].type) { - /*******************************************************************************/ - /* AP2P Activation */ - /*******************************************************************************/ -#if RFAL_FEATURE_NFC_DEP - case RFAL_NFC_LISTEN_TYPE_AP2P: - /* Activation has already been performed (ATR_REQ) */ - - gNfcDev.devList[devIt].nfcid = - gNfcDev.devList[devIt].proto.nfcDep.activation.Target.ATR_RES.NFCID3; - gNfcDev.devList[devIt].nfcidLen = RFAL_NFCDEP_NFCID3_LEN; - break; -#endif /* RFAL_FEATURE_NFC_DEP */ - - /*******************************************************************************/ - /* Passive NFC-A Activation */ - /*******************************************************************************/ -#if RFAL_FEATURE_NFCA - case RFAL_NFC_LISTEN_TYPE_NFCA: - - if(!gNfcDev.isTechInit) { - rfalNfcaPollerInitialize(); - gNfcDev.isTechInit = true; - gNfcDev.isOperOngoing = false; - return ERR_BUSY; - } - - if(gNfcDev.devList[devIt].dev.nfca.isSleep) /* Check if desired device is in Sleep */ - { - rfalNfcaSensRes sensRes; - rfalNfcaSelRes selRes; - - if(!gNfcDev.isOperOngoing) { - /* Wake up all cards */ - EXIT_ON_ERR( - err, rfalNfcaPollerCheckPresence(RFAL_14443A_SHORTFRAME_CMD_WUPA, &sensRes)); - gNfcDev.isOperOngoing = true; - } else { - /* Select specific device */ - EXIT_ON_ERR( - err, - rfalNfcaPollerSelect( - gNfcDev.devList[devIt].dev.nfca.nfcId1, - gNfcDev.devList[devIt].dev.nfca.nfcId1Len, - &selRes)); - gNfcDev.devList[devIt].dev.nfca.isSleep = false; - gNfcDev.isOperOngoing = false; - } - return ERR_BUSY; - } - - /* Set NFCID */ - gNfcDev.devList[devIt].nfcid = gNfcDev.devList[devIt].dev.nfca.nfcId1; - gNfcDev.devList[devIt].nfcidLen = gNfcDev.devList[devIt].dev.nfca.nfcId1Len; - - /*******************************************************************************/ - /* Perform protocol specific activation */ - switch(gNfcDev.devList[devIt].dev.nfca.type) { - /*******************************************************************************/ - case RFAL_NFCA_T1T: - - /* No further activation needed for T1T (RID already performed) */ - - gNfcDev.devList[devIt].nfcid = gNfcDev.devList[devIt].dev.nfca.ridRes.uid; - gNfcDev.devList[devIt].nfcidLen = RFAL_T1T_UID_LEN; - - gNfcDev.devList[devIt].rfInterface = RFAL_NFC_INTERFACE_RF; - break; - - case RFAL_NFCA_T2T: - - /* No further activation needed for a T2T */ - - gNfcDev.devList[devIt].rfInterface = RFAL_NFC_INTERFACE_RF; - break; - - /*******************************************************************************/ - case RFAL_NFCA_T4T: /* Device supports ISO-DEP */ - -#if RFAL_FEATURE_ISO_DEP && RFAL_FEATURE_ISO_DEP_POLL - if(!gNfcDev.isOperOngoing) { - /* Perform ISO-DEP (ISO14443-4) activation: RATS and PPS if supported */ - rfalIsoDepInitialize(); - EXIT_ON_ERR( - err, - rfalIsoDepPollAStartActivation( - (rfalIsoDepFSxI)RFAL_ISODEP_FSDI_DEFAULT, - RFAL_ISODEP_NO_DID, - gNfcDev.disc.maxBR, - &gNfcDev.devList[devIt].proto.isoDep)); - - gNfcDev.isOperOngoing = true; - return ERR_BUSY; - } - - err = rfalIsoDepPollAGetActivationStatus(); - if(err != ERR_NONE) { - return err; - } - - gNfcDev.devList[devIt].rfInterface = - RFAL_NFC_INTERFACE_ISODEP; /* NFC-A T4T device activated */ -#else - gNfcDev.devList[devIt].rfInterface = - RFAL_NFC_INTERFACE_RF; /* No ISO-DEP supported activate using RF interface */ -#endif /* RFAL_FEATURE_ISO_DEP_POLL */ - break; - - /*******************************************************************************/ - case RFAL_NFCA_T4T_NFCDEP: /* Device supports both T4T and NFC-DEP */ - case RFAL_NFCA_NFCDEP: /* Device supports NFC-DEP */ - -#if RFAL_FEATURE_NFC_DEP - /* Perform NFC-DEP (P2P) activation: ATR and PSL if supported */ - EXIT_ON_ERR( - err, - rfalNfcNfcDepActivate(&gNfcDev.devList[devIt], RFAL_NFCDEP_COMM_PASSIVE, NULL, 0)); - - gNfcDev.devList[devIt].nfcid = - gNfcDev.devList[devIt].proto.nfcDep.activation.Target.ATR_RES.NFCID3; - gNfcDev.devList[devIt].nfcidLen = RFAL_NFCDEP_NFCID3_LEN; - - gNfcDev.devList[devIt].rfInterface = - RFAL_NFC_INTERFACE_NFCDEP; /* NFC-A P2P device activated */ -#else - gNfcDev.devList[devIt].rfInterface = - RFAL_NFC_INTERFACE_RF; /* No NFC-DEP supported activate using RF interface */ -#endif /* RFAL_FEATURE_NFC_DEP */ - break; - - /*******************************************************************************/ - default: - return ERR_WRONG_STATE; - } - break; -#endif /* RFAL_FEATURE_NFCA */ - - /*******************************************************************************/ - /* Passive NFC-B Activation */ - /*******************************************************************************/ -#if RFAL_FEATURE_NFCB - case RFAL_NFC_LISTEN_TYPE_NFCB: - - if(!gNfcDev.isTechInit) { - rfalNfcbPollerInitialize(); - gNfcDev.isTechInit = true; - gNfcDev.isOperOngoing = false; - return ERR_BUSY; - } - - if(gNfcDev.devList[devIt].dev.nfcb.isSleep) /* Check if desired device is in Sleep */ - { - rfalNfcbSensbRes sensbRes; - uint8_t sensbResLen; - - /* Wake up all cards. SENSB_RES may return collision but the NFCID0 is available to explicitly select NFC-B card via ATTRIB; so error will be ignored here */ - rfalNfcbPollerCheckPresence( - RFAL_NFCB_SENS_CMD_ALLB_REQ, RFAL_NFCB_SLOT_NUM_1, &sensbRes, &sensbResLen); - } - - /* Set NFCID */ - gNfcDev.devList[devIt].nfcid = gNfcDev.devList[devIt].dev.nfcb.sensbRes.nfcid0; - gNfcDev.devList[devIt].nfcidLen = RFAL_NFCB_NFCID0_LEN; - -#if RFAL_FEATURE_ISO_DEP && RFAL_FEATURE_ISO_DEP_POLL - /* Check if device supports ISO-DEP (ISO14443-4) */ - if((gNfcDev.devList[devIt].dev.nfcb.sensbRes.protInfo.FsciProType & - RFAL_NFCB_SENSB_RES_PROTO_ISO_MASK) != 0U) { - if(!gNfcDev.isOperOngoing) { - rfalIsoDepInitialize(); - /* Perform ISO-DEP (ISO14443-4) activation: ATTRIB */ - EXIT_ON_ERR( - err, - rfalIsoDepPollBStartActivation( - (rfalIsoDepFSxI)RFAL_ISODEP_FSDI_DEFAULT, - RFAL_ISODEP_NO_DID, - gNfcDev.disc.maxBR, - 0x00, - &gNfcDev.devList[devIt].dev.nfcb, - NULL, - 0, - &gNfcDev.devList[devIt].proto.isoDep)); - - gNfcDev.isOperOngoing = true; - return ERR_BUSY; - } - - err = rfalIsoDepPollBGetActivationStatus(); - if(err != ERR_NONE) { - return err; - } - - gNfcDev.devList[devIt].rfInterface = - RFAL_NFC_INTERFACE_ISODEP; /* NFC-B T4T device activated */ - break; - } - -#endif /* RFAL_FEATURE_ISO_DEP_POLL */ - - gNfcDev.devList[devIt].rfInterface = - RFAL_NFC_INTERFACE_RF; /* NFC-B device activated */ - break; - -#endif /* RFAL_FEATURE_NFCB */ - - /*******************************************************************************/ - /* Passive NFC-F Activation */ - /*******************************************************************************/ -#if RFAL_FEATURE_NFCF - case RFAL_NFC_LISTEN_TYPE_NFCF: - - rfalNfcfPollerInitialize(gNfcDev.disc.nfcfBR); - -#if RFAL_FEATURE_NFC_DEP - if(rfalNfcfIsNfcDepSupported(&gNfcDev.devList[devIt].dev.nfcf)) { - /* Perform NFC-DEP (P2P) activation: ATR and PSL if supported */ - EXIT_ON_ERR( - err, - rfalNfcNfcDepActivate(&gNfcDev.devList[devIt], RFAL_NFCDEP_COMM_PASSIVE, NULL, 0)); - - /* Set NFCID */ - gNfcDev.devList[devIt].nfcid = - gNfcDev.devList[devIt].proto.nfcDep.activation.Target.ATR_RES.NFCID3; - gNfcDev.devList[devIt].nfcidLen = RFAL_NFCDEP_NFCID3_LEN; - - gNfcDev.devList[devIt].rfInterface = - RFAL_NFC_INTERFACE_NFCDEP; /* NFC-F P2P device activated */ - break; - } -#endif /* RFAL_FEATURE_NFC_DEP */ - - /* Set NFCID */ - gNfcDev.devList[devIt].nfcid = gNfcDev.devList[devIt].dev.nfcf.sensfRes.NFCID2; - gNfcDev.devList[devIt].nfcidLen = RFAL_NFCF_NFCID2_LEN; - - gNfcDev.devList[devIt].rfInterface = - RFAL_NFC_INTERFACE_RF; /* NFC-F T3T device activated */ - break; -#endif /* RFAL_FEATURE_NFCF */ - - /*******************************************************************************/ - /* Passive NFC-V Activation */ - /*******************************************************************************/ -#if RFAL_FEATURE_NFCV - case RFAL_NFC_LISTEN_TYPE_NFCV: - - rfalNfcvPollerInitialize(); - - /* No specific activation needed for a T5T */ - - /* Set NFCID */ - gNfcDev.devList[devIt].nfcid = gNfcDev.devList[devIt].dev.nfcv.InvRes.UID; - gNfcDev.devList[devIt].nfcidLen = RFAL_NFCV_UID_LEN; - - gNfcDev.devList[devIt].rfInterface = - RFAL_NFC_INTERFACE_RF; /* NFC-V T5T device activated */ - break; -#endif /* RFAL_FEATURE_NFCV */ - - /*******************************************************************************/ - /* Passive ST25TB Activation */ - /*******************************************************************************/ -#if RFAL_FEATURE_ST25TB - case RFAL_NFC_LISTEN_TYPE_ST25TB: - - rfalSt25tbPollerInitialize(); - - /* No specific activation needed for a ST25TB */ - - /* Set NFCID */ - gNfcDev.devList[devIt].nfcid = gNfcDev.devList[devIt].dev.st25tb.UID; - gNfcDev.devList[devIt].nfcidLen = RFAL_ST25TB_UID_LEN; - - gNfcDev.devList[devIt].rfInterface = RFAL_NFC_INTERFACE_RF; /* ST25TB device activated */ - break; -#endif /* RFAL_FEATURE_ST25TB */ - - /*******************************************************************************/ - default: - return ERR_WRONG_STATE; - } - - gNfcDev.activeDev = &gNfcDev.devList[devIt]; /* Assign active device to be used further on */ - return ERR_NONE; -} - -/*! - ****************************************************************************** - * \brief Listener Activation - * - * This method handles the listen mode Activation according to the different - * protocols the Reader/Initiator performs - * - * \return ERR_NONE : Operation completed with no error - * \return ERR_BUSY : Operation ongoing - * \return ERR_PROTO : Unexpected frame received - * \return ERR_XXXX : Error occurred - * - ****************************************************************************** - */ -#if RFAL_FEATURE_LISTEN_MODE -static ReturnCode rfalNfcListenActivation(void) { - bool isDataRcvd; - ReturnCode ret; - rfalLmState lmSt; - rfalBitRate bitRate; -#if RFAL_FEATURE_NFC_DEP - uint8_t hdrLen; - - /* Set the header length in NFC-A */ - hdrLen = (RFAL_NFCDEP_SB_LEN + RFAL_NFCDEP_LEN_LEN); -#endif /* RFAL_FEATURE_NFC_DEP */ - - lmSt = rfalListenGetState(&isDataRcvd, &bitRate); - - switch(lmSt) { -#if RFAL_FEATURE_NFCA - /*******************************************************************************/ - case RFAL_LM_STATE_ACTIVE_A: /* NFC-A CE activation */ - case RFAL_LM_STATE_ACTIVE_Ax: - - if(isDataRcvd) /* Check if Reader/Initator has sent some data */ - { - /* Check if received data is a Sleep request */ - if(rfalNfcaListenerIsSleepReq( - gNfcDev.rxBuf.rfBuf, - rfalConvBitsToBytes(gNfcDev.rxLen))) /* Check if received data is a SLP_REQ */ - { - /* Set the Listen Mode in Sleep state */ - EXIT_ON_ERR( - ret, - rfalListenSleepStart( - RFAL_LM_STATE_SLEEP_A, - gNfcDev.rxBuf.rfBuf, - sizeof(gNfcDev.rxBuf.rfBuf), - &gNfcDev.rxLen)); - } - - else if(gNfcDev.disc.activate_after_sak) { - gNfcDev.devList->type = RFAL_NFC_POLL_TYPE_NFCA; - rfalListenSetState(RFAL_LM_STATE_ACTIVE_A); - return ERR_NONE; - } -#if RFAL_FEATURE_ISO_DEP && RFAL_FEATURE_ISO_DEP_LISTEN - /* Check if received data is a valid RATS */ - else if(rfalIsoDepIsRats( - gNfcDev.rxBuf.rfBuf, (uint8_t)rfalConvBitsToBytes(gNfcDev.rxLen))) { - rfalIsoDepAtsParam atsParam; - rfalIsoDepListenActvParam rxParam; - - /* Set ATS parameters */ - atsParam.fsci = (uint8_t)RFAL_ISODEP_DEFAULT_FSCI; - atsParam.fwi = RFAL_ISODEP_DEFAULT_FWI; - atsParam.sfgi = RFAL_ISODEP_DEFAULT_SFGI; - atsParam.didSupport = false; - atsParam.ta = RFAL_ISODEP_ATS_TA_SAME_D; - atsParam.hb = NULL; - atsParam.hbLen = 0; - - /* Set Rx parameters */ - rxParam.rxBuf = - (rfalIsoDepBufFormat*)&gNfcDev.rxBuf - .isoDepBuf; /* PRQA S 0310 # MISRA 11.3 - Intentional safe cast to avoiding large buffer duplication */ - rxParam.rxLen = &gNfcDev.rxLen; - rxParam.isoDepDev = &gNfcDev.devList->proto.isoDep; - rxParam.isRxChaining = &gNfcDev.isRxChaining; - - rfalListenSetState(RFAL_LM_STATE_CARDEMU_4A); /* Set next state CE T4T */ - rfalIsoDepInitialize(); /* Initialize ISO-DEP layer to handle ISO14443-a activation / RATS */ - - /* Set ISO-DEP layer to digest RATS and handle activation */ - EXIT_ON_ERR( - ret, - rfalIsoDepListenStartActivation( - &atsParam, NULL, gNfcDev.rxBuf.rfBuf, gNfcDev.rxLen, rxParam)); - } -#endif /* RFAL_FEATURE_ISO_DEP_LISTEN */ - -#if RFAL_FEATURE_NFC_DEP - - /* Check if received data is a valid ATR_REQ */ - else if(rfalNfcDepIsAtrReq( - &gNfcDev.rxBuf.rfBuf[hdrLen], - (rfalConvBitsToBytes(gNfcDev.rxLen) - hdrLen), - gNfcDev.devList->nfcid)) { - gNfcDev.devList->type = RFAL_NFC_POLL_TYPE_NFCA; - EXIT_ON_ERR( - ret, - rfalNfcNfcDepActivate( - gNfcDev.devList, - RFAL_NFCDEP_COMM_PASSIVE, - &gNfcDev.rxBuf.rfBuf[hdrLen], - (rfalConvBitsToBytes(gNfcDev.rxLen) - hdrLen))); - } -#endif /* RFAL_FEATURE_NFC_DEP */ - - else { - return ERR_PROTO; - } - } - return ERR_BUSY; - -#endif /* RFAL_FEATURE_NFCA */ - -#if RFAL_FEATURE_ISO_DEP && RFAL_FEATURE_ISO_DEP_LISTEN - /*******************************************************************************/ - case RFAL_LM_STATE_CARDEMU_4A: /* T4T ISO-DEP activation */ - - ret = rfalIsoDepListenGetActivationStatus(); - if(ret == ERR_NONE) { - gNfcDev.devList->type = RFAL_NFC_POLL_TYPE_NFCA; - gNfcDev.devList->rfInterface = RFAL_NFC_INTERFACE_ISODEP; - gNfcDev.devList->nfcid = NULL; - gNfcDev.devList->nfcidLen = 0; - } - return ret; -#endif /* RFAL_FEATURE_ISO_DEP_LISTEN */ - - /*******************************************************************************/ - case RFAL_LM_STATE_READY_F: /* NFC-F CE activation */ - - if(isDataRcvd) /* Wait for the first received data */ - { -#if RFAL_FEATURE_NFC_DEP - /* Set the header length in NFC-F */ - hdrLen = RFAL_NFCDEP_LEN_LEN; - - if(rfalNfcDepIsAtrReq( - &gNfcDev.rxBuf.rfBuf[hdrLen], - (rfalConvBitsToBytes(gNfcDev.rxLen) - hdrLen), - gNfcDev.devList->nfcid)) { - gNfcDev.devList->type = RFAL_NFC_POLL_TYPE_NFCF; - EXIT_ON_ERR( - ret, - rfalNfcNfcDepActivate( - gNfcDev.devList, - RFAL_NFCDEP_COMM_PASSIVE, - &gNfcDev.rxBuf.rfBuf[hdrLen], - (rfalConvBitsToBytes(gNfcDev.rxLen) - hdrLen))); - } else -#endif /* RFAL_FEATURE_NFC_DEP */ - { - rfalListenSetState( - RFAL_LM_STATE_CARDEMU_3); /* First data already received - set T3T CE */ - } - } - return ERR_BUSY; - - /*******************************************************************************/ - case RFAL_LM_STATE_CARDEMU_3: /* T3T activated */ - - gNfcDev.devList->type = RFAL_NFC_POLL_TYPE_NFCF; - gNfcDev.devList->rfInterface = RFAL_NFC_INTERFACE_RF; - gNfcDev.devList->nfcid = NULL; - gNfcDev.devList->nfcidLen = 0; - - return ERR_NONE; - -#if RFAL_FEATURE_NFC_DEP - /*******************************************************************************/ - case RFAL_LM_STATE_TARGET_A: /* NFC-DEP activation */ - case RFAL_LM_STATE_TARGET_F: - - ret = rfalNfcDepListenGetActivationStatus(); - if(ret == ERR_NONE) { - gNfcDev.devList->rfInterface = RFAL_NFC_INTERFACE_NFCDEP; - gNfcDev.devList->nfcidLen = RFAL_NFCDEP_NFCID3_LEN; - } - return ret; -#endif /* RFAL_FEATURE_NFC_DEP */ - - /*******************************************************************************/ - case RFAL_LM_STATE_IDLE: /* AP2P activation */ - if(isDataRcvd) /* Check if Reader/Initator has sent some data */ - { - if((gNfcDev.lmMask & RFAL_LM_MASK_ACTIVE_P2P) != 0U) /* Check if AP2P is enabled */ - { -#if RFAL_FEATURE_NFC_DEP - /* Calculate the header length in NFC-A or NFC-F mode*/ - hdrLen = - ((bitRate == RFAL_BR_106) ? (RFAL_NFCDEP_SB_LEN + RFAL_NFCDEP_LEN_LEN) : - RFAL_NFCDEP_LEN_LEN); - - if(rfalNfcDepIsAtrReq( - &gNfcDev.rxBuf.rfBuf[hdrLen], - (rfalConvBitsToBytes(gNfcDev.rxLen) - hdrLen), - NULL)) { - gNfcDev.devList->type = RFAL_NFC_POLL_TYPE_AP2P; - rfalSetMode((RFAL_MODE_LISTEN_ACTIVE_P2P), bitRate, bitRate); - EXIT_ON_ERR( - ret, - rfalNfcNfcDepActivate( - gNfcDev.devList, - RFAL_NFCDEP_COMM_ACTIVE, - &gNfcDev.rxBuf.rfBuf[hdrLen], - (rfalConvBitsToBytes(gNfcDev.rxLen) - hdrLen))); - } else -#endif /* RFAL_FEATURE_NFC_DEP */ - { - return ERR_PROTO; - } - } - } - return ERR_BUSY; - - /*******************************************************************************/ - case RFAL_LM_STATE_READY_A: - case RFAL_LM_STATE_READY_Ax: - case RFAL_LM_STATE_SLEEP_A: - case RFAL_LM_STATE_SLEEP_AF: - return ERR_BUSY; - - /*******************************************************************************/ - case RFAL_LM_STATE_POWER_OFF: - return ERR_LINK_LOSS; - - default: /* Wait for activation */ - break; - } - - return ERR_INTERNAL; -} -#endif /* RFAL_FEATURE_LISTEN_MODE */ - -/*! - ****************************************************************************** - * \brief Poller NFC DEP Activate - * - * This method performs NFC-DEP Activation - * - * \param[in] device : device info - * \param[in] commMode : communication mode (Passive/Active) - * \param[in] atrReq : received ATR_REQ - * \param[in] atrReqLen : received ATR_REQ size - * - * \return ERR_NONE : Operation completed with no error - * \return ERR_BUSY : Operation ongoing - * \return ERR_XXXX : Error occurred - * - ****************************************************************************** - */ -#if RFAL_FEATURE_NFC_DEP -static ReturnCode rfalNfcNfcDepActivate( - rfalNfcDevice* device, - rfalNfcDepCommMode commMode, - const uint8_t* atrReq, - uint16_t atrReqLen) { - rfalNfcDepAtrParam initParam; - - /* Suppress warnings if Listen mode is disabled */ - NO_WARNING(atrReq); - NO_WARNING(atrReqLen); - - /* If we are in Poll mode */ - if(rfalNfcIsRemDevListener(device->type)) { - /*******************************************************************************/ - /* If Passive F use the NFCID2 retrieved from SENSF */ - if(device->type == RFAL_NFC_LISTEN_TYPE_NFCF) { - initParam.nfcid = device->dev.nfcf.sensfRes.NFCID2; - initParam.nfcidLen = RFAL_NFCF_NFCID2_LEN; - } else { - initParam.nfcid = gNfcDev.disc.nfcid3; - initParam.nfcidLen = RFAL_NFCDEP_NFCID3_LEN; - } - - initParam.BS = RFAL_NFCDEP_Bx_NO_HIGH_BR; - initParam.BR = RFAL_NFCDEP_Bx_NO_HIGH_BR; - initParam.DID = RFAL_NFCDEP_DID_NO; - initParam.NAD = RFAL_NFCDEP_NAD_NO; - initParam.LR = RFAL_NFCDEP_LR_254; - initParam.GB = gNfcDev.disc.GB; - initParam.GBLen = gNfcDev.disc.GBLen; - initParam.commMode = commMode; - initParam.operParam = - (RFAL_NFCDEP_OPER_FULL_MI_EN | RFAL_NFCDEP_OPER_EMPTY_DEP_DIS | - RFAL_NFCDEP_OPER_ATN_EN | RFAL_NFCDEP_OPER_RTOX_REQ_EN); - - rfalNfcDepInitialize(); - /* Perform NFC-DEP (P2P) activation: ATR and PSL if supported */ - return rfalNfcDepInitiatorHandleActivation( - &initParam, gNfcDev.disc.maxBR, &device->proto.nfcDep); - } - /* If we are in Listen mode */ -#if RFAL_FEATURE_LISTEN_MODE - else if(rfalNfcIsRemDevPoller(device->type)) { - rfalNfcDepListenActvParam actvParams; - rfalNfcDepTargetParam targetParam; - - ST_MEMCPY(targetParam.nfcid3, (uint8_t*)gNfcDev.disc.nfcid3, RFAL_NFCDEP_NFCID3_LEN); - targetParam.bst = RFAL_NFCDEP_Bx_NO_HIGH_BR; - targetParam.brt = RFAL_NFCDEP_Bx_NO_HIGH_BR; - targetParam.to = RFAL_NFCDEP_WT_TRG_MAX_L13; /* [LLCP] 1.3 6.2.1 */ - targetParam.ppt = rfalNfcDepLR2PP(RFAL_NFCDEP_LR_254); - if(gNfcDev.disc.GBLen >= RFAL_NFCDEP_GB_MAX_LEN) { - return ERR_PARAM; - } - targetParam.GBtLen = gNfcDev.disc.GBLen; - if(gNfcDev.disc.GBLen > 0U) { - ST_MEMCPY(targetParam.GBt, gNfcDev.disc.GB, gNfcDev.disc.GBLen); - } - targetParam.operParam = - (RFAL_NFCDEP_OPER_FULL_MI_EN | RFAL_NFCDEP_OPER_EMPTY_DEP_DIS | - RFAL_NFCDEP_OPER_ATN_EN | RFAL_NFCDEP_OPER_RTOX_REQ_EN); - targetParam.commMode = commMode; - - /* Set activation buffer (including header) for NFC-DEP */ - actvParams.rxBuf = - (rfalNfcDepBufFormat*)&gNfcDev.rxBuf - .nfcDepBuf; /* PRQA S 0310 # MISRA 11.3 - Intentional safe cast to avoiding large buffer duplication */ - actvParams.rxLen = &gNfcDev.rxLen; - actvParams.isRxChaining = &gNfcDev.isRxChaining; - actvParams.nfcDepDev = &gNfcDev.devList->proto.nfcDep; - - rfalListenSetState( - ((device->type == RFAL_NFC_POLL_TYPE_NFCA) ? RFAL_LM_STATE_TARGET_A : - RFAL_LM_STATE_TARGET_F)); - - rfalNfcDepInitialize(); - /* Perform NFC-DEP (P2P) activation: send ATR_RES and handle activation */ - return rfalNfcDepListenStartActivation(&targetParam, atrReq, atrReqLen, actvParams); - } -#endif /* RFAL_FEATURE_LISTEN_MODE */ - - else { - return ERR_INTERNAL; - } -} -#endif /* RFAL_FEATURE_NFC_DEP */ - -/*! - ****************************************************************************** - * \brief Poller NFC Deactivate - * - * This method Deactivates the device if a deactivation procedure exists - * - * \return ERR_NONE : Operation completed with no error - * \return ERR_BUSY : Operation ongoing - * \return ERR_XXXX : Error occurred - * - ****************************************************************************** - */ -static ReturnCode rfalNfcDeactivation(void) { - /* Check if a device has been activated */ - if(gNfcDev.activeDev != NULL) { - if(rfalNfcIsRemDevListener( - gNfcDev.activeDev->type)) /* Listen mode no additional deactivation to be performed*/ - { -#ifndef RFAL_NFC_SKIP_DEACT - switch(gNfcDev.activeDev->rfInterface) { - /*******************************************************************************/ - case RFAL_NFC_INTERFACE_RF: - break; /* No specific deactivation to be performed */ - - /*******************************************************************************/ -#if RFAL_FEATURE_ISO_DEP && RFAL_FEATURE_ISO_DEP_POLL - case RFAL_NFC_INTERFACE_ISODEP: - rfalIsoDepDeselect(); /* Send a Deselect to device */ - break; -#endif /* RFAL_FEATURE_ISO_DEP_POLL */ - - /*******************************************************************************/ -#if RFAL_FEATURE_NFC_DEP - case RFAL_NFC_INTERFACE_NFCDEP: - switch(gNfcDev.activeDev->type) { - case RFAL_NFC_LISTEN_TYPE_AP2P: - rfalNfcDepRLS(); /* Send a Release to device */ - break; - default: - rfalNfcDepDSL(); /* Send a Deselect to device */ - break; - } - break; -#endif /* RFAL_FEATURE_NFC_DEP */ - - default: - return ERR_REQUEST; - } -#endif /* RFAL_NFC_SKIP_DEACT */ - } - } - -#if RFAL_FEATURE_WAKEUP_MODE - rfalWakeUpModeStop(); -#endif /* RFAL_FEATURE_WAKEUP_MODE */ - -#if RFAL_FEATURE_LISTEN_MODE - rfalListenStop(); -#else - rfalFieldOff(); -#endif - - gNfcDev.activeDev = NULL; - return ERR_NONE; -} diff --git a/lib/ST25RFAL002/source/rfal_nfcDep.c b/lib/ST25RFAL002/source/rfal_nfcDep.c deleted file mode 100644 index ad851ac5d..000000000 --- a/lib/ST25RFAL002/source/rfal_nfcDep.c +++ /dev/null @@ -1,2730 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: NFCC firmware - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfcDep.c - * - * \author Gustavo Patricio - * - * \brief Implementation of NFC-DEP protocol - * - * NFC-DEP is also known as NFCIP - Near Field Communication - * Interface and Protocol - * - * This implementation was based on the following specs: - * - NFC Forum Digital 1.1 - * - ECMA 340 3rd Edition 2013 - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_nfcDep.h" -#include "rfal_nfcf.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#if RFAL_FEATURE_NFC_DEP - -/* Check for valid Block/Payload length Digital 2.0 Table 90*/ -#if((RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN != 64) && (RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN != 128) && \ - (RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN != 192) && (RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN != 254)) -#error \ - " RFAL: Invalid NFC-DEP Block Max length. Please change RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN. " -#endif - -/* Check for valid PDU length */ -#if((RFAL_FEATURE_NFC_DEP_PDU_MAX_LEN < RFAL_FEATURE_NFC_DEP_BLOCK_MAX_LEN)) -#error " RFAL: Invalid NFC-DEP PDU Max length. Please change RFAL_FEATURE_NFC_DEP_PDU_MAX_LEN. " -#endif - -/* - ****************************************************************************** - * DEFINES - ****************************************************************************** - */ -#define NFCIP_ATR_RETRY_MAX 2U /*!< Max consecutive retrys of an ATR REQ with transm error*/ - -#define NFCIP_PSLPAY_LEN (2U) /*!< PSL Payload length (BRS + FSL) */ -#define NFCIP_PSLREQ_LEN \ - (3U + RFAL_NFCDEP_LEN_LEN) /*!< PSL REQ length (incl LEN) */ -#define NFCIP_PSLRES_LEN \ - (3U + RFAL_NFCDEP_LEN_LEN) /*!< PSL RES length (incl LEN) */ - -#define NFCIP_ATRREQ_BUF_LEN \ - (RFAL_NFCDEP_ATRREQ_MAX_LEN + RFAL_NFCDEP_LEN_LEN) /*!< ATR REQ max length (incl LEN) */ -#define NFCIP_ATRRES_BUF_LEN \ - (RFAL_NFCDEP_ATRRES_MAX_LEN + RFAL_NFCDEP_LEN_LEN) /*!< ATR RES max length (incl LEN) */ - -#define NFCIP_RLSREQ_LEN \ - (3U + RFAL_NFCDEP_LEN_LEN) /*!< RLS REQ length (incl LEN) */ -#define NFCIP_RLSRES_LEN \ - (3U + RFAL_NFCDEP_LEN_LEN) /*!< RSL RES length (incl LEN) */ -#define NFCIP_RLSRES_MIN \ - (2U + RFAL_NFCDEP_LEN_LEN) /*!< Minimum length for a RLS RES (incl LEN) */ - -#define NFCIP_DSLREQ_LEN \ - (3U + RFAL_NFCDEP_LEN_LEN) /*!< DSL REQ length (incl LEN) */ -#define NFCIP_DSLRES_LEN \ - (3U + RFAL_NFCDEP_LEN_LEN) /*!< DSL RES length (incl LEN) */ -#define NFCIP_DSLRES_MIN \ - (2U + RFAL_NFCDEP_LEN_LEN) /*!< Minimum length for a DSL RES (incl LEN) */ - -#define NFCIP_DSLRES_MAX_LEN \ - (3U + RFAL_NFCDEP_LEN_LEN) /*!< Maximum length for a DSL RES (incl LEN) */ -#define NFCIP_RLSRES_MAX_LEN \ - (3U + RFAL_NFCDEP_LEN_LEN) /*!< Minimum length for a RLS RES (incl LEN) */ -#define NFCIP_TARGET_RES_MAX \ - (MAX(NFCIP_RLSRES_MAX_LEN, NFCIP_DSLRES_MAX_LEN)) /*!< Max target control res length */ - -#define NFCIP_NO_FWT RFAL_FWT_NONE /*!< No FWT value - Target Mode */ -#define NFCIP_INIT_MIN_RTOX 1U /*!< Minimum RTOX value Digital 1.0 14.8.4.1 */ -#define NFCIP_INIT_MAX_RTOX 59U /*!< Maximum RTOX value Digital 1.0 14.8.4.1 */ - -#define NFCIP_TARG_MIN_RTOX 1U /*!< Minimum target RTOX value Digital 1.0 14.8.4.1 */ -#define NFCIP_TARG_MAX_RTOX 59U /*!< Maximum target RTOX value Digital 1.0 14.8.4.1 */ - -#define NFCIP_TRECOV 1280U /*!< Digital 1.0 A.10 Trecov */ - -#define NFCIP_TIMEOUT_ADJUSTMENT \ - 3072U /*!< Timeout Adjustment to compensate timing from end of Tx to end of frame */ -#define NFCIP_RWT_ACTIVATION \ - (0x1000001U + \ - NFCIP_TIMEOUT_ADJUSTMENT) /*!< Digital 2.2 B.11 RWT ACTIVATION 2^24 + RWT Delta + Adjustment*/ -#define NFCIP_RWT_ACM_ACTIVATION \ - (0x200001U + \ - NFCIP_TIMEOUT_ADJUSTMENT) /*!< Digital 2.2 B.11 RWT ACTIVATION 2^21 + RWT Delta + Adjustment*/ - -#define RFAL_NFCDEP_HEADER_PAD \ - (RFAL_NFCDEP_DEPREQ_HEADER_LEN - \ - RFAL_NFCDEP_LEN_MIN) /*!< Difference between expected rcvd header len and max foreseen */ - -#ifndef RFAL_NFCDEP_MAX_TX_RETRYS -#define RFAL_NFCDEP_MAX_TX_RETRYS \ - (uint8_t)3U /*!< Number of retransmit retyrs */ -#endif /* RFAL_NFCDEP_MAX_TX_RETRYS */ - -#ifndef RFAL_NFCDEP_TO_RETRYS -#define RFAL_NFCDEP_TO_RETRYS \ - (uint8_t)3U /*!< Number of retrys for Timeout */ -#endif /* RFAL_NFCDEP_TO_RETRYS */ - -#ifndef RFAL_NFCDEP_MAX_RTOX_RETRYS -#define RFAL_NFCDEP_MAX_RTOX_RETRYS \ - (uint8_t)10U /*!< Number of retrys for RTOX Digital 2.0 17.12.4.3 */ -#endif /* RFAL_NFCDEP_MAX_RTOX_RETRYS */ - -#ifndef RFAL_NFCDEP_MAX_NACK_RETRYS -#define RFAL_NFCDEP_MAX_NACK_RETRYS \ - (uint8_t)3U /*!< Number of retrys for NACK */ -#endif /* RFAL_NFCDEP_MAX_NACK_RETRYS */ - -#ifndef RFAL_NFCDEP_MAX_ATN_RETRYS -#define RFAL_NFCDEP_MAX_ATN_RETRYS \ - (uint8_t)3U /*!< Number of retrys for ATN */ -#endif /* RFAL_NFCDEP_MAX_ATN_RETRYS */ - -#define NFCIP_MIN_TXERROR_LEN \ - 4U /*!< Minimum frame length with error to be ignored Digital 1.0 14.12.5.4 */ - -#define NFCIP_REQ (uint8_t)0xD4U /*!= NFCIP_ST_INIT_IDLE) && \ - ((st) <= \ - NFCIP_ST_INIT_RLS)) /*!< Checks if module is set as Initiator */ -#define nfcipIsTarget(st) \ - (!nfcipIsInitiator( \ - st)) /*!< Checks if module is set as Target */ - -#define nfcipIsBRAllowed(br, mBR) \ - (((1U << (br)) & (mBR)) != \ - 0U) /*!< Checks bit rate is allowed by given mask */ - -#define nfcipIsEmptyDEPEnabled(op) \ - (!nfcipIsEmptyDEPDisabled( \ - op)) /*!< Checks if empty payload is allowed by operation config NCI 1.0 Table 81 */ -#define nfcipIsEmptyDEPDisabled(op) \ - (((op)&RFAL_NFCDEP_OPER_EMPTY_DEP_DIS) != \ - 0U) /*!< Checks if empty payload is not allowed by operation config NCI 1.0 Table 81 */ - -#define nfcipIsRTOXReqEnabled(op) \ - (!nfcipIsRTOXReqDisabled( \ - op)) /*!< Checks if send a RTOX_REQ is allowed by operation config NCI 1.0 Table 81 */ -#define nfcipIsRTOXReqDisabled(op) \ - (((op)&RFAL_NFCDEP_OPER_RTOX_REQ_DIS) != \ - 0U) /*!< Checks if send a RTOX_REQ is not allowed by operation config NCI 1.0 Table 81 */ - -/*! Checks if isDeactivating callback is set and calls it, otherwise returns false */ -#define nfcipIsDeactivationPending() \ - ((gNfcip.isDeactivating == NULL) ? false : gNfcip.isDeactivating()) - -/*! Returns the RWT Activation according to the current communication mode */ -#define nfcipRWTActivation() \ - ((gNfcip.cfg.commMode == RFAL_NFCDEP_COMM_ACTIVE) ? NFCIP_RWT_ACM_ACTIVATION : \ - NFCIP_RWT_ACTIVATION) - -#define nfcipRTOXAdjust(v) \ - ((v) - ((v) >> 3)) /*!< Adjust RTOX timer value to a percentage of the total, current 88% */ - -/*******************************************************************************/ - -// timerPollTimeoutValue is necessary after timerCalculateTimeout so that system will wake up upon timer timeout. -#define nfcipTimerStart(timer, time_ms) \ - do { \ - platformTimerDestroy(timer); \ - (timer) = platformTimerCreate((uint16_t)(time_ms)); \ - } while(0) /*!< Configures and starts the RTOX timer */ -#define nfcipTimerisExpired(timer) \ - platformTimerIsExpired(timer) /*!< Checks RTOX timer has expired */ -#define nfcipTimerDestroy(timer) \ - platformTimerDestroy(timer) /*!< Destroys RTOX timer */ - -#define nfcipLogE(...) /*!< Macro for the error log method */ -#define nfcipLogW(...) /*!< Macro for the warning log method */ -#define nfcipLogI(...) /*!< Macro for the info log method */ -#define nfcipLogD(...) /*!< Macro for the debug log method */ - -/*! Digital 1.1 - 16.12.5.2 The Target SHALL NOT attempt any error recovery and remains in Rx mode upon Transmission or a Protocol Error */ -#define nfcDepReEnableRx(rxB, rxBL, rxL) \ - rfalTransceiveBlockingTx( \ - NULL, \ - 0, \ - (rxB), \ - (rxBL), \ - (rxL), \ - (RFAL_TXRX_FLAGS_DEFAULT | (uint32_t)RFAL_TXRX_FLAGS_NFCIP1_ON), \ - RFAL_FWT_NONE) - -/* - ****************************************************************************** - * LOCAL DATA TYPES - ****************************************************************************** - */ - -/*! Struct that holds all DEP parameters/configs for the following communications */ -typedef struct { - uint8_t did; /*!< Device ID (DID) to be used */ - - uint8_t* txBuf; /*!< Pointer to the Tx buffer to be sent */ - uint16_t txBufLen; /*!< Length of the data in the txBuf */ - uint8_t txBufPaylPos; /*!< Position inside txBuf where data starts */ - bool txChaining; /*!< Flag indicating chaining on transmission */ - - uint8_t* rxBuf; /*!< Pointer to the Rx buffer for incoming data */ - uint16_t rxBufLen; /*!< Length of the data in the rxBuf */ - uint8_t rxBufPaylPos; /*!< Position inside rxBuf where data is to be placed*/ - - uint32_t fwt; /*!< Frame Waiting Time (FWT) to be used */ - uint32_t dFwt; /*!< Delta Frame Waiting Time (dFWT) to be used */ - uint16_t fsc; /*!< Frame Size (FSC) to be used */ - -} rfalNfcDepDEPParams; - -/*! NFCIP module states */ -typedef enum { - NFCIP_ST_IDLE, - NFCIP_ST_INIT_IDLE, - NFCIP_ST_INIT_ATR, - NFCIP_ST_INIT_PSL, - NFCIP_ST_INIT_DEP_IDLE, - NFCIP_ST_INIT_DEP_TX, - NFCIP_ST_INIT_DEP_RX, - NFCIP_ST_INIT_DEP_ATN, - NFCIP_ST_INIT_DSL, - NFCIP_ST_INIT_RLS, - - NFCIP_ST_TARG_WAIT_ATR, - NFCIP_ST_TARG_WAIT_ACTV, - NFCIP_ST_TARG_DEP_IDLE, - NFCIP_ST_TARG_DEP_RX, - NFCIP_ST_TARG_DEP_RTOX, - NFCIP_ST_TARG_DEP_TX, - NFCIP_ST_TARG_DEP_SLEEP -} rfalNfcDepState; - -/*! NFCIP commands (Request, Response) */ -typedef enum { - NFCIP_CMD_ATR_REQ = 0x00, - NFCIP_CMD_ATR_RES = 0x01, - NFCIP_CMD_WUP_REQ = 0x02, - NFCIP_CMD_WUP_RES = 0x03, - NFCIP_CMD_PSL_REQ = 0x04, - NFCIP_CMD_PSL_RES = 0x05, - NFCIP_CMD_DEP_REQ = 0x06, - NFCIP_CMD_DEP_RES = 0x07, - NFCIP_CMD_DSL_REQ = 0x08, - NFCIP_CMD_DSL_RES = 0x09, - NFCIP_CMD_RLS_REQ = 0x0A, - NFCIP_CMD_RLS_RES = 0x0B -} rfalNfcDepCmd; - -/*! Struct that holds all NFCIP data */ -typedef struct { - rfalNfcDepConfigs cfg; /*!< Holds the current configuration to be used */ - - rfalNfcDepState state; /*!< Current state of the NFCIP module */ - uint8_t pni; /*!< Packet Number Information (PNI) counter */ - - uint8_t lastCmd; /*!< Last command sent */ - uint8_t lastPFB; /*!< Last PFB sent */ - uint8_t lastPFBnATN; /*!< Last PFB sent (excluding ATN) */ - uint8_t lastRTOX; /*!< Last RTOX value sent */ - - uint8_t cntTxRetrys; /*!< Retransmissions counter */ - uint8_t cntTORetrys; /*!< Timeouts counter */ - uint8_t cntRTOXRetrys; /*!< RTOX counter */ - uint8_t cntNACKRetrys; /*!< NACK counter */ - uint8_t cntATNRetrys; /*!< Attention (ATN) counter */ - - uint16_t fsc; /*!< Current Frame Size (FSC) to be used */ - bool isTxChaining; /*!< Flag for chaining on Transmission */ - bool isRxChaining; /*!< Flag for chaining on Reception */ - uint8_t* txBuf; /*!< Pointer to the Tx buffer to be sent */ - uint8_t* rxBuf; /*!< Pointer to the Rx buffer for incoming data */ - uint16_t txBufLen; /*!< Length of the data in the txBuf */ - uint16_t rxBufLen; /*!< Length of rxBuf buffer */ - uint16_t* rxRcvdLen; /*!< Length of the data in the rxBuf */ - uint8_t txBufPaylPos; /*!< Position in txBuf where data starts */ - uint8_t rxBufPaylPos; /*!< Position in rxBuf where data is to be placed */ - bool* isChaining; /*!< Flag for chaining on Reception */ - - rfalNfcDepDevice* nfcDepDev; /*!< Pointer to NFC-DEP device info */ - - uint32_t RTOXTimer; /*!< Timer used for RTOX */ - rfalNfcDepDeactCallback isDeactivating; /*!< Deactivating flag check callback */ - - bool isReqPending; /*!< Flag pending REQ from Target activation */ - bool isTxPending; /*!< Flag pending DEP Block while waiting RTOX Ack */ - bool isWait4RTOX; /*!< Flag for waiting RTOX Ack */ - - rfalNfcDepPduTxRxParam PDUParam; /*!< PDU TxRx params */ - uint16_t PDUTxPos; /*!< PDU Tx position */ - uint16_t PDURxPos; /*!< PDU Rx position */ - bool isPDURxChaining; /*!< PDU Transceive chaining flag */ -} rfalNfcDep; - -/* - ****************************************************************************** - * LOCAL VARIABLES - ****************************************************************************** - */ - -static rfalNfcDep gNfcip; /*!< NFCIP module instance */ - -/* - ****************************************************************************** - * LOCAL FUNCTION PROTOTYPES - ****************************************************************************** - */ - -static ReturnCode nfcipTxRx( - rfalNfcDepCmd cmd, - uint8_t* txBuf, - uint32_t fwt, - uint8_t* paylBuf, - uint8_t paylBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rxActLen); -static ReturnCode nfcipTx( - rfalNfcDepCmd cmd, - uint8_t* txBuf, - uint8_t* paylBuf, - uint16_t paylLen, - uint8_t pfbData, - uint32_t fwt); -static ReturnCode nfcipDEPControlMsg(uint8_t pfb, uint8_t RTOX); -static ReturnCode nfcipInitiatorHandleDEP( - ReturnCode rxRes, - uint16_t rxLen, - uint16_t* outActRxLen, - bool* outIsChaining); -static ReturnCode - nfcipTargetHandleRX(ReturnCode rxRes, uint16_t* outActRxLen, bool* outIsChaining); -static ReturnCode nfcipTargetHandleActivation(rfalNfcDepDevice* nfcDepDev, uint8_t* outBRS); - -/*! - ****************************************************************************** - * \brief NFCIP Configure - * - * Configures the nfcip layer with the given configurations - * - * \param[in] cfg : nfcip configuration for following communication - ****************************************************************************** - */ -static void nfcipConfig(const rfalNfcDepConfigs* cfg); - -/*! - ****************************************************************************** - * \brief Set DEP parameters - * - * This method sets the parameters/configs for following Data Exchange - * Sets the nfcip module state according to the role it is configured - * - * - * \warning To be used only after proper Initiator/Target activation: - * nfcipTargetHandleActivation() or nfcipInitiatorActivate() has - * returned success - * - * This must be called before nfcipRun() in case of Target to pass - * rxBuffer - * - * Everytime some data needs to be transmitted call this to set it and - * call nfcipRun() until done or error - * - * \param[in] DEPParams : the parameters to be used during Data Exchange - ****************************************************************************** - */ -static void nfcipSetDEPParams(const rfalNfcDepDEPParams* DEPParams); - -/*! - ****************************************************************************** - * \brief NFCIP run protocol - * - * This method handles all the nfcip protocol during Data Exchange (DEP - * requests and responses). - * - * A data exchange cycle is considered a DEP REQ and a DEP RES. - * - * In case of Tx chaining(MI) must signal it with nfcipSetDEPParams() - * In case of Rx chaining(MI) outIsChaining will be set to true and the - * current data returned - * - * \param[out] outActRxLen : data received length - * \param[out] outIsChaining : true if other peer is performing chaining(MI) - * - * \return ERR_NONE : Data exchange cycle completed successfully - * \return ERR_TIMEOUT : Timeout occurred - * \return ERR_PROTO : Protocol error occurred - * \return ERR_AGAIN : Other peer is doing chaining(MI), current block - * was received successfully call again until complete - * - ****************************************************************************** - */ -static ReturnCode nfcipRun(uint16_t* outActRxLen, bool* outIsChaining); - -/*! - ****************************************************************************** - * \brief Transmission method - * - * This method checks if the current communication is Active or Passive - * and performs the necessary procedures for each communication type - * - * Transmits the data hold in txBuf - * - * \param[in] txBuf : buffer to transmit - * \param[in] txBufLen : txBuffer capacity - * \param[in] fwt : fwt for current Tx - * - * \return ERR_NONE : No error - ****************************************************************************** - */ -static ReturnCode nfcipDataTx(uint8_t* txBuf, uint16_t txBufLen, uint32_t fwt); - -/*! - ****************************************************************************** - * \brief Reception method - * - * This method checks if the current communication is Active or Passive - * and calls the appropriate reception method - * - * Copies incoming data to rxBuf - * - * \param[in] blocking : reception is to be done blocking or non-blocking - * - * \return ERR_BUSY : Busy - * \return ERR_NONE : No error - ****************************************************************************** - */ -static ReturnCode nfcipDataRx(bool blocking); - -/* - ****************************************************************************** - * LOCAL FUNCTIONS - ****************************************************************************** - */ - -/*******************************************************************************/ - -/*******************************************************************************/ -static bool nfcipDxIsSupported(uint8_t Dx, uint8_t BRx, uint8_t BSx) { - uint8_t Bx; - - /* Take the min of the possible bit rates, we'll use one for both directions */ - Bx = MIN(BRx, BSx); - - /* Lower bit rates must be supported for P2P */ - if((Dx <= (uint8_t)RFAL_NFCDEP_Dx_04_424)) { - return true; - } - - if((Dx == (uint8_t)RFAL_NFCDEP_Dx_08_848) && (Bx >= (uint8_t)RFAL_NFCDEP_Bx_08_848)) { - return true; - } - - return false; -} - -/*******************************************************************************/ -static ReturnCode nfcipTxRx( - rfalNfcDepCmd cmd, - uint8_t* txBuf, - uint32_t fwt, - uint8_t* paylBuf, - uint8_t paylBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rxActLen) { - ReturnCode ret; - - if((cmd == NFCIP_CMD_DEP_REQ) || - (cmd == NFCIP_CMD_DEP_RES)) /* this method cannot be used for DEPs */ - { - return ERR_PARAM; - } - - /* Assign the global params for this TxRx */ - gNfcip.rxBuf = rxBuf; - gNfcip.rxBufLen = rxBufLen; - gNfcip.rxRcvdLen = rxActLen; - - /*******************************************************************************/ - /* Transmission */ - /*******************************************************************************/ - if(txBuf != NULL) /* if nothing to Tx, just do Rx */ - { - EXIT_ON_ERR(ret, nfcipTx(cmd, txBuf, paylBuf, paylBufLen, 0, fwt)); - } - - /*******************************************************************************/ - /* Reception */ - /*******************************************************************************/ - ret = nfcipDataRx(true); - if(ret != ERR_NONE) { - return ret; - } - - /*******************************************************************************/ - *rxActLen = *rxBuf; /* Use LEN byte instead due to with/without CRC modes */ - return ERR_NONE; /* Tx and Rx completed successfully */ -} - -/*******************************************************************************/ -static ReturnCode nfcipDEPControlMsg(uint8_t pfb, uint8_t RTOX) { - uint8_t ctrlMsg[20]; - rfalNfcDepCmd depCmd; - uint32_t fwt; - - /*******************************************************************************/ - /* Calculate Cmd and fwt to be used */ - /*******************************************************************************/ - depCmd = - ((gNfcip.cfg.role == RFAL_NFCDEP_ROLE_TARGET) ? NFCIP_CMD_DEP_RES : NFCIP_CMD_DEP_REQ); - fwt = - ((gNfcip.cfg.role == RFAL_NFCDEP_ROLE_TARGET) ? - NFCIP_NO_FWT : - (nfcip_PFBisSTO(pfb) ? ((RTOX * gNfcip.cfg.fwt) + gNfcip.cfg.dFwt) : - (gNfcip.cfg.fwt + gNfcip.cfg.dFwt))); - - if(nfcip_PFBisSTO(pfb)) { - ctrlMsg[RFAL_NFCDEP_DEPREQ_HEADER_LEN] = RTOX; - return nfcipTx( - depCmd, ctrlMsg, &ctrlMsg[RFAL_NFCDEP_DEPREQ_HEADER_LEN], sizeof(uint8_t), pfb, fwt); - } else { - return nfcipTx(depCmd, ctrlMsg, NULL, 0, pfb, fwt); - } -} - -/*******************************************************************************/ -static void nfcipClearCounters(void) { - gNfcip.cntATNRetrys = 0; - gNfcip.cntNACKRetrys = 0; - gNfcip.cntTORetrys = 0; - gNfcip.cntTxRetrys = 0; - gNfcip.cntRTOXRetrys = 0; -} - -/*******************************************************************************/ -static ReturnCode nfcipInitiatorHandleDEP( - ReturnCode rxRes, - uint16_t rxLen, - uint16_t* outActRxLen, - bool* outIsChaining) { - ReturnCode ret; - uint8_t nfcDepLen; - uint8_t rxMsgIt; - uint8_t rxPFB; - uint8_t rxRTOX; - uint8_t optHdrLen; - - ret = ERR_INTERNAL; - rxMsgIt = 0; - optHdrLen = 0; - - *outActRxLen = 0; - *outIsChaining = false; - - /*******************************************************************************/ - /* Handle reception errors */ - /*******************************************************************************/ - switch(rxRes) { - /*******************************************************************************/ - /* Timeout -> Digital 1.0 14.15.5.6 */ - case ERR_TIMEOUT: - - nfcipLogI(" NFCIP(I) TIMEOUT TORetrys:%d \r\n", gNfcip.cntTORetrys); - - /* Digital 1.0 14.15.5.6 - If nTO >= Max raise protocol error */ - if(gNfcip.cntTORetrys++ >= RFAL_NFCDEP_TO_RETRYS) { - return ERR_PROTO; - } - - /*******************************************************************************/ - /* Upon Timeout error, if Deactivation is pending, no more error recovery - * will be done #54. - * This is used to address the issue some devices that havea big TO. - * Normally LLCP layer has timeout already, and NFCIP layer is still - * running error handling, retrying ATN/NACKs */ - /*******************************************************************************/ - if(nfcipIsDeactivationPending()) { - nfcipLogI(" skipping error recovery due deactivation pending \r\n"); - return ERR_TIMEOUT; - } - - /* Digital 1.0 14.15.5.6 1) If last PDU was NACK */ - if(nfcip_PFBisRNACK(gNfcip.lastPFB)) { - /* Digital 1.0 14.15.5.6 2) if NACKs failed raise protocol error */ - if(gNfcip.cntNACKRetrys++ >= RFAL_NFCDEP_MAX_NACK_RETRYS) { - return ERR_PROTO; - } - - /* Send NACK */ - nfcipLogI(" NFCIP(I) Sending NACK retry: %d \r\n", gNfcip.cntNACKRetrys); - EXIT_ON_ERR(ret, nfcipDEPControlMsg(nfcip_PFBRPDU_NACK(gNfcip.pni), 0)); - return ERR_BUSY; - } - - nfcipLogI(" NFCIP(I) Checking if to send ATN ATNRetrys: %d \r\n", gNfcip.cntATNRetrys); - - /* Digital 1.0 14.15.5.6 3) Otherwise send ATN */ - if(gNfcip.cntATNRetrys++ >= RFAL_NFCDEP_MAX_NACK_RETRYS) { - return ERR_PROTO; - } - - /* Send ATN */ - nfcipLogI(" NFCIP(I) Sending ATN \r\n"); - EXIT_ON_ERR(ret, nfcipDEPControlMsg(nfcip_PFBSPDU_ATN(), 0)); - return ERR_BUSY; - - /*******************************************************************************/ - /* Data rcvd with error -> Digital 1.0 14.12.5.4 */ - case ERR_CRC: - case ERR_PAR: - case ERR_FRAMING: - case ERR_RF_COLLISION: - - nfcipLogI(" NFCIP(I) rx Error: %d \r\n", rxRes); - - /* Digital 1.0 14.12.5.4 Tx Error with data, ignore */ - if(rxLen < NFCIP_MIN_TXERROR_LEN) { - nfcipLogI(" NFCIP(I) Transmission error w data \r\n"); -#if 0 - if(gNfcip.cfg.commMode == RFAL_NFCDEP_COMM_PASSIVE) - { - nfcipLogI( " NFCIP(I) Transmission error w data -> reEnabling Rx \r\n" ); - nfcipReEnableRxTout( NFCIP_TRECOV ); - return ERR_BUSY; - } -#endif /* 0 */ - } - - /* Digital 1.1 16.12.5.4 if NACKs failed raise Transmission error */ - if(gNfcip.cntNACKRetrys++ >= RFAL_NFCDEP_MAX_NACK_RETRYS) { - return ERR_FRAMING; - } - - /* Send NACK */ - nfcipLogI(" NFCIP(I) Sending NACK \r\n"); - EXIT_ON_ERR(ret, nfcipDEPControlMsg(nfcip_PFBRPDU_NACK(gNfcip.pni), 0)); - return ERR_BUSY; - - case ERR_NONE: - break; - - case ERR_BUSY: - return ERR_BUSY; /* Debug purposes */ - - default: - nfcipLogW(" NFCIP(I) Error: %d \r\n", rxRes); - return rxRes; - } - - /*******************************************************************************/ - /* Rx OK check if valid DEP PDU */ - /*******************************************************************************/ - - /* Due to different modes on ST25R391x (with/without CRC) use NFC-DEP LEN instead of bytes retrieved */ - nfcDepLen = gNfcip.rxBuf[rxMsgIt++]; - - nfcipLogD(" NFCIP(I) rx OK: %d bytes \r\n", nfcDepLen); - - /* Digital 1.0 14.15.5.5 Protocol Error */ - if(gNfcip.rxBuf[rxMsgIt++] != NFCIP_RES) { - nfcipLogW(" NFCIP(I) error %02X instead of %02X \r\n", gNfcip.rxBuf[--rxMsgIt], NFCIP_RES); - return ERR_PROTO; - } - - /* Digital 1.0 14.15.5.5 Protocol Error */ - if(gNfcip.rxBuf[rxMsgIt++] != (uint8_t)NFCIP_CMD_DEP_RES) { - nfcipLogW( - " NFCIP(I) error %02X instead of %02X \r\n", - gNfcip.rxBuf[--rxMsgIt], - NFCIP_CMD_DEP_RES); - return ERR_PROTO; - } - - rxPFB = gNfcip.rxBuf[rxMsgIt++]; - - /*******************************************************************************/ - /* Check for valid PFB type */ - if(!(nfcip_PFBisSPDU(rxPFB) || nfcip_PFBisRPDU(rxPFB) || nfcip_PFBisIPDU(rxPFB))) { - return ERR_PROTO; - } - - /*******************************************************************************/ - /* Digital 1.0 14.8.2.1 check if DID is expected and match -> Protocol Error */ - if(gNfcip.cfg.did != RFAL_NFCDEP_DID_NO) { - if((gNfcip.rxBuf[rxMsgIt++] != gNfcip.cfg.did) || !nfcip_PFBhasDID(rxPFB)) { - return ERR_PROTO; - } - optHdrLen++; /* Inc header optional field cnt*/ - } else if(nfcip_PFBhasDID(rxPFB)) /* DID not expected but rcv */ - { - return ERR_PROTO; - } else { - /* MISRA 15.7 - Empty else */ - } - - /*******************************************************************************/ - /* Digital 1.0 14.6.2.8 & 14.6.3.11 NAD must not be used */ - if(gNfcip.cfg.nad != RFAL_NFCDEP_NAD_NO) { - if((gNfcip.rxBuf[rxMsgIt++] != gNfcip.cfg.nad) || !nfcip_PFBhasNAD(rxPFB)) { - return ERR_PROTO; - } - optHdrLen++; /* Inc header optional field cnt*/ - } else if(nfcip_PFBhasNAD(rxPFB)) /* NAD not expected but rcv */ - { - return ERR_PROTO; - } else { - /* MISRA 15.7 - Empty else */ - } - - /*******************************************************************************/ - /* Process R-PDU */ - /*******************************************************************************/ - if(nfcip_PFBisRPDU(rxPFB)) { - /*******************************************************************************/ - /* R ACK */ - /*******************************************************************************/ - if(nfcip_PFBisRACK(rxPFB)) { - nfcipLogI(" NFCIP(I) Rcvd ACK \r\n"); - if(gNfcip.pni == nfcip_PBF_PNI(rxPFB)) { - /* 14.12.3.3 R-ACK with correct PNI -> Increment */ - gNfcip.pni = nfcip_PNIInc(gNfcip.pni); - - /* R-ACK while not performing chaining -> Protocol error*/ - if(!gNfcip.isTxChaining) { - return ERR_PROTO; - } - - nfcipClearCounters(); - gNfcip.state = NFCIP_ST_INIT_DEP_IDLE; - return ERR_NONE; /* This block has been transmitted */ - } else /* Digital 1.0 14.12.4.5 ACK with wrong PNI Initiator may retransmit */ - { - if(gNfcip.cntTxRetrys++ >= RFAL_NFCDEP_MAX_TX_RETRYS) { - return ERR_PROTO; - } - - /* Extended the MAY in Digital 1.0 14.12.4.5 to only reTransmit if the ACK - * is for the previous DEP, otherwise raise Protocol immediately - * If the PNI difference is more than 1 it is worthless to reTransmit 3x - * and after raise the error */ - - if(nfcip_PNIDec(gNfcip.pni) == nfcip_PBF_PNI(rxPFB)) { - /* ReTransmit */ - nfcipLogI(" NFCIP(I) Rcvd ACK prev PNI -> reTx \r\n"); - gNfcip.state = NFCIP_ST_INIT_DEP_TX; - return ERR_BUSY; - } - - nfcipLogI(" NFCIP(I) Rcvd ACK unexpected far PNI -> Error \r\n"); - return ERR_PROTO; - } - } else /* Digital 1.0 - 14.12.5.2 Target must never send NACK */ - { - return ERR_PROTO; - } - } - - /*******************************************************************************/ - /* Process S-PDU */ - /*******************************************************************************/ - if(nfcip_PFBisSPDU(rxPFB)) { - nfcipLogI(" NFCIP(I) Rcvd S-PDU \r\n"); - /*******************************************************************************/ - /* S ATN */ - /*******************************************************************************/ - if(nfcip_PFBisSATN(rxPFB)) /* If is a S-ATN */ - { - nfcipLogI(" NFCIP(I) Rcvd ATN \r\n"); - if(nfcip_PFBisSATN(gNfcip.lastPFB)) /* Check if is expected */ - { - gNfcip.cntATNRetrys = 0; /* Clear ATN counter */ - - /* Although spec is not clear NFC Forum Digital test is expecting to - * retransmit upon receiving ATN_RES */ - if(nfcip_PFBisSTO(gNfcip.lastPFBnATN)) { - nfcipLogI(" NFCIP(I) Rcvd ATN -> reTx RTOX_RES \r\n"); - EXIT_ON_ERR(ret, nfcipDEPControlMsg(nfcip_PFBSPDU_TO(), gNfcip.lastRTOX)); - } else { - /* ReTransmit ? */ - if(gNfcip.cntTxRetrys++ >= RFAL_NFCDEP_MAX_TX_RETRYS) { - return ERR_PROTO; - } - - nfcipLogI(" NFCIP(I) Rcvd ATN -> reTx PNI: %d \r\n", gNfcip.pni); - gNfcip.state = NFCIP_ST_INIT_DEP_TX; - } - - return ERR_BUSY; - } else /* Digital 1.0 14.12.4.4 & 14.12.4.8 */ - { - return ERR_PROTO; - } - } - /*******************************************************************************/ - /* S TO */ - /*******************************************************************************/ - else if(nfcip_PFBisSTO(rxPFB)) /* If is a S-TO (RTOX) */ - { - nfcipLogI(" NFCIP(I) Rcvd TO \r\n"); - - rxRTOX = gNfcip.rxBuf[rxMsgIt++]; - - /* Digital 1.1 16.12.4.3 - Initiator MAY stop accepting subsequent RTOX Req * - * - RTOX request to an ATN -> Protocol error */ - if((gNfcip.cntRTOXRetrys++ > RFAL_NFCDEP_MAX_RTOX_RETRYS) || - nfcip_PFBisSATN(gNfcip.lastPFB)) { - return ERR_PROTO; - } - - /* Digital 1.1 16.8.4.1 RTOX must be between [1,59] */ - if((rxRTOX < NFCIP_INIT_MIN_RTOX) || (rxRTOX > NFCIP_INIT_MAX_RTOX)) { - return ERR_PROTO; - } - - EXIT_ON_ERR(ret, nfcipDEPControlMsg(nfcip_PFBSPDU_TO(), rxRTOX)); - gNfcip.lastRTOX = rxRTOX; - - return ERR_BUSY; - } else { - /* Unexpected S-PDU */ - return ERR_PROTO; /* PRQA S 2880 # MISRA 2.1 - Guard code to prevent unexpected behavior */ - } - } - - /*******************************************************************************/ - /* Process I-PDU */ - /*******************************************************************************/ - if(nfcip_PFBisIPDU(rxPFB)) { - if(gNfcip.pni != nfcip_PBF_PNI(rxPFB)) { - nfcipLogI( - " NFCIP(I) Rcvd IPDU wrong PNI curPNI: %d rxPNI: %d \r\n", - gNfcip.pni, - nfcip_PBF_PNI(rxPFB)); - return ERR_PROTO; - } - - nfcipLogD(" NFCIP(I) Rcvd IPDU OK PNI: %d \r\n", gNfcip.pni); - - /* 14.12.3.3 I-PDU with correct PNI -> Increment */ - gNfcip.pni = nfcip_PNIInc(gNfcip.pni); - - /* Successful data Exchange */ - nfcipClearCounters(); - *outActRxLen = ((uint16_t)nfcDepLen - RFAL_NFCDEP_DEP_HEADER - (uint16_t)optHdrLen); - - if((&gNfcip.rxBuf[gNfcip.rxBufPaylPos] != - &gNfcip.rxBuf[RFAL_NFCDEP_DEP_HEADER + optHdrLen]) && - (*outActRxLen > 0U)) { - ST_MEMMOVE( - &gNfcip.rxBuf[gNfcip.rxBufPaylPos], - &gNfcip.rxBuf[RFAL_NFCDEP_DEP_HEADER + optHdrLen], - *outActRxLen); - } - - /*******************************************************************************/ - /* Check if target is indicating chaining MI */ - /*******************************************************************************/ - if(nfcip_PFBisIMI(rxPFB)) { - gNfcip.isRxChaining = true; - *outIsChaining = true; - - nfcipLogD(" NFCIP(I) Rcvd IPDU OK w MI -> ACK \r\n"); - EXIT_ON_ERR( - ret, nfcipDEPControlMsg(nfcip_PFBRPDU_ACK(gNfcip.pni), gNfcip.rxBuf[rxMsgIt++])); - - return ERR_AGAIN; /* Send Again signalling to run again, but some chaining data has arrived*/ - } else { - gNfcip.isRxChaining = false; - gNfcip.state = NFCIP_ST_INIT_DEP_IDLE; - - ret = ERR_NONE; /* Data exchange done */ - } - } - return ret; -} - -/*******************************************************************************/ -static ReturnCode - nfcipTargetHandleRX(ReturnCode rxRes, uint16_t* outActRxLen, bool* outIsChaining) { - ReturnCode ret; - uint8_t nfcDepLen; - uint8_t rxMsgIt; - uint8_t rxPFB; - uint8_t optHdrLen; - uint8_t resBuf[RFAL_NFCDEP_HEADER_PAD + NFCIP_TARGET_RES_MAX]; - - ret = ERR_INTERNAL; - rxMsgIt = 0; - optHdrLen = 0; - - *outActRxLen = 0; - *outIsChaining = false; - - /*******************************************************************************/ - /* Handle reception errors */ - /*******************************************************************************/ - switch(rxRes) { - /*******************************************************************************/ - case ERR_NONE: - break; - - case ERR_LINK_LOSS: - nfcipLogW(" NFCIP(T) Error: %d \r\n", rxRes); - return rxRes; - - case ERR_BUSY: - return ERR_BUSY; /* Debug purposes */ - - case ERR_TIMEOUT: - case ERR_CRC: - case ERR_PAR: - case ERR_FRAMING: - case ERR_PROTO: - default: - /* Digital 1.1 16.12.5.2 The Target MUST NOT attempt any error recovery. * - * The Target MUST always stay in receive mode when a * - * Transmission Error or a Protocol Error occurs. * - * * - * Do not push Transmission/Protocol Errors to upper layer in Listen Mode #766 */ - - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; - } - - /*******************************************************************************/ - /* Rx OK check if valid DEP PDU */ - /*******************************************************************************/ - - /* Due to different modes on ST25R391x (with/without CRC) use NFC-DEP LEN instead of bytes retrieved */ - nfcDepLen = gNfcip.rxBuf[rxMsgIt++]; - - nfcipLogD(" NFCIP(T) rx OK: %d bytes \r\n", nfcDepLen); - - if(gNfcip.rxBuf[rxMsgIt++] != NFCIP_REQ) { - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore bad request */ - } - - /*******************************************************************************/ - /* Check whether target rcvd a normal DEP or deactivation request */ - /*******************************************************************************/ - switch(gNfcip.rxBuf[rxMsgIt++]) { - /*******************************************************************************/ - case(uint8_t)NFCIP_CMD_DEP_REQ: - break; /* Continue to normal DEP processing */ - - /*******************************************************************************/ - case(uint8_t)NFCIP_CMD_DSL_REQ: - - nfcipLogI(" NFCIP(T) rx DSL \r\n"); - - /* Digital 1.0 14.9.1.2 If DID is used and incorrect ignore it */ - /* [Digital 1.0, 16.9.1.2]: If DID == 0, Target SHALL ignore DSL_REQ with DID */ - if((((gNfcip.rxBuf[rxMsgIt++] != gNfcip.cfg.did) || - (nfcDepLen != RFAL_NFCDEP_DSL_RLS_LEN_DID)) && - (gNfcip.cfg.did != RFAL_NFCDEP_DID_NO)) || - ((gNfcip.cfg.did == RFAL_NFCDEP_DID_NO) && - (nfcDepLen != RFAL_NFCDEP_DSL_RLS_LEN_NO_DID))) { - nfcipLogI(" NFCIP(T) DSL wrong DID, ignoring \r\n"); - return ERR_BUSY; - } - - nfcipTx(NFCIP_CMD_DSL_RES, resBuf, NULL, 0, 0, NFCIP_NO_FWT); - - gNfcip.state = NFCIP_ST_TARG_DEP_SLEEP; - return ERR_SLEEP_REQ; - - /*******************************************************************************/ - case(uint8_t)NFCIP_CMD_RLS_REQ: - - nfcipLogI(" NFCIP(T) rx RLS \r\n"); - - /* Digital 1.0 14.10.1.2 If DID is used and incorrect ignore it */ - /* [Digital 1.0, 16.10.2.2]: If DID == 0, Target SHALL ignore DSL_REQ with DID */ - if((((gNfcip.rxBuf[rxMsgIt++] != gNfcip.cfg.did) || - (nfcDepLen != RFAL_NFCDEP_DSL_RLS_LEN_DID)) && - (gNfcip.cfg.did != RFAL_NFCDEP_DID_NO)) || - ((gNfcip.cfg.did == RFAL_NFCDEP_DID_NO) && - (nfcDepLen > RFAL_NFCDEP_DSL_RLS_LEN_NO_DID))) { - nfcipLogI(" NFCIP(T) RLS wrong DID, ignoring \r\n"); - return ERR_BUSY; - } - - nfcipTx(NFCIP_CMD_RLS_RES, resBuf, NULL, 0, 0, NFCIP_NO_FWT); - - gNfcip.state = NFCIP_ST_TARG_DEP_IDLE; - return ERR_RELEASE_REQ; - - /*******************************************************************************/ - /*case NFCIP_CMD_PSL_REQ: PSL must be handled in Activation only */ - /*case NFCIP_CMD_WUP_REQ: WUP not in NFC Forum Digital 1.0 */ - default: - - /* Don't go to NFCIP_ST_TARG_DEP_IDLE state as it needs to ignore this * - * invalid frame, and keep waiting for more frames */ - - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore bad frame */ - } - - /*******************************************************************************/ - - rxPFB = gNfcip.rxBuf[rxMsgIt++]; /* Store rcvd PFB */ - - /*******************************************************************************/ - /* Check for valid PFB type */ - if(!(nfcip_PFBisSPDU(rxPFB) || nfcip_PFBisRPDU(rxPFB) || nfcip_PFBisIPDU(rxPFB))) { - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore invalid PFB */ - } - - /*******************************************************************************/ - if(gNfcip.cfg.did != RFAL_NFCDEP_DID_NO) { - if(!nfcip_PFBhasDID(rxPFB)) { - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore bad/missing DID */ - } - if(gNfcip.rxBuf[rxMsgIt++] != gNfcip.cfg.did) /* MISRA 13.5 */ - { - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore bad/missing DID */ - } - optHdrLen++; /* Inc header optional field cnt*/ - } else if(nfcip_PFBhasDID(rxPFB)) /* DID not expected but rcv */ - { - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore unexpected DID */ - } else { - /* MISRA 15.7 - Empty else */ - } - - /*******************************************************************************/ - if(gNfcip.cfg.nad != RFAL_NFCDEP_NAD_NO) { - if((gNfcip.rxBuf[rxMsgIt++] != gNfcip.cfg.did) || !nfcip_PFBhasDID(rxPFB)) { - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore bad/missing DID */ - } - optHdrLen++; /* Inc header optional field cnt*/ - } else if(nfcip_PFBhasNAD(rxPFB)) /* NAD not expected but rcv */ - { - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore unexpected NAD */ - } else { - /* MISRA 15.7 - Empty else */ - } - - /*******************************************************************************/ - /* Process R-PDU */ - /*******************************************************************************/ - if(nfcip_PFBisRPDU(rxPFB)) { - nfcipLogD(" NFCIP(T) Rcvd R-PDU \r\n"); - /*******************************************************************************/ - /* R ACK */ - /*******************************************************************************/ - if(nfcip_PFBisRACK(rxPFB)) { - nfcipLogI(" NFCIP(T) Rcvd ACK \r\n"); - if(gNfcip.pni == nfcip_PBF_PNI(rxPFB)) { - /* R-ACK while not performing chaining -> Protocol error */ - if(!gNfcip.isTxChaining) { - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore unexpected ACK */ - } - - /* This block has been transmitted and acknowledged, perform RTOX until next data is provided */ - - /* Digital 1.1 16.12.4.7 - If ACK rcvd continue with chaining or an RTOX */ - nfcipTimerStart( - gNfcip.RTOXTimer, - nfcipRTOXAdjust(nfcipConv1FcToMs(rfalNfcDepWT2RWT(gNfcip.cfg.to)))); - gNfcip.state = NFCIP_ST_TARG_DEP_RTOX; - - return ERR_NONE; /* This block has been transmitted */ - } - - /* Digital 1.0 14.12.3.4 - If last send was ATN and rx PNI is minus 1 */ - else if( - nfcip_PFBisSATN(gNfcip.lastPFB) && - (nfcip_PNIDec(gNfcip.pni) == nfcip_PBF_PNI(rxPFB))) { - nfcipLogI(" NFCIP(T) wrong PNI, last was ATN reTx \r\n"); - /* Spec says to leave current PNI as is, but will be Inc after Tx, remaining the same */ - gNfcip.pni = nfcip_PNIDec(gNfcip.pni); - - gNfcip.state = NFCIP_ST_TARG_DEP_TX; - return ERR_BUSY; - } else { - /* MISRA 15.7 - Empty else */ - } - } - /*******************************************************************************/ - /* R NACK */ - /*******************************************************************************/ - /* ISO 18092 12.6.1.3.3 When rcv NACK if PNI = prev PNI sent -> reTx */ - else if(nfcip_PFBisRNACK(rxPFB) && (nfcip_PNIDec(gNfcip.pni) == nfcip_PBF_PNI(rxPFB))) { - nfcipLogI(" NFCIP(T) Rcvd NACK \r\n"); - - gNfcip.pni = nfcip_PNIDec(gNfcip.pni); /* Dec so that has the prev PNI */ - - gNfcip.state = NFCIP_ST_TARG_DEP_TX; - return ERR_BUSY; - } else { - nfcipLogI(" NFCIP(T) Unexpected R-PDU \r\n"); - - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore unexpected R-PDU */ - } - } - - /*******************************************************************************/ - /* Process S-PDU */ - /*******************************************************************************/ - if(nfcip_PFBisSPDU(rxPFB)) { - nfcipLogD(" NFCIP(T) Rcvd S-PDU \r\n"); - - /*******************************************************************************/ - /* S ATN */ - /*******************************************************************************/ - /* ISO 18092 12.6.3 Attention */ - if(nfcip_PFBisSATN(rxPFB)) /* If is a S-ATN */ - { - nfcipLogI(" NFCIP(T) Rcvd ATN curPNI: %d \r\n", gNfcip.pni); - EXIT_ON_ERR(ret, nfcipDEPControlMsg(nfcip_PFBSPDU_ATN(), 0)); - return ERR_BUSY; - } - - /*******************************************************************************/ - /* S TO */ - /*******************************************************************************/ - else if(nfcip_PFBisSTO(rxPFB)) /* If is a S-TO (RTOX) */ - { - if(nfcip_PFBisSTO(gNfcip.lastPFBnATN)) { - nfcipLogI(" NFCIP(T) Rcvd TO \r\n"); - - /* Digital 1.1 16.8.4.6 RTOX value in RES different that in REQ -> Protocol Error */ - if(gNfcip.lastRTOX != gNfcip.rxBuf[rxMsgIt++]) { - nfcipLogI(" NFCIP(T) Mismatched RTOX value \r\n"); - - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore unexpected RTOX value */ - } - - /* Clear waiting for RTOX Ack Flag */ - gNfcip.isWait4RTOX = false; - - /* Check if a Tx is already pending */ - if(gNfcip.isTxPending) { - nfcipLogW(" NFCIP(T) Tx pending, go immediately to TX \r\n"); - - gNfcip.state = NFCIP_ST_TARG_DEP_TX; - return ERR_BUSY; - } - - /* Start RTOX timer and change to check state */ - nfcipTimerStart( - gNfcip.RTOXTimer, - nfcipRTOXAdjust( - nfcipConv1FcToMs(gNfcip.lastRTOX * rfalNfcDepWT2RWT(gNfcip.cfg.to)))); - gNfcip.state = NFCIP_ST_TARG_DEP_RTOX; - - return ERR_BUSY; - } - } else { - /* Unexpected S-PDU */ - nfcipLogI( - " NFCIP(T) Unexpected S-PDU \r\n"); /* PRQA S 2880 # MISRA 2.1 - Guard code to prevent unexpected behavior */ - - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore unexpected S-PDU */ - } - } - - /*******************************************************************************/ - /* Process I-PDU */ - /*******************************************************************************/ - if(nfcip_PFBisIPDU(rxPFB)) { - if(gNfcip.pni != nfcip_PBF_PNI(rxPFB)) { - nfcipLogI( - " NFCIP(T) Rcvd IPDU wrong PNI curPNI: %d rxPNI: %d \r\n", - gNfcip.pni, - nfcip_PBF_PNI(rxPFB)); - - /* Digital 1.1 16.12.3.4 - If last send was ATN and rx PNI is minus 1 */ - if(nfcip_PFBisSATN(gNfcip.lastPFB) && - (nfcip_PNIDec(gNfcip.pni) == nfcip_PBF_PNI(rxPFB))) { - /* Spec says to leave current PNI as is, but will be Inc after Data Tx, remaining the same */ - gNfcip.pni = nfcip_PNIDec(gNfcip.pni); - - if(nfcip_PFBisIMI(rxPFB)) { - nfcipLogI( - " NFCIP(T) PNI = prevPNI && ATN before && chaining -> send ACK \r\n"); - EXIT_ON_ERR( - ret, - nfcipDEPControlMsg(nfcip_PFBRPDU_ACK(gNfcip.pni), gNfcip.rxBuf[rxMsgIt++])); - - /* Digital 1.1 16.12.3.4 (...) leave the current PNI unchanged afterwards */ - gNfcip.pni = nfcip_PNIInc(gNfcip.pni); - } else { - nfcipLogI(" NFCIP(T) PNI = prevPNI && ATN before -> reTx last I-PDU \r\n"); - gNfcip.state = NFCIP_ST_TARG_DEP_TX; - } - - return ERR_BUSY; - } - - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - return ERR_BUSY; /* ERR_PROTO - Ignore bad PNI value */ - } - - nfcipLogD(" NFCIP(T) Rcvd IPDU OK PNI: %d \r\n", gNfcip.pni); - - /*******************************************************************************/ - /* Successful data exchange */ - /*******************************************************************************/ - *outActRxLen = ((uint16_t)nfcDepLen - RFAL_NFCDEP_DEP_HEADER - (uint16_t)optHdrLen); - - nfcipClearCounters(); - - if((&gNfcip.rxBuf[gNfcip.rxBufPaylPos] != - &gNfcip.rxBuf[RFAL_NFCDEP_DEP_HEADER + optHdrLen]) && - (*outActRxLen > 0U)) { - ST_MEMMOVE( - &gNfcip.rxBuf[gNfcip.rxBufPaylPos], - &gNfcip.rxBuf[RFAL_NFCDEP_DEP_HEADER + optHdrLen], - *outActRxLen); - } - - /*******************************************************************************/ - /* Check if Initiator is indicating chaining MI */ - /*******************************************************************************/ - if(nfcip_PFBisIMI(rxPFB)) { - gNfcip.isRxChaining = true; - *outIsChaining = true; - - nfcipLogD(" NFCIP(T) Rcvd IPDU OK w MI -> ACK \r\n"); - EXIT_ON_ERR( - ret, nfcipDEPControlMsg(nfcip_PFBRPDU_ACK(gNfcip.pni), gNfcip.rxBuf[rxMsgIt++])); - - gNfcip.pni = nfcip_PNIInc(gNfcip.pni); - - return ERR_AGAIN; /* Send Again signalling to run again, but some chaining data has arrived*/ - } else { - if(gNfcip.isRxChaining) { - nfcipLogI(" NFCIP(T) Rcvd last IPDU chaining finished \r\n"); - } - - /*******************************************************************************/ - /* Reception done, send to DH and start RTOX timer */ - /*******************************************************************************/ - nfcipTimerStart( - gNfcip.RTOXTimer, - nfcipRTOXAdjust(nfcipConv1FcToMs(rfalNfcDepWT2RWT(gNfcip.cfg.to)))); - gNfcip.state = NFCIP_ST_TARG_DEP_RTOX; - - gNfcip.isRxChaining = false; - ret = ERR_NONE; /* Data exchange done */ - } - } - return ret; -} - -/*******************************************************************************/ -static ReturnCode nfcipTx( - rfalNfcDepCmd cmd, - uint8_t* txBuf, - uint8_t* paylBuf, - uint16_t paylLen, - uint8_t pfbData, - uint32_t fwt) { - uint16_t txBufIt; - uint8_t* txBlock; - uint8_t* payloadBuf; - uint8_t pfb; - - if(txBuf == NULL) { - return ERR_PARAM; - } - - payloadBuf = paylBuf; /* MISRA 17.8: Use intermediate variable */ - - if((paylLen == 0U) || (payloadBuf == NULL)) { - payloadBuf = (uint8_t*)&txBuf - [RFAL_NFCDEP_DEPREQ_HEADER_LEN]; /* If not a DEP (no Data) ensure enough space for header */ - } - - txBufIt = 0; - pfb = pfbData; /* MISRA 17.8: Use intermediate variable */ - - txBlock = payloadBuf; /* Point to beginning of the Data, and go backwards */ - - gNfcip.lastCmd = (uint8_t)cmd; /* Store last cmd sent */ - gNfcip.lastPFB = NFCIP_PFB_INVALID; /* Reset last pfb sent */ - - /*******************************************************************************/ - /* Compute outgoing NFCIP message */ - /*******************************************************************************/ - switch(cmd) { - /*******************************************************************************/ - case NFCIP_CMD_ATR_RES: - case NFCIP_CMD_ATR_REQ: - - rfalNfcDepSetNFCID(payloadBuf, gNfcip.cfg.nfcid, gNfcip.cfg.nfcidLen); /* NFCID */ - txBufIt += RFAL_NFCDEP_NFCID3_LEN; - - payloadBuf[txBufIt++] = gNfcip.cfg.did; /* DID */ - payloadBuf[txBufIt++] = gNfcip.cfg.bs; /* BS */ - payloadBuf[txBufIt++] = gNfcip.cfg.br; /* BR */ - - if(cmd == NFCIP_CMD_ATR_RES) { - payloadBuf[txBufIt++] = gNfcip.cfg.to; /* ATR_RES[ TO ] */ - } - - if(gNfcip.cfg.gbLen > 0U) { - payloadBuf[txBufIt++] = nfcip_PPwGB(gNfcip.cfg.lr); /* PP signalling GB */ - ST_MEMCPY( - &payloadBuf[txBufIt], gNfcip.cfg.gb, gNfcip.cfg.gbLen); /* set General Bytes */ - txBufIt += gNfcip.cfg.gbLen; - } else { - payloadBuf[txBufIt++] = rfalNfcDepLR2PP(gNfcip.cfg.lr); /* PP without GB */ - } - - if((txBufIt + RFAL_NFCDEP_CMDTYPE_LEN + RFAL_NFCDEP_CMD_LEN) > - RFAL_NFCDEP_ATRREQ_MAX_LEN) /* Check max ATR length (ATR_REQ = ATR_RES)*/ - { - return ERR_PARAM; - } - break; - - /*******************************************************************************/ - case NFCIP_CMD_WUP_REQ: /* ISO 18092 - 12.5.2.1 */ - - rfalNfcDepSetNFCID((payloadBuf), gNfcip.cfg.nfcid, gNfcip.cfg.nfcidLen); /* NFCID */ - txBufIt += RFAL_NFCDEP_NFCID3_LEN; - - *(--txBlock) = gNfcip.cfg.did; /* DID */ - break; - - /*******************************************************************************/ - case NFCIP_CMD_WUP_RES: /* ISO 18092 - 12.5.2.2 */ - case NFCIP_CMD_PSL_REQ: - case NFCIP_CMD_PSL_RES: - - *(--txBlock) = gNfcip.cfg.did; /* DID */ - break; - - /*******************************************************************************/ - case NFCIP_CMD_RLS_REQ: - case NFCIP_CMD_RLS_RES: - case NFCIP_CMD_DSL_REQ: - case NFCIP_CMD_DSL_RES: - - /* Digital 1.0 - 14.8.1.1 & 14.9.1.1 & 14.10.1.1 Only add DID if not 0 */ - if(gNfcip.cfg.did != RFAL_NFCDEP_DID_NO) { - *(--txBlock) = gNfcip.cfg.did; /* DID */ - } - break; - - /*******************************************************************************/ - case NFCIP_CMD_DEP_REQ: - case NFCIP_CMD_DEP_RES: - - /* Compute optional PFB bits */ - if(gNfcip.cfg.did != RFAL_NFCDEP_DID_NO) { - pfb |= NFCIP_PFB_DID_BIT; - } - if(gNfcip.cfg.nad != RFAL_NFCDEP_NAD_NO) { - pfb |= NFCIP_PFB_NAD_BIT; - } - if((gNfcip.isTxChaining) && (nfcip_PFBisIPDU(pfb))) { - pfb |= NFCIP_PFB_MI_BIT; - } - - /* Store PFB for future handling */ - gNfcip.lastPFB = pfb; /* store PFB sent */ - - if(!nfcip_PFBisSATN(pfb)) { - gNfcip.lastPFBnATN = pfb; /* store last PFB different then ATN */ - } - - /* Add NAD if it is to be supported */ - if(gNfcip.cfg.nad != RFAL_NFCDEP_NAD_NO) { - *(--txBlock) = gNfcip.cfg.nad; /* NAD */ - } - - /* Digital 1.0 - 14.8.1.1 & 14.8.1.1 Only add DID if not 0 */ - if(gNfcip.cfg.did != RFAL_NFCDEP_DID_NO) { - *(--txBlock) = gNfcip.cfg.did; /* DID */ - } - - *(--txBlock) = pfb; /* PFB */ - - /* NCI 1.0 - Check if Empty frames are allowed */ - if((paylLen == 0U) && nfcipIsEmptyDEPDisabled(gNfcip.cfg.oper) && nfcip_PFBisIPDU(pfb)) { - return ERR_PARAM; - } - break; - - /*******************************************************************************/ - default: - return ERR_PARAM; - } - - /*******************************************************************************/ - /* Prepend Header */ - /*******************************************************************************/ - *(--txBlock) = (uint8_t)cmd; /* CMD */ - *(--txBlock) = (uint8_t)(nfcipCmdIsReq(cmd) ? NFCIP_REQ : NFCIP_RES); /* CMDType */ - - txBufIt += - paylLen + - (uint16_t)((uint32_t)payloadBuf - (uint32_t)txBlock); /* Calculate overall buffer size */ - - if(txBufIt > gNfcip.fsc) /* Check if msg length violates the maximum payload size FSC */ - { - return ERR_NOTSUPP; - } - - /*******************************************************************************/ - return nfcipDataTx(txBlock, txBufIt, fwt); -} - -/* - ****************************************************************************** - * GLOBAL FUNCTIONS - ****************************************************************************** - */ - -/*******************************************************************************/ -static void nfcipConfig(const rfalNfcDepConfigs* cfg) { - if(cfg == NULL) { - return; - } - - ST_MEMCPY(&gNfcip.cfg, cfg, sizeof(rfalNfcDepConfigs)); /* Copy given config to local */ - - gNfcip.cfg.to = - MIN(RFAL_NFCDEP_WT_TRG_MAX, gNfcip.cfg.to); /* Ensure proper WT value */ - gNfcip.cfg.did = nfcip_DIDMax(gNfcip.cfg.did); /* Ensure proper DID value */ - gNfcip.fsc = rfalNfcDepLR2FS(gNfcip.cfg.lr); /* Calculate FSC based on given LR */ - - gNfcip.state = - ((gNfcip.cfg.role == RFAL_NFCDEP_ROLE_TARGET) ? NFCIP_ST_TARG_WAIT_ATR : - NFCIP_ST_INIT_IDLE); -} - -/*******************************************************************************/ -static ReturnCode nfcipRun(uint16_t* outActRxLen, bool* outIsChaining) { - ReturnCode ret; - - ret = ERR_SYNTAX; - - nfcipLogD(" NFCIP Run() state: %d \r\n", gNfcip.state); - - switch(gNfcip.state) { - /*******************************************************************************/ - case NFCIP_ST_IDLE: - case NFCIP_ST_INIT_DEP_IDLE: - case NFCIP_ST_TARG_DEP_IDLE: - case NFCIP_ST_TARG_DEP_SLEEP: - return ERR_NONE; - - /*******************************************************************************/ - case NFCIP_ST_INIT_DEP_TX: - - nfcipLogD(" NFCIP(I) Tx PNI: %d txLen: %d \r\n", gNfcip.pni, gNfcip.txBufLen); - ret = nfcipTx( - NFCIP_CMD_DEP_REQ, - gNfcip.txBuf, - &gNfcip.txBuf[gNfcip.txBufPaylPos], - gNfcip.txBufLen, - nfcip_PFBIPDU(gNfcip.pni), - (gNfcip.cfg.fwt + gNfcip.cfg.dFwt)); - - switch(ret) { - case ERR_NONE: - gNfcip.state = NFCIP_ST_INIT_DEP_RX; - break; - - case ERR_PARAM: - default: - gNfcip.state = NFCIP_ST_INIT_DEP_IDLE; - return ret; - } - /* fall through */ - - /*******************************************************************************/ - case NFCIP_ST_INIT_DEP_RX: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - ret = nfcipDataRx(false); - - if(ret != ERR_BUSY) { - ret = nfcipInitiatorHandleDEP(ret, *gNfcip.rxRcvdLen, outActRxLen, outIsChaining); - } - - break; - - /*******************************************************************************/ - case NFCIP_ST_TARG_DEP_RTOX: - - if(!nfcipTimerisExpired(gNfcip.RTOXTimer)) /* Do nothing until RTOX timer has expired */ - { - return ERR_BUSY; - } - - /* If we cannot send a RTOX raise a Timeout error so that we do not - * hold the field On forever in AP2P */ - if(nfcipIsRTOXReqDisabled(gNfcip.cfg.oper)) { - /* We should reEnable Rx, and measure time between our field Off to - * either report link loss or recover #287 */ - nfcipLogI(" NFCIP(T) RTOX not sent due to config, NOT reenabling Rx \r\n"); - return ERR_TIMEOUT; - } - - if(gNfcip.cntRTOXRetrys++ > - RFAL_NFCDEP_MAX_RTOX_RETRYS) /* Check maximum consecutive RTOX requests */ - { - return ERR_PROTO; - } - - nfcipLogI(" NFCIP(T) RTOX sent \r\n"); - - gNfcip.lastRTOX = - nfcip_RTOXTargMax(gNfcip.cfg.to); /* Calculate requested RTOX value, and send it */ - EXIT_ON_ERR(ret, nfcipDEPControlMsg(nfcip_PFBSPDU_TO(), gNfcip.lastRTOX)); - - /* Set waiting for RTOX Ack Flag */ - gNfcip.isWait4RTOX = true; - - gNfcip.state = NFCIP_ST_TARG_DEP_RX; /* Go back to Rx to process RTOX ack */ - return ERR_BUSY; - - /*******************************************************************************/ - case NFCIP_ST_TARG_DEP_TX: - - nfcipLogD(" NFCIP(T) Tx PNI: %d txLen: %d \r\n", gNfcip.pni, gNfcip.txBufLen); - ret = nfcipTx( - NFCIP_CMD_DEP_RES, - gNfcip.txBuf, - &gNfcip.txBuf[gNfcip.txBufPaylPos], - gNfcip.txBufLen, - nfcip_PFBIPDU(gNfcip.pni), - NFCIP_NO_FWT); - - /* Clear flags */ - gNfcip.isTxPending = false; - gNfcip.isWait4RTOX = false; - - /* Digital 1.0 14.12.3.4 Increment the current PNI after Tx */ - gNfcip.pni = nfcip_PNIInc(gNfcip.pni); - - switch(ret) { - case ERR_NONE: - gNfcip.state = NFCIP_ST_TARG_DEP_RX; /* All OK, goto Rx state */ - break; - - case ERR_PARAM: - default: - gNfcip.state = NFCIP_ST_TARG_DEP_IDLE; /* Upon Tx error, goto IDLE state */ - return ret; - } - /* fall through */ - - /*******************************************************************************/ - case NFCIP_ST_TARG_DEP_RX: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - if(gNfcip.isReqPending) /* if already has Data should be from a DEP from nfcipTargetHandleActivation() */ - { - nfcipLogD(" NFCIP(T) Skipping Rx Using DEP from Activation \r\n"); - - gNfcip.isReqPending = false; - ret = ERR_NONE; - } else { - ret = nfcipDataRx(false); - } - - if(ret != ERR_BUSY) { - ret = nfcipTargetHandleRX(ret, outActRxLen, outIsChaining); - } - - break; - - /*******************************************************************************/ - default: - /* MISRA 16.4: no empty default statement (a comment being enough) */ - break; - } - return ret; -} - -/*******************************************************************************/ -void rfalNfcDepSetDeactivatingCallback(rfalNfcDepDeactCallback pFunc) { - gNfcip.isDeactivating = pFunc; -} - -/*******************************************************************************/ -void rfalNfcDepInitialize(void) { - nfcipLogD(" NFCIP Ini() \r\n"); - - gNfcip.state = NFCIP_ST_IDLE; - gNfcip.isDeactivating = NULL; - - gNfcip.isTxPending = false; - gNfcip.isWait4RTOX = false; - gNfcip.isReqPending = false; - - gNfcip.cfg.oper = - (RFAL_NFCDEP_OPER_FULL_MI_DIS | RFAL_NFCDEP_OPER_EMPTY_DEP_EN | RFAL_NFCDEP_OPER_ATN_EN | - RFAL_NFCDEP_OPER_RTOX_REQ_EN); - - gNfcip.cfg.did = RFAL_NFCDEP_DID_NO; - gNfcip.cfg.nad = RFAL_NFCDEP_NAD_NO; - - gNfcip.cfg.br = RFAL_NFCDEP_Bx_NO_HIGH_BR; - gNfcip.cfg.bs = RFAL_NFCDEP_Bx_NO_HIGH_BR; - - gNfcip.cfg.lr = RFAL_NFCDEP_LR_254; - gNfcip.fsc = rfalNfcDepLR2FS(gNfcip.cfg.lr); - - gNfcip.cfg.gbLen = 0; - - gNfcip.cfg.fwt = RFAL_NFCDEP_MAX_FWT; - gNfcip.cfg.dFwt = RFAL_NFCDEP_MAX_FWT; - - gNfcip.pni = 0; - - /* Destroy any ongoing RTOX timer*/ - nfcipTimerDestroy(gNfcip.RTOXTimer); - gNfcip.RTOXTimer = 0U; - - gNfcip.PDUTxPos = 0; - gNfcip.PDURxPos = 0; - gNfcip.PDUParam.rxLen = NULL; - gNfcip.PDUParam.rxBuf = NULL; - gNfcip.PDUParam.txBuf = NULL; - - nfcipClearCounters(); -} - -/*******************************************************************************/ -static void nfcipSetDEPParams(const rfalNfcDepDEPParams* DEPParams) { - nfcipLogD(" NFCIP SetDEP() txLen: %d \r\n", DEPParams->txBufLen); - - gNfcip.isTxChaining = DEPParams->txChaining; - gNfcip.txBuf = DEPParams->txBuf; - gNfcip.rxBuf = DEPParams->rxBuf; - gNfcip.txBufLen = DEPParams->txBufLen; - gNfcip.rxBufLen = DEPParams->rxBufLen; - gNfcip.txBufPaylPos = DEPParams->txBufPaylPos; - gNfcip.rxBufPaylPos = DEPParams->rxBufPaylPos; - - if(DEPParams->did != RFAL_NFCDEP_DID_KEEP) { - gNfcip.cfg.did = nfcip_DIDMax(DEPParams->did); - } - - gNfcip.cfg.fwt = DEPParams->fwt; - gNfcip.cfg.dFwt = DEPParams->dFwt; - gNfcip.fsc = DEPParams->fsc; - - if(gNfcip.cfg.role == RFAL_NFCDEP_ROLE_TARGET) { - /* If there's any data to be sent go for Tx */ - if(DEPParams->txBufLen > 0U) { - /* Ensure that an RTOX Ack is not being expected at moment */ - if(!gNfcip.isWait4RTOX) { - gNfcip.state = NFCIP_ST_TARG_DEP_TX; - return; - } else { - /* If RTOX Ack is expected, signal a pending Tx to be transmitted right after */ - gNfcip.isTxPending = true; - nfcipLogW(" NFCIP(T) Waiting RTOX, queueing outgoing DEP Block \r\n"); - } - } - - /*Digital 1.0 14.12.4.1 In target mode the first PDU MUST be sent by the Initiator */ - gNfcip.state = NFCIP_ST_TARG_DEP_RX; - return; - } - - /* New data TxRx request clear previous error counters for consecutive TxRx without reseting communication/protocol layer*/ - nfcipClearCounters(); - - gNfcip.state = NFCIP_ST_INIT_DEP_TX; -} - -/*******************************************************************************/ -bool rfalNfcDepTargetRcvdATR(void) { - return ( - (gNfcip.cfg.role == RFAL_NFCDEP_ROLE_TARGET) && nfcipIsTarget(gNfcip.state) && - (gNfcip.state > NFCIP_ST_TARG_WAIT_ATR)); -} - -/*******************************************************************************/ -bool rfalNfcDepIsAtrReq(const uint8_t* buf, uint16_t bufLen, uint8_t* nfcid3) { - uint8_t msgIt; - - msgIt = 0; - - if((bufLen < RFAL_NFCDEP_ATRREQ_MIN_LEN) || (bufLen > RFAL_NFCDEP_ATRREQ_MAX_LEN)) { - return false; - } - - if(buf[msgIt++] != NFCIP_REQ) { - return false; - } - - if(buf[msgIt++] != (uint8_t)NFCIP_CMD_ATR_REQ) { - return false; - } - - /* Output NFID3 if requested */ - if(nfcid3 != NULL) { - ST_MEMCPY(nfcid3, &buf[RFAL_NFCDEP_ATR_REQ_NFCID3_POS], RFAL_NFCDEP_NFCID3_LEN); - } - - return true; -} - -/*******************************************************************************/ -static ReturnCode nfcipTargetHandleActivation(rfalNfcDepDevice* nfcDepDev, uint8_t* outBRS) { - ReturnCode ret; - uint8_t msgIt; - uint8_t txBuf[RFAL_NFCDEP_HEADER_PAD + NFCIP_PSLRES_LEN]; - - /*******************************************************************************/ - /* Check if we are in correct state */ - /*******************************************************************************/ - if(gNfcip.state != NFCIP_ST_TARG_WAIT_ACTV) { - return ERR_WRONG_STATE; - } - - /*******************************************************************************/ - /* Check required parameters */ - /*******************************************************************************/ - if(outBRS == NULL) { - return ERR_PARAM; - } - - /*******************************************************************************/ - /* Wait and process incoming cmd (PSL / DEP) */ - /*******************************************************************************/ - ret = nfcipDataRx(false); - - if(ret != ERR_NONE) { - return ret; - } - - msgIt = 0; - *outBRS = RFAL_NFCDEP_BRS_MAINTAIN; /* set out BRS to be maintained */ - - msgIt++; /* Skip LEN byte */ - - if(gNfcip.rxBuf[msgIt++] != NFCIP_REQ) { - return ERR_PROTO; - } - - if(gNfcip.rxBuf[msgIt] == (uint8_t)NFCIP_CMD_PSL_REQ) { - msgIt++; - - if(gNfcip.rxBuf[msgIt++] != gNfcip.cfg.did) /* Checking DID */ - { - return ERR_PROTO; - } - - nfcipLogI(" NFCIP(T) PSL REQ rcvd \r\n"); - - *outBRS = gNfcip.rxBuf[msgIt++]; /* assign output BRS value */ - - /* Store FSL(LR) and update current config */ - gNfcip.cfg.lr = (gNfcip.rxBuf[msgIt++] & RFAL_NFCDEP_LR_VAL_MASK); - gNfcip.fsc = rfalNfcDepLR2FS(gNfcip.cfg.lr); - - /*******************************************************************************/ - /* Update NFC-DDE Device info */ - if(nfcDepDev != NULL) { - /* Update Bitrate info */ - /* PRQA S 4342 2 # MISRA 10.5 - Layout of enum rfalBitRate and definition of rfalNfcDepBRS2DSI guarantee no invalid enum values to be created */ - nfcDepDev->info.DSI = (rfalBitRate)rfalNfcDepBRS2DSI( - *outBRS); /* DSI codes the bit rate from Initiator to Target */ - nfcDepDev->info.DRI = (rfalBitRate)rfalNfcDepBRS2DRI( - *outBRS); /* DRI codes the bit rate from Target to Initiator */ - - /* Update Length Reduction and Frame Size */ - nfcDepDev->info.LR = gNfcip.cfg.lr; - nfcDepDev->info.FS = gNfcip.fsc; - - /* Update PPi byte */ - nfcDepDev->activation.Initiator.ATR_REQ.PPi &= ~RFAL_NFCDEP_PP_LR_MASK; - nfcDepDev->activation.Initiator.ATR_REQ.PPi |= rfalNfcDepLR2PP(gNfcip.cfg.lr); - } - - rfalSetBitRate(RFAL_BR_KEEP, gNfcip.nfcDepDev->info.DSI); - - EXIT_ON_ERR(ret, nfcipTx(NFCIP_CMD_PSL_RES, txBuf, NULL, 0, 0, NFCIP_NO_FWT)); - } else { - if(gNfcip.rxBuf[msgIt] == (uint8_t)NFCIP_CMD_DEP_REQ) { - msgIt++; - - /*******************************************************************************/ - /* Digital 1.0 14.12.3.1 PNI must be initialized to 0 */ - if(nfcip_PBF_PNI(gNfcip.rxBuf[msgIt]) != 0U) { - return ERR_PROTO; - } - - /*******************************************************************************/ - /* Digital 1.0 14.8.2.1 check if DID is expected and match -> Protocol Error */ - if(nfcip_PFBhasDID(gNfcip.rxBuf[msgIt])) { - if(gNfcip.rxBuf[++msgIt] != gNfcip.cfg.did) { - return ERR_PROTO; - } - } else if(gNfcip.cfg.did != RFAL_NFCDEP_DID_NO) /* DID expected but not rcv */ - { - return ERR_PROTO; - } else { - /* MISRA 15.7 - Empty else */ - } - } - - /* Signal Request pending to be digested on normal Handling (DEP_REQ, DSL_REQ, RLS_REQ) */ - gNfcip.isReqPending = true; - } - - gNfcip.state = NFCIP_ST_TARG_DEP_RX; - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode - rfalNfcDepATR(const rfalNfcDepAtrParam* param, rfalNfcDepAtrRes* atrRes, uint8_t* atrResLen) { - ReturnCode ret; - rfalNfcDepConfigs cfg; - uint16_t rxLen; - uint8_t msgIt; - uint8_t txBuf[RFAL_NFCDEP_ATRREQ_MAX_LEN]; - uint8_t rxBuf[NFCIP_ATRRES_BUF_LEN]; - - if((param == NULL) || (atrRes == NULL) || (atrResLen == NULL)) { - return ERR_PARAM; - } - - /*******************************************************************************/ - /* Configure NFC-DEP layer */ - /*******************************************************************************/ - - cfg.did = param->DID; - cfg.nad = param->NAD; - cfg.fwt = RFAL_NFCDEP_MAX_FWT; - cfg.dFwt = RFAL_NFCDEP_MAX_FWT; - cfg.br = param->BR; - cfg.bs = param->BS; - cfg.lr = param->LR; - cfg.to = RFAL_NFCDEP_WT_TRG_MAX; /* Not used in Initiator mode */ - - cfg.gbLen = param->GBLen; - if(cfg.gbLen > 0U) /* MISRA 21.18 */ - { - ST_MEMCPY(cfg.gb, param->GB, cfg.gbLen); - } - - cfg.nfcidLen = param->nfcidLen; - if(cfg.nfcidLen > 0U) /* MISRA 21.18 */ - { - ST_MEMCPY(cfg.nfcid, param->nfcid, cfg.nfcidLen); - } - - cfg.role = RFAL_NFCDEP_ROLE_INITIATOR; - cfg.oper = param->operParam; - cfg.commMode = param->commMode; - - rfalNfcDepInitialize(); - nfcipConfig(&cfg); - - /*******************************************************************************/ - /* Send ATR_REQ */ - /*******************************************************************************/ - - EXIT_ON_ERR( - ret, - nfcipTxRx( - NFCIP_CMD_ATR_REQ, - txBuf, - nfcipRWTActivation(), - NULL, - 0, - rxBuf, - NFCIP_ATRRES_BUF_LEN, - &rxLen)); - - /*******************************************************************************/ - /* ATR sent, check response */ - /*******************************************************************************/ - msgIt = 0; - rxLen = ((uint16_t)rxBuf[msgIt++] - RFAL_NFCDEP_LEN_LEN); /* use LEN byte */ - - if((rxLen < RFAL_NFCDEP_ATRRES_MIN_LEN) || - (rxLen > RFAL_NFCDEP_ATRRES_MAX_LEN)) /* Checking length: ATR_RES */ - { - return ERR_PROTO; - } - - if(rxBuf[msgIt++] != NFCIP_RES) /* Checking if is a response*/ - { - return ERR_PROTO; - } - - if(rxBuf[msgIt++] != (uint8_t)NFCIP_CMD_ATR_RES) /* Checking if is a ATR RES */ - { - return ERR_PROTO; - } - - ST_MEMCPY((uint8_t*)atrRes, (rxBuf + RFAL_NFCDEP_LEN_LEN), rxLen); - *atrResLen = (uint8_t)rxLen; - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepPSL(uint8_t BRS, uint8_t FSL) { - ReturnCode ret; - uint16_t rxLen; - uint8_t msgIt; - uint8_t txBuf[NFCIP_PSLREQ_LEN + NFCIP_PSLPAY_LEN]; - uint8_t rxBuf[NFCIP_PSLRES_LEN]; - - msgIt = NFCIP_PSLREQ_LEN; - - txBuf[msgIt++] = BRS; - txBuf[msgIt++] = FSL; - - /*******************************************************************************/ - /* Send PSL REQ and wait for response */ - /*******************************************************************************/ - EXIT_ON_ERR( - ret, - nfcipTxRx( - NFCIP_CMD_PSL_REQ, - txBuf, - nfcipRWTActivation(), - &txBuf[NFCIP_PSLREQ_LEN], - (msgIt - NFCIP_PSLREQ_LEN), - rxBuf, - NFCIP_PSLRES_LEN, - &rxLen)); - - /*******************************************************************************/ - /* PSL sent, check response */ - /*******************************************************************************/ - msgIt = 0; - rxLen = (uint16_t)(rxBuf[msgIt++]); /* use LEN byte */ - - if(rxLen < NFCIP_PSLRES_LEN) /* Checking length: LEN + RLS_RES */ - { - return ERR_PROTO; - } - - if(rxBuf[msgIt++] != NFCIP_RES) /* Checking if is a response */ - { - return ERR_PROTO; - } - - if(rxBuf[msgIt++] != (uint8_t)NFCIP_CMD_PSL_RES) /* Checking if is a PSL RES */ - { - return ERR_PROTO; - } - - if(rxBuf[msgIt++] != gNfcip.cfg.did) /* Checking DID */ - { - return ERR_PROTO; - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepDSL(void) { - ReturnCode ret; - uint8_t txBuf[RFAL_NFCDEP_HEADER_PAD + NFCIP_DSLREQ_LEN]; - uint8_t rxBuf[NFCIP_DSLRES_LEN]; - uint8_t rxMsgIt; - uint16_t rxLen = 0; - - if(gNfcip.cfg.role == RFAL_NFCDEP_ROLE_TARGET) { - return ERR_NONE; /* Target has no deselect procedure */ - } - - /* Repeating a DSL REQ is optional, not doing it */ - EXIT_ON_ERR( - ret, - nfcipTxRx( - NFCIP_CMD_DSL_REQ, - txBuf, - nfcipRWTActivation(), - NULL, - 0, - rxBuf, - (uint16_t)sizeof(rxBuf), - &rxLen)); - - /*******************************************************************************/ - rxMsgIt = 0; - - if(rxBuf[rxMsgIt++] < NFCIP_DSLRES_MIN) /* Checking length: LEN + DSL_RES */ - { - return ERR_PROTO; - } - - if(rxBuf[rxMsgIt++] != NFCIP_RES) /* Checking if is a response */ - { - return ERR_PROTO; - } - - if(rxBuf[rxMsgIt++] != (uint8_t)NFCIP_CMD_DSL_RES) /* Checking if is DSL RES */ - { - return ERR_PROTO; - } - - if(gNfcip.cfg.did != RFAL_NFCDEP_DID_NO) { - if(rxBuf[rxMsgIt++] != gNfcip.cfg.did) { - return ERR_PROTO; - } - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepRLS(void) { - ReturnCode ret; - uint8_t txBuf[RFAL_NFCDEP_HEADER_PAD + NFCIP_RLSREQ_LEN]; - uint8_t rxBuf[NFCIP_RLSRES_LEN]; - uint8_t rxMsgIt; - uint16_t rxLen = 0; - - if(gNfcip.cfg.role == RFAL_NFCDEP_ROLE_TARGET) /* Target has no release procedure */ - { - return ERR_NONE; - } - - /* Repeating a RLS REQ is optional, not doing it */ - EXIT_ON_ERR( - ret, - nfcipTxRx( - NFCIP_CMD_RLS_REQ, - txBuf, - nfcipRWTActivation(), - NULL, - 0, - rxBuf, - (uint16_t)sizeof(rxBuf), - &rxLen)); - - /*******************************************************************************/ - rxMsgIt = 0; - - if(rxBuf[rxMsgIt++] < NFCIP_RLSRES_MIN) /* Checking length: LEN + RLS_RES */ - { - return ERR_PROTO; - } - - if(rxBuf[rxMsgIt++] != NFCIP_RES) /* Checking if is a response */ - { - return ERR_PROTO; - } - - if(rxBuf[rxMsgIt++] != (uint8_t)NFCIP_CMD_RLS_RES) /* Checking if is RLS RES */ - { - return ERR_PROTO; - } - - if(gNfcip.cfg.did != RFAL_NFCDEP_DID_NO) { - if(rxBuf[rxMsgIt++] != gNfcip.cfg.did) { - return ERR_PROTO; - } - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepInitiatorHandleActivation( - rfalNfcDepAtrParam* param, - rfalBitRate desiredBR, - rfalNfcDepDevice* nfcDepDev) { - ReturnCode ret; - uint8_t maxRetyrs; - uint8_t PSL_BRS; - uint8_t PSL_FSL; - bool sendPSL; - - if((param == NULL) || (nfcDepDev == NULL)) { - return ERR_PARAM; - } - - param->NAD = RFAL_NFCDEP_NAD_NO; /* Digital 1.1 16.6.2.9 Initiator SHALL NOT use NAD */ - maxRetyrs = NFCIP_ATR_RETRY_MAX; - - /*******************************************************************************/ - /* Send ATR REQ and wait for response */ - /*******************************************************************************/ - do { /* Upon transmission error ATR REQ should be retried */ - - ret = rfalNfcDepATR( - param, - &nfcDepDev->activation.Target.ATR_RES, - &nfcDepDev->activation.Target.ATR_RESLen); - - if(nfcipIsTransmissionError(ret)) { - continue; - } - break; - } while((maxRetyrs--) != 0U); - - if(ret != ERR_NONE) { - return ret; - } - - /*******************************************************************************/ - /* Compute NFC-DEP device with ATR_RES */ - /*******************************************************************************/ - nfcDepDev->info.GBLen = (nfcDepDev->activation.Target.ATR_RESLen - RFAL_NFCDEP_ATRRES_MIN_LEN); - nfcDepDev->info.DID = nfcDepDev->activation.Target.ATR_RES.DID; - nfcDepDev->info.NAD = - RFAL_NFCDEP_NAD_NO; /* Digital 1.1 16.6.3.11 Initiator SHALL ignore b1 of PPt */ - nfcDepDev->info.LR = rfalNfcDepPP2LR(nfcDepDev->activation.Target.ATR_RES.PPt); - nfcDepDev->info.FS = rfalNfcDepLR2FS(nfcDepDev->info.LR); - nfcDepDev->info.WT = (nfcDepDev->activation.Target.ATR_RES.TO & RFAL_NFCDEP_WT_MASK); - nfcDepDev->info.FWT = rfalNfcDepCalculateRWT(nfcDepDev->info.WT); - nfcDepDev->info.dFWT = RFAL_NFCDEP_WT_DELTA; - - rfalGetBitRate(&nfcDepDev->info.DSI, &nfcDepDev->info.DRI); - - /*******************************************************************************/ - /* Check if a PSL needs to be sent */ - /*******************************************************************************/ - sendPSL = false; - PSL_BRS = rfalNfcDepDx2BRS( - nfcDepDev->info.DSI); /* Set current bit rate divisor on both directions */ - PSL_FSL = nfcDepDev->info.LR; /* Set current Frame Size */ - - /* Activity 1.0 9.4.4.15 & 9.4.6.3 NFC-DEP Activation PSL - * Activity 2.0 9.4.4.17 & 9.4.6.6 NFC-DEP Activation PSL - * - * PSL_REQ shall only be sent if desired bit rate is different from current (Activity 1.0) - * PSL_REQ shall be sent to update LR or bit rate (Activity 2.0) - * */ - -#if 0 /* PSL due to LR is disabled, can be enabled if desired*/ - /*******************************************************************************/ - /* Check Frame Size */ - /*******************************************************************************/ - if( gNfcip.cfg.lr < nfcDepDev->info.LR ) /* If our Length reduction is smaller */ - { - sendPSL = true; - - nfcDepDev->info.LR = MIN( nfcDepDev->info.LR, gNfcip.cfg.lr ); - - gNfcip.cfg.lr = nfcDepDev->info.LR; /* Update nfcip LR to be used */ - gNfcip.fsc = rfalNfcDepLR2FS( gNfcip.cfg.lr ); /* Update nfcip FSC to be used */ - - PSL_FSL = gNfcip.cfg.lr; /* Set LR to be sent */ - - nfcipLogI( " NFCIP(I) Frame Size differ, PSL new fsc: %d \r\n", gNfcip.fsc ); - } -#endif - - /*******************************************************************************/ - /* Check Baud rates */ - /*******************************************************************************/ - if((nfcDepDev->info.DSI != desiredBR) && - (desiredBR != RFAL_BR_KEEP)) /* if desired BR is different */ - { - if(nfcipDxIsSupported( - (uint8_t)desiredBR, - nfcDepDev->activation.Target.ATR_RES.BRt, - nfcDepDev->activation.Target.ATR_RES - .BSt)) /* if desired BR is supported */ /* MISRA 13.5 */ - { - sendPSL = true; - PSL_BRS = rfalNfcDepDx2BRS(desiredBR); - - nfcipLogI(" NFCIP(I) BR differ, PSL BR: 0x%02X \r\n", PSL_BRS); - } - } - - /*******************************************************************************/ - if(sendPSL) { - /*******************************************************************************/ - /* Send PSL REQ and wait for response */ - /*******************************************************************************/ - EXIT_ON_ERR(ret, rfalNfcDepPSL(PSL_BRS, PSL_FSL)); - - /* Check if bit rate has been changed */ - if(nfcDepDev->info.DSI != desiredBR) { - /* Check if device was in Passive NFC-A and went to higher bit rates, use NFC-F */ - if((nfcDepDev->info.DSI == RFAL_BR_106) && - (gNfcip.cfg.commMode == RFAL_NFCDEP_COMM_PASSIVE)) { -#if RFAL_FEATURE_NFCF - /* If Passive initialize NFC-F module */ - rfalNfcfPollerInitialize(desiredBR); -#else /* RFAL_FEATURE_NFCF */ - return ERR_NOTSUPP; -#endif /* RFAL_FEATURE_NFCF */ - } - - nfcDepDev->info.DRI = desiredBR; /* DSI Bit Rate coding from Initiator to Target */ - nfcDepDev->info.DSI = desiredBR; /* DRI Bit Rate coding from Target to Initiator */ - - rfalSetBitRate(nfcDepDev->info.DSI, nfcDepDev->info.DRI); - } - - return ERR_NONE; /* PSL has been sent */ - } - - return ERR_NONE; /* No PSL has been sent */ -} - -/*******************************************************************************/ -uint32_t rfalNfcDepCalculateRWT(uint8_t wt) { - /* Digital 1.0 14.6.3.8 & Digital 1.1 16.6.3.9 */ - /* Digital 1.1 16.6.3.9 treat all RFU values as WT=14 */ - uint8_t responseWaitTime = MIN(RFAL_NFCDEP_WT_INI_MAX, wt); - - return (uint32_t)rfalNfcDepWT2RWT(responseWaitTime); -} - -/*******************************************************************************/ -static ReturnCode nfcipDataTx(uint8_t* txBuf, uint16_t txBufLen, uint32_t fwt) { - return rfalTransceiveBlockingTx( - txBuf, - txBufLen, - gNfcip.rxBuf, - gNfcip.rxBufLen, - gNfcip.rxRcvdLen, - (RFAL_TXRX_FLAGS_DEFAULT | (uint32_t)RFAL_TXRX_FLAGS_NFCIP1_ON), - ((fwt == NFCIP_NO_FWT) ? RFAL_FWT_NONE : fwt)); -} - -/*******************************************************************************/ -static ReturnCode nfcipDataRx(bool blocking) { - ReturnCode ret; - - /* Perform Rx either blocking or non-blocking */ - if(blocking) { - ret = rfalTransceiveBlockingRx(); - } else { - ret = rfalGetTransceiveStatus(); - } - - if(ret != ERR_BUSY) { - if(gNfcip.rxRcvdLen != NULL) { - (*gNfcip.rxRcvdLen) = rfalConvBitsToBytes(*gNfcip.rxRcvdLen); - - if((ret == ERR_NONE) && (gNfcip.rxBuf != NULL)) { - /* Digital 1.1 16.4.1.3 - Length byte LEN SHALL have a value between 3 and 255 -> otherwise treat as Transmission Error * - * - Ensure that actual received and frame length do match, otherwise treat as Transmission error */ - if((*gNfcip.rxRcvdLen != (uint16_t)*gNfcip.rxBuf) || - (*gNfcip.rxRcvdLen < RFAL_NFCDEP_LEN_MIN) || - (*gNfcip.rxRcvdLen > RFAL_NFCDEP_LEN_MAX)) { - return ERR_FRAMING; - } - } - } - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepListenStartActivation( - const rfalNfcDepTargetParam* param, - const uint8_t* atrReq, - uint16_t atrReqLength, - rfalNfcDepListenActvParam rxParam) { - ReturnCode ret; - rfalNfcDepConfigs cfg; - - if((param == NULL) || (atrReq == NULL) || (rxParam.rxLen == NULL)) { - return ERR_PARAM; - } - - /*******************************************************************************/ - /* Check whether is a valid ATR_REQ Compute NFC-DEP device */ - if(!rfalNfcDepIsAtrReq(atrReq, atrReqLength, NULL)) { - return ERR_PARAM; - } - - rxParam.nfcDepDev->activation.Initiator.ATR_REQLen = - (uint8_t)atrReqLength; /* nfcipIsAtrReq() is already checking Min and Max buffer lengths */ - if(atrReqLength > 0U) /* MISRA 21.18 */ - { - ST_MEMCPY( - (uint8_t*)&rxParam.nfcDepDev->activation.Initiator.ATR_REQ, atrReq, atrReqLength); - } - - rxParam.nfcDepDev->info.GBLen = (uint8_t)(atrReqLength - RFAL_NFCDEP_ATRREQ_MIN_LEN); - rxParam.nfcDepDev->info.DID = rxParam.nfcDepDev->activation.Initiator.ATR_REQ.DID; - rxParam.nfcDepDev->info.NAD = - RFAL_NFCDEP_NAD_NO; /* Digital 1.1 16.6.2.9 Initiator SHALL NOT use NAD */ - rxParam.nfcDepDev->info.LR = - rfalNfcDepPP2LR(rxParam.nfcDepDev->activation.Initiator.ATR_REQ.PPi); - rxParam.nfcDepDev->info.FS = rfalNfcDepLR2FS(rxParam.nfcDepDev->info.LR); - rxParam.nfcDepDev->info.WT = 0; - rxParam.nfcDepDev->info.FWT = NFCIP_NO_FWT; - rxParam.nfcDepDev->info.dFWT = NFCIP_NO_FWT; - - rfalGetBitRate(&rxParam.nfcDepDev->info.DSI, &rxParam.nfcDepDev->info.DRI); - - /* Store Device Info location, updated upon a PSL */ - gNfcip.nfcDepDev = rxParam.nfcDepDev; - - /*******************************************************************************/ - cfg.did = rxParam.nfcDepDev->activation.Initiator.ATR_REQ.DID; - cfg.nad = RFAL_NFCDEP_NAD_NO; - - cfg.fwt = RFAL_NFCDEP_MAX_FWT; - cfg.dFwt = RFAL_NFCDEP_MAX_FWT; - - cfg.br = param->brt; - cfg.bs = param->bst; - - cfg.lr = rfalNfcDepPP2LR(param->ppt); - - cfg.gbLen = param->GBtLen; - if(cfg.gbLen > 0U) /* MISRA 21.18 */ - { - ST_MEMCPY(cfg.gb, param->GBt, cfg.gbLen); - } - - cfg.nfcidLen = RFAL_NFCDEP_NFCID3_LEN; - ST_MEMCPY(cfg.nfcid, param->nfcid3, RFAL_NFCDEP_NFCID3_LEN); - - cfg.to = param->to; - - cfg.role = RFAL_NFCDEP_ROLE_TARGET; - cfg.oper = param->operParam; - cfg.commMode = param->commMode; - - rfalNfcDepInitialize(); - nfcipConfig(&cfg); - - /*******************************************************************************/ - /* Reply with ATR RES to Initiator */ - /*******************************************************************************/ - gNfcip.rxBuf = (uint8_t*)rxParam.rxBuf; - gNfcip.rxBufLen = sizeof(rfalNfcDepBufFormat); - gNfcip.rxRcvdLen = rxParam.rxLen; - gNfcip.rxBufPaylPos = RFAL_NFCDEP_DEPREQ_HEADER_LEN; - gNfcip.isChaining = rxParam.isRxChaining; - gNfcip.txBufPaylPos = RFAL_NFCDEP_DEPREQ_HEADER_LEN; - - EXIT_ON_ERR(ret, nfcipTx(NFCIP_CMD_ATR_RES, (uint8_t*)gNfcip.rxBuf, NULL, 0, 0, NFCIP_NO_FWT)); - - gNfcip.state = NFCIP_ST_TARG_WAIT_ACTV; - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepListenGetActivationStatus(void) { - ReturnCode err; - uint8_t BRS; - - BRS = RFAL_NFCDEP_BRS_MAINTAIN; - - err = nfcipTargetHandleActivation(gNfcip.nfcDepDev, &BRS); - - switch(err) { - case ERR_NONE: - - if(BRS != RFAL_NFCDEP_BRS_MAINTAIN) { - /* DSI codes the bit rate from Initiator to Target */ - /* DRI codes the bit rate from Target to Initiator */ - - if(gNfcip.cfg.commMode == RFAL_NFCDEP_COMM_ACTIVE) { - EXIT_ON_ERR( - err, - rfalSetMode( - RFAL_MODE_LISTEN_ACTIVE_P2P, - gNfcip.nfcDepDev->info.DRI, - gNfcip.nfcDepDev->info.DSI)); - } else { - EXIT_ON_ERR( - err, - rfalSetMode( - ((RFAL_BR_106 == gNfcip.nfcDepDev->info.DRI) ? RFAL_MODE_LISTEN_NFCA : - RFAL_MODE_LISTEN_NFCF), - gNfcip.nfcDepDev->info.DRI, - gNfcip.nfcDepDev->info.DSI)); - } - } - break; - - case ERR_BUSY: - // do nothing - break; - - case ERR_PROTO: - default: - // re-enable receiving of data - nfcDepReEnableRx(gNfcip.rxBuf, gNfcip.rxBufLen, gNfcip.rxRcvdLen); - break; - } - - return err; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepStartTransceive(const rfalNfcDepTxRxParam* param) { - rfalNfcDepDEPParams nfcDepParams; - - nfcDepParams.txBuf = (uint8_t*)param->txBuf; - nfcDepParams.txBufLen = param->txBufLen; - nfcDepParams.txChaining = param->isTxChaining; - nfcDepParams.txBufPaylPos = - RFAL_NFCDEP_DEPREQ_HEADER_LEN; /* position in txBuf where actual outgoing data is located */ - nfcDepParams.did = RFAL_NFCDEP_DID_KEEP; - nfcDepParams.rxBufPaylPos = RFAL_NFCDEP_DEPREQ_HEADER_LEN; - nfcDepParams.rxBuf = (uint8_t*)param->rxBuf; - nfcDepParams.rxBufLen = sizeof(rfalNfcDepBufFormat); - nfcDepParams.fsc = param->FSx; - nfcDepParams.fwt = param->FWT; - nfcDepParams.dFwt = param->dFWT; - - gNfcip.rxRcvdLen = param->rxLen; - gNfcip.isChaining = param->isRxChaining; - - nfcipSetDEPParams(&nfcDepParams); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepGetTransceiveStatus(void) { - return nfcipRun(gNfcip.rxRcvdLen, gNfcip.isChaining); -} - -/*******************************************************************************/ -static void rfalNfcDepPdu2BLockParam( - rfalNfcDepPduTxRxParam pduParam, - rfalNfcDepTxRxParam* blockParam, - uint16_t txPos, - uint16_t rxPos) { - uint16_t maxInfLen; - - NO_WARNING(rxPos); /* Keep this param for future use */ - - blockParam->DID = pduParam.DID; - blockParam->FSx = pduParam.FSx; - blockParam->FWT = pduParam.FWT; - blockParam->dFWT = pduParam.dFWT; - - /* Calculate max INF/Payload to be sent to other device */ - maxInfLen = (blockParam->FSx - (RFAL_NFCDEP_HEADER + RFAL_NFCDEP_DEP_PFB_LEN)); - maxInfLen += ((blockParam->DID != RFAL_NFCDEP_DID_NO) ? RFAL_NFCDEP_DID_LEN : 0U); - - if((pduParam.txBufLen - txPos) > maxInfLen) { - blockParam->isTxChaining = true; - blockParam->txBufLen = maxInfLen; - } else { - blockParam->isTxChaining = false; - blockParam->txBufLen = (pduParam.txBufLen - txPos); - } - - /* TxBuf is moved to the beginning for every Block */ - blockParam->txBuf = - (rfalNfcDepBufFormat*)pduParam - .txBuf; /* PRQA S 0310 # MISRA 11.3 - Intentional safe cast to avoiding large buffer duplication */ - blockParam->rxBuf = - pduParam - .tmpBuf; /* Simply using the pdu buffer is not possible because of current ACK handling */ - blockParam->isRxChaining = &gNfcip.isPDURxChaining; - blockParam->rxLen = pduParam.rxLen; -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepStartPduTransceive(rfalNfcDepPduTxRxParam param) { - rfalNfcDepTxRxParam txRxParam; - - /* Initialize and store APDU context */ - gNfcip.PDUParam = param; - gNfcip.PDUTxPos = 0; - gNfcip.PDURxPos = 0; - - /* Convert PDU TxRxParams to Block TxRxParams */ - rfalNfcDepPdu2BLockParam(gNfcip.PDUParam, &txRxParam, gNfcip.PDUTxPos, gNfcip.PDURxPos); - - return rfalNfcDepStartTransceive(&txRxParam); -} - -/*******************************************************************************/ -ReturnCode rfalNfcDepGetPduTransceiveStatus(void) { - ReturnCode ret; - rfalNfcDepTxRxParam txRxParam; - - ret = rfalNfcDepGetTransceiveStatus(); - switch(ret) { - /*******************************************************************************/ - case ERR_NONE: - - /* Check if we are still doing chaining on Tx */ - if(gNfcip.isTxChaining) { - /* Add already Tx bytes */ - gNfcip.PDUTxPos += gNfcip.txBufLen; - - /* Convert APDU TxRxParams to I-Block TxRxParams */ - rfalNfcDepPdu2BLockParam( - gNfcip.PDUParam, &txRxParam, gNfcip.PDUTxPos, gNfcip.PDURxPos); - - if(txRxParam.txBufLen > 0U) /* MISRA 21.18 */ - { - /* Move next Block to beginning of APDU Tx buffer */ - ST_MEMCPY( - gNfcip.PDUParam.txBuf->pdu, - &gNfcip.PDUParam.txBuf->pdu[gNfcip.PDUTxPos], - txRxParam.txBufLen); - } - - EXIT_ON_ERR(ret, rfalNfcDepStartTransceive(&txRxParam)); - return ERR_BUSY; - } - - /* PDU TxRx is done */ - /* fall through */ - - /*******************************************************************************/ - case ERR_AGAIN: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - /* Check if no PDU transceive has been started before (data from rfalNfcDepListenStartActivation) */ - if(gNfcip.PDUParam.rxLen == NULL) { - /* In Listen mode first chained packet cannot be retrieved via APDU interface */ - if(ret == ERR_AGAIN) { - return ERR_NOTSUPP; - } - - /* TxRx is complete and full data is already available */ - return ERR_NONE; - } - - if((*gNfcip.PDUParam.rxLen) > 0U) /* MISRA 21.18 */ - { - /* Ensure that data in tmpBuf still fits into PDU buffer */ - if((uint16_t)((uint16_t)gNfcip.PDURxPos + (*gNfcip.PDUParam.rxLen)) > - RFAL_FEATURE_NFC_DEP_PDU_MAX_LEN) { - return ERR_NOMEM; - } - - /* Copy chained packet from tmp buffer to PDU buffer */ - ST_MEMCPY( - &gNfcip.PDUParam.rxBuf->pdu[gNfcip.PDURxPos], - gNfcip.PDUParam.tmpBuf->inf, - *gNfcip.PDUParam.rxLen); - gNfcip.PDURxPos += *gNfcip.PDUParam.rxLen; - } - - /* Update output param rxLen */ - *gNfcip.PDUParam.rxLen = gNfcip.PDURxPos; - - /* Wait for following Block or PDU TxRx is done */ - return ((ret == ERR_AGAIN) ? ERR_BUSY : ERR_NONE); - - /*******************************************************************************/ - default: - /* MISRA 16.4: no empty default statement (a comment being enough) */ - break; - } - - return ret; -} - -#endif /* RFAL_FEATURE_NFC_DEP */ diff --git a/lib/ST25RFAL002/source/rfal_nfca.c b/lib/ST25RFAL002/source/rfal_nfca.c deleted file mode 100644 index d4e4c9388..000000000 --- a/lib/ST25RFAL002/source/rfal_nfca.c +++ /dev/null @@ -1,886 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfca.c - * - * \author Gustavo Patricio - * - * \brief Provides several NFC-A convenience methods and definitions - * - * It provides a Poller (ISO14443A PCD) interface and as well as - * some NFC-A Listener (ISO14443A PICC) helpers. - * - * The definitions and helpers methods provided by this module are only - * up to ISO14443-3 layer - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_nfca.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_NFCA -#define RFAL_FEATURE_NFCA false /* NFC-A module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_NFCA - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_NFCA_SLP_FWT \ - rfalConvMsTo1fc(1) /*!< Check 1ms for any modulation ISO14443-3 6.4.3 */ -#define RFAL_NFCA_SLP_CMD 0x50U /*!< SLP cmd (byte1) Digital 1.1 6.9.1 & Table 20 */ -#define RFAL_NFCA_SLP_BYTE2 0x00U /*!< SLP byte2 Digital 1.1 6.9.1 & Table 20 */ -#define RFAL_NFCA_SLP_CMD_POS 0U /*!< SLP cmd position Digital 1.1 6.9.1 & Table 20 */ -#define RFAL_NFCA_SLP_BYTE2_POS 1U /*!< SLP byte2 position Digital 1.1 6.9.1 & Table 20 */ - -#define RFAL_NFCA_SDD_CT 0x88U /*!< Cascade Tag value Digital 1.1 6.7.2 */ -#define RFAL_NFCA_SDD_CT_LEN 1U /*!< Cascade Tag length */ - -#define RFAL_NFCA_SLP_REQ_LEN 2U /*!< SLP_REQ length */ - -#define RFAL_NFCA_SEL_CMD_LEN 1U /*!< SEL_CMD length */ -#define RFAL_NFCA_SEL_PAR_LEN 1U /*!< SEL_PAR length */ -#define RFAL_NFCA_SEL_SELPAR \ - rfalNfcaSelPar(7U, 0U) /*!< SEL_PAR on Select is always with 4 data/nfcid */ -#define RFAL_NFCA_BCC_LEN 1U /*!< BCC length */ - -#define RFAL_NFCA_SDD_REQ_LEN \ - (RFAL_NFCA_SEL_CMD_LEN + RFAL_NFCA_SEL_PAR_LEN) /*!< SDD_REQ length */ -#define RFAL_NFCA_SDD_RES_LEN \ - (RFAL_NFCA_CASCADE_1_UID_LEN + RFAL_NFCA_BCC_LEN) /*!< SDD_RES length */ - -#define RFAL_NFCA_T_RETRANS 5U /*!< t RETRANSMISSION [3, 33]ms EMVCo 2.6 A.5 */ -#define RFAL_NFCA_N_RETRANS 2U /*!< Number of retries EMVCo 2.6 9.6.1.3 */ - -/*! SDD_REQ (Select) Cascade Levels */ -enum { - RFAL_NFCA_SEL_CASCADE_L1 = 0, /*!< SDD_REQ Cascade Level 1 */ - RFAL_NFCA_SEL_CASCADE_L2 = 1, /*!< SDD_REQ Cascade Level 2 */ - RFAL_NFCA_SEL_CASCADE_L3 = 2 /*!< SDD_REQ Cascade Level 3 */ -}; - -/*! SDD_REQ (Select) request Cascade Level command Digital 1.1 Table 15 */ -enum { - RFAL_NFCA_CMD_SEL_CL1 = 0x93, /*!< SDD_REQ command Cascade Level 1 */ - RFAL_NFCA_CMD_SEL_CL2 = 0x95, /*!< SDD_REQ command Cascade Level 2 */ - RFAL_NFCA_CMD_SEL_CL3 = 0x97, /*!< SDD_REQ command Cascade Level 3 */ -}; - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ -#define rfalNfcaSelPar(nBy, nbi) \ - (uint8_t)( \ - (((nBy) << 4U) & 0xF0U) | \ - ((nbi)&0x0FU)) /*!< Calculates SEL_PAR with the bytes/bits to be sent */ -#define rfalNfcaCLn2SELCMD(cl) \ - (uint8_t)( \ - (uint8_t)(RFAL_NFCA_CMD_SEL_CL1) + \ - (2U * (cl))) /*!< Calculates SEL_CMD with the given cascade level */ -#define rfalNfcaNfcidLen2CL(len) \ - ((len) / 5U) /*!< Calculates cascade level by the NFCID length */ -#define rfalNfcaRunBlocking(e, fn) \ - do { \ - (e) = (fn); \ - rfalWorker(); \ - } while((e) == ERR_BUSY) /*!< Macro used for the blocking methods */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! Colission Resolution states */ -typedef enum { - RFAL_NFCA_CR_IDLE, /*!< IDLE state */ - RFAL_NFCA_CR_CL, /*!< New Cascading Level state */ - RFAL_NFCA_CR_SDD, /*!< Perform anticollsion state */ - RFAL_NFCA_CR_SEL, /*!< Perform CL Selection state */ - RFAL_NFCA_CR_DONE /*!< Collision Resolution done state */ -} colResState; - -/*! Colission Resolution context */ -typedef struct { - uint8_t devLimit; /*!< Device limit to be used */ - rfalComplianceMode compMode; /*!< Compliancy mode to be used */ - rfalNfcaListenDevice* - nfcaDevList; /*!< Location of the device list */ - uint8_t* devCnt; /*!< Location of the device counter */ - bool collPending; /*!< Collision pending flag */ - - bool* collPend; /*!< Location of collision pending flag (Single CR) */ - rfalNfcaSelReq selReq; /*!< SelReqused during anticollision (Single CR) */ - rfalNfcaSelRes* selRes; /*!< Location to place of the SEL_RES(SAK) (Single CR) */ - uint8_t* nfcId1; /*!< Location to place the NFCID1 (Single CR) */ - uint8_t* nfcId1Len; /*!< Location to place the NFCID1 length (Single CR) */ - uint8_t cascadeLv; /*!< Current Cascading Level (Single CR) */ - colResState state; /*!< Single Collision Resolution state (Single CR) */ - uint8_t bytesTxRx; /*!< TxRx bytes used during anticollision loop (Single CR) */ - uint8_t bitsTxRx; /*!< TxRx bits used during anticollision loop (Single CR) */ - uint16_t rxLen; - uint32_t tmrFDT; /*!< FDT timer used between SED_REQs (Single CR) */ - uint8_t retries; /*!< Retries to be performed upon a timeout error (Single CR)*/ - uint8_t backtrackCnt; /*!< Backtrack retries (Single CR) */ - bool doBacktrack; /*!< Backtrack flag (Single CR) */ -} colResParams; - -/*! RFAL NFC-A instance */ -typedef struct { - colResParams CR; /*!< Collision Resolution context */ -} rfalNfca; - -/*! SLP_REQ (HLTA) format Digital 1.1 6.9.1 & Table 20 */ -typedef struct { - uint8_t frame[RFAL_NFCA_SLP_REQ_LEN]; /*!< SLP: 0x50 0x00 */ -} rfalNfcaSlpReq; - -/* -****************************************************************************** -* LOCAL VARIABLES -****************************************************************************** -*/ -static rfalNfca gNfca; /*!< RFAL NFC-A instance */ - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -static uint8_t rfalNfcaCalculateBcc(const uint8_t* buf, uint8_t bufLen); -static ReturnCode rfalNfcaPollerStartSingleCollisionResolution( - uint8_t devLimit, - bool* collPending, - rfalNfcaSelRes* selRes, - uint8_t* nfcId1, - uint8_t* nfcId1Len); -static ReturnCode rfalNfcaPollerGetSingleCollisionResolutionStatus(void); - -/* - ****************************************************************************** - * LOCAL FUNCTIONS - ****************************************************************************** - */ - -static uint8_t rfalNfcaCalculateBcc(const uint8_t* buf, uint8_t bufLen) { - uint8_t i; - uint8_t BCC; - - BCC = 0; - - /* BCC is XOR over first 4 bytes of the SDD_RES Digital 1.1 6.7.2 */ - for(i = 0; i < bufLen; i++) { - BCC ^= buf[i]; - } - - return BCC; -} - -/*******************************************************************************/ -static ReturnCode rfalNfcaPollerStartSingleCollisionResolution( - uint8_t devLimit, - bool* collPending, - rfalNfcaSelRes* selRes, - uint8_t* nfcId1, - uint8_t* nfcId1Len) { - /* Check parameters */ - if((collPending == NULL) || (selRes == NULL) || (nfcId1 == NULL) || (nfcId1Len == NULL)) { - return ERR_PARAM; - } - - /* Initialize output parameters */ - *collPending = false; /* Activity 1.1 9.3.4.6 */ - *nfcId1Len = 0; - ST_MEMSET(nfcId1, 0x00, RFAL_NFCA_CASCADE_3_UID_LEN); - - /* Save parameters */ - gNfca.CR.devLimit = devLimit; - gNfca.CR.collPend = collPending; - gNfca.CR.selRes = selRes; - gNfca.CR.nfcId1 = nfcId1; - gNfca.CR.nfcId1Len = nfcId1Len; - - platformTimerDestroy(gNfca.CR.tmrFDT); - gNfca.CR.tmrFDT = 0U; - gNfca.CR.retries = RFAL_NFCA_N_RETRANS; - gNfca.CR.cascadeLv = (uint8_t)RFAL_NFCA_SEL_CASCADE_L1; - gNfca.CR.state = RFAL_NFCA_CR_CL; - - gNfca.CR.doBacktrack = false; - gNfca.CR.backtrackCnt = 3U; - - return ERR_NONE; -} - -/*******************************************************************************/ -static ReturnCode rfalNfcaPollerGetSingleCollisionResolutionStatus(void) { - ReturnCode ret; - uint8_t collBit = 1U; /* standards mandate or recommend collision bit to be set to One. */ - - /* Check if FDT timer is still running */ - if(!platformTimerIsExpired(gNfca.CR.tmrFDT) && (gNfca.CR.tmrFDT != 0U)) { - return ERR_BUSY; - } - - /*******************************************************************************/ - /* Go through all Cascade Levels Activity 1.1 9.3.4 */ - if(gNfca.CR.cascadeLv > (uint8_t)RFAL_NFCA_SEL_CASCADE_L3) { - return ERR_INTERNAL; - } - - switch(gNfca.CR.state) { - /*******************************************************************************/ - case RFAL_NFCA_CR_CL: - - /* Initialize the SDD_REQ to send for the new cascade level */ - ST_MEMSET((uint8_t*)&gNfca.CR.selReq, 0x00, sizeof(rfalNfcaSelReq)); - - gNfca.CR.bytesTxRx = RFAL_NFCA_SDD_REQ_LEN; - gNfca.CR.bitsTxRx = 0U; - gNfca.CR.state = RFAL_NFCA_CR_SDD; - - /* fall through */ - - /*******************************************************************************/ - case RFAL_NFCA_CR_SDD: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - /* Calculate SEL_CMD and SEL_PAR with the bytes/bits to be sent */ - gNfca.CR.selReq.selCmd = rfalNfcaCLn2SELCMD(gNfca.CR.cascadeLv); - gNfca.CR.selReq.selPar = rfalNfcaSelPar(gNfca.CR.bytesTxRx, gNfca.CR.bitsTxRx); - - /* Send SDD_REQ (Anticollision frame) */ - ret = rfalISO14443ATransceiveAnticollisionFrame( - (uint8_t*)&gNfca.CR.selReq, - &gNfca.CR.bytesTxRx, - &gNfca.CR.bitsTxRx, - &gNfca.CR.rxLen, - RFAL_NFCA_FDTMIN); - - /* Retry upon timeout EMVCo 2.6 9.6.1.3 */ - if((ret == ERR_TIMEOUT) && (gNfca.CR.devLimit == 0U) && (gNfca.CR.retries != 0U)) { - gNfca.CR.retries--; - platformTimerDestroy(gNfca.CR.tmrFDT); - gNfca.CR.tmrFDT = platformTimerCreate(RFAL_NFCA_T_RETRANS); - break; - } - - /* Covert rxLen into bytes */ - gNfca.CR.rxLen = rfalConvBitsToBytes(gNfca.CR.rxLen); - - if((ret == ERR_TIMEOUT) && (gNfca.CR.backtrackCnt != 0U) && (!gNfca.CR.doBacktrack) && - !((RFAL_NFCA_SDD_REQ_LEN == gNfca.CR.bytesTxRx) && (0U == gNfca.CR.bitsTxRx))) { - /* In multiple card scenarios it may always happen that some - * collisions of a weaker tag go unnoticed. If then a later - * collision is recognized and the strong tag has a 0 at the - * collision position then no tag will respond. Catch this - * corner case and then try with the bit being sent as zero. */ - rfalNfcaSensRes sensRes; - ret = ERR_RF_COLLISION; - rfalNfcaPollerCheckPresence(RFAL_14443A_SHORTFRAME_CMD_REQA, &sensRes); - /* Algorithm below does a post-increment, decrement to go back to current position */ - if(0U == gNfca.CR.bitsTxRx) { - gNfca.CR.bitsTxRx = 7; - gNfca.CR.bytesTxRx--; - } else { - gNfca.CR.bitsTxRx--; - } - collBit = - (uint8_t)(((uint8_t*)&gNfca.CR.selReq)[gNfca.CR.bytesTxRx] & (1U << gNfca.CR.bitsTxRx)); - collBit = (uint8_t)((0U == collBit) ? 1U : 0U); // invert the collision bit - gNfca.CR.doBacktrack = true; - gNfca.CR.backtrackCnt--; - } else { - gNfca.CR.doBacktrack = false; - } - - if(ret == ERR_RF_COLLISION) { - /* Check received length */ - if((gNfca.CR.bytesTxRx + ((gNfca.CR.bitsTxRx != 0U) ? 1U : 0U)) > - (RFAL_NFCA_SDD_RES_LEN + RFAL_NFCA_SDD_REQ_LEN)) { - return ERR_PROTO; - } - - if(((gNfca.CR.bytesTxRx + ((gNfca.CR.bitsTxRx != 0U) ? 1U : 0U)) > - (RFAL_NFCA_CASCADE_1_UID_LEN + RFAL_NFCA_SDD_REQ_LEN)) && - (gNfca.CR.backtrackCnt != 0U)) { /* Collision in BCC: Anticollide only UID part */ - gNfca.CR.backtrackCnt--; - gNfca.CR.bytesTxRx = RFAL_NFCA_CASCADE_1_UID_LEN + RFAL_NFCA_SDD_REQ_LEN - 1U; - gNfca.CR.bitsTxRx = 7; - collBit = - (uint8_t)(((uint8_t*)&gNfca.CR.selReq)[gNfca.CR.bytesTxRx] & (1U << gNfca.CR.bitsTxRx)); /* Not a real collision, extract the actual bit for the subsequent code */ - } - - if((gNfca.CR.devLimit == 0U) && !(*gNfca.CR.collPend)) { - /* Activity 1.0 & 1.1 9.3.4.12: If CON_DEVICES_LIMIT has a value of 0, then - * NFC Forum Device is configured to perform collision detection only */ - *gNfca.CR.collPend = true; - return ERR_IGNORE; - } - - *gNfca.CR.collPend = true; - - /* Set and select the collision bit, with the number of bytes/bits successfully TxRx */ - if(collBit != 0U) { - ((uint8_t*)&gNfca.CR.selReq)[gNfca.CR.bytesTxRx] = - (uint8_t)(((uint8_t*)&gNfca.CR.selReq)[gNfca.CR.bytesTxRx] | (1U << gNfca.CR.bitsTxRx)); /* MISRA 10.3 */ - } else { - ((uint8_t*)&gNfca.CR.selReq)[gNfca.CR.bytesTxRx] = - (uint8_t)(((uint8_t*)&gNfca.CR.selReq)[gNfca.CR.bytesTxRx] & ~(1U << gNfca.CR.bitsTxRx)); /* MISRA 10.3 */ - } - - gNfca.CR.bitsTxRx++; - - /* Check if number of bits form a byte */ - if(gNfca.CR.bitsTxRx == RFAL_BITS_IN_BYTE) { - gNfca.CR.bitsTxRx = 0; - gNfca.CR.bytesTxRx++; - } - break; - } - - /*******************************************************************************/ - /* Check if Collision loop has failed */ - if(ret != ERR_NONE) { - return ret; - } - - /* If collisions are to be reported check whether the response is complete */ - if((gNfca.CR.devLimit == 0U) && (gNfca.CR.rxLen != sizeof(rfalNfcaSddRes))) { - return ERR_PROTO; - } - - /* Check if the received BCC match */ - if(gNfca.CR.selReq.bcc != - rfalNfcaCalculateBcc(gNfca.CR.selReq.nfcid1, RFAL_NFCA_CASCADE_1_UID_LEN)) { - return ERR_PROTO; - } - - /*******************************************************************************/ - /* Anticollision OK, Select this Cascade Level */ - gNfca.CR.selReq.selPar = RFAL_NFCA_SEL_SELPAR; - - gNfca.CR.retries = RFAL_NFCA_N_RETRANS; - gNfca.CR.state = RFAL_NFCA_CR_SEL; - break; - - /*******************************************************************************/ - case RFAL_NFCA_CR_SEL: - - /* Send SEL_REQ (Select command) - Retry upon timeout EMVCo 2.6 9.6.1.3 */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&gNfca.CR.selReq, - sizeof(rfalNfcaSelReq), - (uint8_t*)gNfca.CR.selRes, - sizeof(rfalNfcaSelRes), - &gNfca.CR.rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCA_FDTMIN); - - /* Retry upon timeout EMVCo 2.6 9.6.1.3 */ - if((ret == ERR_TIMEOUT) && (gNfca.CR.devLimit == 0U) && (gNfca.CR.retries != 0U)) { - gNfca.CR.retries--; - platformTimerDestroy(gNfca.CR.tmrFDT); - gNfca.CR.tmrFDT = platformTimerCreate(RFAL_NFCA_T_RETRANS); - break; - } - - if(ret != ERR_NONE) { - return ret; - } - - /* Ensure proper response length */ - if(gNfca.CR.rxLen != sizeof(rfalNfcaSelRes)) { - return ERR_PROTO; - } - - /*******************************************************************************/ - /* Check cascade byte, if cascade tag then go next cascade level */ - if(*gNfca.CR.selReq.nfcid1 == RFAL_NFCA_SDD_CT) { - /* Cascade Tag present, store nfcid1 bytes (excluding cascade tag) and continue for next CL */ - ST_MEMCPY( - &gNfca.CR.nfcId1[*gNfca.CR.nfcId1Len], - &((uint8_t*)&gNfca.CR.selReq.nfcid1)[RFAL_NFCA_SDD_CT_LEN], - (RFAL_NFCA_CASCADE_1_UID_LEN - RFAL_NFCA_SDD_CT_LEN)); - *gNfca.CR.nfcId1Len += (RFAL_NFCA_CASCADE_1_UID_LEN - RFAL_NFCA_SDD_CT_LEN); - - /* Go to next cascade level */ - gNfca.CR.state = RFAL_NFCA_CR_CL; - gNfca.CR.cascadeLv++; - } else { - /* UID Selection complete, Stop Cascade Level loop */ - ST_MEMCPY( - &gNfca.CR.nfcId1[*gNfca.CR.nfcId1Len], - (uint8_t*)&gNfca.CR.selReq.nfcid1, - RFAL_NFCA_CASCADE_1_UID_LEN); - *gNfca.CR.nfcId1Len += RFAL_NFCA_CASCADE_1_UID_LEN; - - gNfca.CR.state = RFAL_NFCA_CR_DONE; - break; /* Only flag operation complete on the next execution */ - } - break; - - /*******************************************************************************/ - case RFAL_NFCA_CR_DONE: - return ERR_NONE; - - /*******************************************************************************/ - default: - return ERR_WRONG_STATE; - } - return ERR_BUSY; -} - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -ReturnCode rfalNfcaPollerInitialize(void) { - ReturnCode ret; - - EXIT_ON_ERR(ret, rfalSetMode(RFAL_MODE_POLL_NFCA, RFAL_BR_106, RFAL_BR_106)); - rfalSetErrorHandling(RFAL_ERRORHANDLING_NFC); - - rfalSetGT(RFAL_GT_NFCA); - rfalSetFDTListen(RFAL_FDT_LISTEN_NFCA_POLLER); - rfalSetFDTPoll(RFAL_FDT_POLL_NFCA_POLLER); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcaPollerCheckPresence(rfal14443AShortFrameCmd cmd, rfalNfcaSensRes* sensRes) { - ReturnCode ret; - uint16_t rcvLen; - - /* Digital 1.1 6.10.1.3 For Commands ALL_REQ, SENS_REQ, SDD_REQ, and SEL_REQ, the NFC Forum Device * - * MUST treat receipt of a Listen Frame at a time after FDT(Listen, min) as a Timeour Error */ - - ret = rfalISO14443ATransceiveShortFrame( - cmd, - (uint8_t*)sensRes, - (uint8_t)rfalConvBytesToBits(sizeof(rfalNfcaSensRes)), - &rcvLen, - RFAL_NFCA_FDTMIN); - if((ret == ERR_RF_COLLISION) || (ret == ERR_CRC) || (ret == ERR_NOMEM) || - (ret == ERR_FRAMING) || (ret == ERR_PAR)) { - ret = ERR_NONE; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode - rfalNfcaPollerTechnologyDetection(rfalComplianceMode compMode, rfalNfcaSensRes* sensRes) { - ReturnCode ret; - - EXIT_ON_ERR( - ret, - rfalNfcaPollerCheckPresence( - ((compMode == RFAL_COMPLIANCE_MODE_EMV) ? RFAL_14443A_SHORTFRAME_CMD_WUPA : - RFAL_14443A_SHORTFRAME_CMD_REQA), - sensRes)); - - /* Send SLP_REQ as Activity 1.1 9.2.3.6 and EMVCo 2.6 9.2.1.3 */ - if(compMode != RFAL_COMPLIANCE_MODE_ISO) { - rfalNfcaPollerSleep(); - } - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcaPollerSingleCollisionResolution( - uint8_t devLimit, - bool* collPending, - rfalNfcaSelRes* selRes, - uint8_t* nfcId1, - uint8_t* nfcId1Len) { - ReturnCode ret; - - EXIT_ON_ERR( - ret, - rfalNfcaPollerStartSingleCollisionResolution( - devLimit, collPending, selRes, nfcId1, nfcId1Len)); - rfalNfcaRunBlocking(ret, rfalNfcaPollerGetSingleCollisionResolutionStatus()); - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalNfcaPollerStartFullCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcaListenDevice* nfcaDevList, - uint8_t* devCnt) { - ReturnCode ret; - rfalNfcaSensRes sensRes; - uint16_t rcvLen; - - if((nfcaDevList == NULL) || (devCnt == NULL)) { - return ERR_PARAM; - } - - *devCnt = 0; - ret = ERR_NONE; - - /*******************************************************************************/ - /* Send ALL_REQ before Anticollision if a Sleep was sent before Activity 1.1 9.3.4.1 and EMVco 2.6 9.3.2.1 */ - if(compMode != RFAL_COMPLIANCE_MODE_ISO) { - ret = rfalISO14443ATransceiveShortFrame( - RFAL_14443A_SHORTFRAME_CMD_WUPA, - (uint8_t*)&nfcaDevList->sensRes, - (uint8_t)rfalConvBytesToBits(sizeof(rfalNfcaSensRes)), - &rcvLen, - RFAL_NFCA_FDTMIN); - if(ret != ERR_NONE) { - if((compMode == RFAL_COMPLIANCE_MODE_EMV) || - ((ret != ERR_RF_COLLISION) && (ret != ERR_CRC) && (ret != ERR_FRAMING) && - (ret != ERR_PAR))) { - return ret; - } - } - - /* Check proper SENS_RES/ATQA size */ - if((ret == ERR_NONE) && (rfalConvBytesToBits(sizeof(rfalNfcaSensRes)) != rcvLen)) { - return ERR_PROTO; - } - } - - /*******************************************************************************/ - /* Store the SENS_RES from Technology Detection or from WUPA */ - sensRes = nfcaDevList->sensRes; - - if(devLimit > 0U) /* MISRA 21.18 */ - { - ST_MEMSET(nfcaDevList, 0x00, (sizeof(rfalNfcaListenDevice) * devLimit)); - } - - /* Restore the prev SENS_RES, assuming that the SENS_RES received is from first device - * When only one device is detected it's not woken up then we'll have no SENS_RES (ATQA) */ - nfcaDevList->sensRes = sensRes; - - /* Save parameters */ - gNfca.CR.devCnt = devCnt; - gNfca.CR.devLimit = devLimit; - gNfca.CR.nfcaDevList = nfcaDevList; - gNfca.CR.compMode = compMode; - -#if RFAL_FEATURE_T1T - /*******************************************************************************/ - /* Only check for T1T if previous SENS_RES was received without a transmission * - * error. When collisions occur bits in the SENS_RES may look like a T1T */ - /* If T1T Anticollision is not supported Activity 1.1 9.3.4.3 */ - if(rfalNfcaIsSensResT1T(&nfcaDevList->sensRes) && (devLimit != 0U) && (ret == ERR_NONE) && - (compMode != RFAL_COMPLIANCE_MODE_EMV)) { - /* RID_REQ shall be performed Activity 1.1 9.3.4.24 */ - rfalT1TPollerInitialize(); - EXIT_ON_ERR(ret, rfalT1TPollerRid(&nfcaDevList->ridRes)); - - *devCnt = 1U; - nfcaDevList->isSleep = false; - nfcaDevList->type = RFAL_NFCA_T1T; - nfcaDevList->nfcId1Len = RFAL_NFCA_CASCADE_1_UID_LEN; - ST_MEMCPY(&nfcaDevList->nfcId1, &nfcaDevList->ridRes.uid, RFAL_NFCA_CASCADE_1_UID_LEN); - - return ERR_NONE; - } -#endif /* RFAL_FEATURE_T1T */ - - return rfalNfcaPollerStartSingleCollisionResolution( - devLimit, - &gNfca.CR.collPending, - &nfcaDevList->selRes, - (uint8_t*)&nfcaDevList->nfcId1, - &nfcaDevList->nfcId1Len); -} - -/*******************************************************************************/ -ReturnCode rfalNfcaPollerGetFullCollisionResolutionStatus(void) { - ReturnCode ret; - uint8_t newDevType; - - if((gNfca.CR.nfcaDevList == NULL) || (gNfca.CR.devCnt == NULL)) { - return ERR_WRONG_STATE; - } - - /*******************************************************************************/ - /* Check whether a T1T has already been detected */ - if(rfalNfcaIsSensResT1T(&gNfca.CR.nfcaDevList->sensRes) && - (gNfca.CR.nfcaDevList->type == RFAL_NFCA_T1T)) { - /* T1T doesn't support Anticollision */ - return ERR_NONE; - } - - /*******************************************************************************/ - EXIT_ON_ERR(ret, rfalNfcaPollerGetSingleCollisionResolutionStatus()); - - /* Assign Listen Device */ - newDevType = ((uint8_t)gNfca.CR.nfcaDevList[*gNfca.CR.devCnt].selRes.sak) & - RFAL_NFCA_SEL_RES_CONF_MASK; /* MISRA 10.8 */ - /* PRQA S 4342 1 # MISRA 10.5 - Guaranteed that no invalid enum values are created: see guard_eq_RFAL_NFCA_T2T, .... */ - gNfca.CR.nfcaDevList[*gNfca.CR.devCnt].type = (rfalNfcaListenDeviceType)newDevType; - gNfca.CR.nfcaDevList[*gNfca.CR.devCnt].isSleep = false; - (*gNfca.CR.devCnt)++; - - /* If a collision was detected and device counter is lower than limit Activity 1.1 9.3.4.21 */ - if((*gNfca.CR.devCnt < gNfca.CR.devLimit) && (gNfca.CR.collPending)) { - /* Put this device to Sleep Activity 1.1 9.3.4.22 */ - rfalNfcaPollerSleep(); - gNfca.CR.nfcaDevList[(*gNfca.CR.devCnt - 1U)].isSleep = true; - - /* Send a new SENS_REQ to check for other cards Activity 1.1 9.3.4.23 */ - ret = rfalNfcaPollerCheckPresence( - RFAL_14443A_SHORTFRAME_CMD_REQA, &gNfca.CR.nfcaDevList[*gNfca.CR.devCnt].sensRes); - if(ret == ERR_TIMEOUT) { - /* No more devices found, exit */ - gNfca.CR.collPending = false; - } else { - /* Another device found, continue loop */ - gNfca.CR.collPending = true; - } - } else { - /* Exit loop */ - gNfca.CR.collPending = false; - } - - /*******************************************************************************/ - /* Check if collision resolution shall continue */ - if((*gNfca.CR.devCnt < gNfca.CR.devLimit) && (gNfca.CR.collPending)) { - EXIT_ON_ERR( - ret, - rfalNfcaPollerStartSingleCollisionResolution( - gNfca.CR.devLimit, - &gNfca.CR.collPending, - &gNfca.CR.nfcaDevList[*gNfca.CR.devCnt].selRes, - (uint8_t*)&gNfca.CR.nfcaDevList[*gNfca.CR.devCnt].nfcId1, - &gNfca.CR.nfcaDevList[*gNfca.CR.devCnt].nfcId1Len)); - - return ERR_BUSY; - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcaPollerFullCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcaListenDevice* nfcaDevList, - uint8_t* devCnt) { - ReturnCode ret; - - EXIT_ON_ERR( - ret, rfalNfcaPollerStartFullCollisionResolution(compMode, devLimit, nfcaDevList, devCnt)); - rfalNfcaRunBlocking(ret, rfalNfcaPollerGetFullCollisionResolutionStatus()); - - return ret; -} - -ReturnCode rfalNfcaPollerSleepFullCollisionResolution( - uint8_t devLimit, - rfalNfcaListenDevice* nfcaDevList, - uint8_t* devCnt) { - bool firstRound; - uint8_t tmpDevCnt; - ReturnCode ret; - - if((nfcaDevList == NULL) || (devCnt == NULL)) { - return ERR_PARAM; - } - - /* Only use ALL_REQ (WUPA) on the first round */ - firstRound = true; - *devCnt = 0; - - /* Perform collision resolution until no new device is found */ - do { - tmpDevCnt = 0; - ret = rfalNfcaPollerFullCollisionResolution( - (firstRound ? RFAL_COMPLIANCE_MODE_NFC : RFAL_COMPLIANCE_MODE_ISO), - (devLimit - *devCnt), - &nfcaDevList[*devCnt], - &tmpDevCnt); - - if((ret == ERR_NONE) && (tmpDevCnt > 0U)) { - *devCnt += tmpDevCnt; - - /* Check whether to seacrh for more devices */ - if(*devCnt < devLimit) { - /* Set last found device to sleep (all others are slept already) */ - rfalNfcaPollerSleep(); - nfcaDevList[((*devCnt) - 1U)].isSleep = true; - - /* Check if any other device is present */ - ret = rfalNfcaPollerCheckPresence( - RFAL_14443A_SHORTFRAME_CMD_REQA, &nfcaDevList[*devCnt].sensRes); - if(ret == ERR_NONE) { - firstRound = false; - continue; - } - } - } - break; - } while(true); - - return ((*devCnt > 0U) ? ERR_NONE : ret); -} - -/*******************************************************************************/ -ReturnCode rfalNfcaPollerSelect(const uint8_t* nfcid1, uint8_t nfcidLen, rfalNfcaSelRes* selRes) { - uint8_t i; - uint8_t cl; - uint8_t nfcidOffset; - uint16_t rxLen; - ReturnCode ret; - rfalNfcaSelReq selReq; - - if((nfcid1 == NULL) || (nfcidLen > RFAL_NFCA_CASCADE_3_UID_LEN) || (selRes == NULL)) { - return ERR_PARAM; - } - - /* Calculate Cascate Level */ - cl = rfalNfcaNfcidLen2CL(nfcidLen); - nfcidOffset = 0; - - /*******************************************************************************/ - /* Go through all Cascade Levels Activity 1.1 9.4.4 */ - for(i = RFAL_NFCA_SEL_CASCADE_L1; i <= cl; i++) { - /* Assign SEL_CMD according to the CLn and SEL_PAR*/ - selReq.selCmd = rfalNfcaCLn2SELCMD(i); - selReq.selPar = RFAL_NFCA_SEL_SELPAR; - - /* Compute NFCID/Data on the SEL_REQ command Digital 1.1 Table 18 */ - if(cl != i) { - *selReq.nfcid1 = RFAL_NFCA_SDD_CT; - ST_MEMCPY( - &selReq.nfcid1[RFAL_NFCA_SDD_CT_LEN], - &nfcid1[nfcidOffset], - (RFAL_NFCA_CASCADE_1_UID_LEN - RFAL_NFCA_SDD_CT_LEN)); - nfcidOffset += (RFAL_NFCA_CASCADE_1_UID_LEN - RFAL_NFCA_SDD_CT_LEN); - } else { - ST_MEMCPY(selReq.nfcid1, &nfcid1[nfcidOffset], RFAL_NFCA_CASCADE_1_UID_LEN); - } - - /* Calculate nfcid's BCC */ - selReq.bcc = rfalNfcaCalculateBcc((uint8_t*)&selReq.nfcid1, sizeof(selReq.nfcid1)); - - /*******************************************************************************/ - /* Send SEL_REQ */ - EXIT_ON_ERR( - ret, - rfalTransceiveBlockingTxRx( - (uint8_t*)&selReq, - sizeof(rfalNfcaSelReq), - (uint8_t*)selRes, - sizeof(rfalNfcaSelRes), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCA_FDTMIN)); - - /* Ensure proper response length */ - if(rxLen != sizeof(rfalNfcaSelRes)) { - return ERR_PROTO; - } - } - - /* REMARK: Could check if NFCID1 is complete */ - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcaPollerSleep(void) { - rfalNfcaSlpReq slpReq; - uint8_t rxBuf; /* dummy buffer, just to perform Rx */ - - slpReq.frame[RFAL_NFCA_SLP_CMD_POS] = RFAL_NFCA_SLP_CMD; - slpReq.frame[RFAL_NFCA_SLP_BYTE2_POS] = RFAL_NFCA_SLP_BYTE2; - - rfalTransceiveBlockingTxRx( - (uint8_t*)&slpReq, - sizeof(rfalNfcaSlpReq), - &rxBuf, - sizeof(rxBuf), - NULL, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCA_SLP_FWT); - - /* ISO14443-3 6.4.3 HLTA - If PICC responds with any modulation during 1 ms this response shall be interpreted as not acknowledge - Digital 2.0 6.9.2.1 & EMVCo 3.0 5.6.2.1 - consider the HLTA command always acknowledged - No check to be compliant with NFC and EMVCo, and to improve interoprability (Kovio RFID Tag) - */ - - return ERR_NONE; -} - -/*******************************************************************************/ -bool rfalNfcaListenerIsSleepReq(const uint8_t* buf, uint16_t bufLen) { - /* Check if length and payload match */ - if((bufLen != sizeof(rfalNfcaSlpReq)) || (buf[RFAL_NFCA_SLP_CMD_POS] != RFAL_NFCA_SLP_CMD) || - (buf[RFAL_NFCA_SLP_BYTE2_POS] != RFAL_NFCA_SLP_BYTE2)) { - return false; - } - - return true; -} - -/* If the guards here don't compile then the code above cannot work anymore. */ -extern uint8_t guard_eq_RFAL_NFCA_T2T - [((RFAL_NFCA_SEL_RES_CONF_MASK & (uint8_t)RFAL_NFCA_T2T) == (uint8_t)RFAL_NFCA_T2T) ? 1 : (-1)]; -extern uint8_t guard_eq_RFAL_NFCA_T4T - [((RFAL_NFCA_SEL_RES_CONF_MASK & (uint8_t)RFAL_NFCA_T4T) == (uint8_t)RFAL_NFCA_T4T) ? 1 : (-1)]; -extern uint8_t guard_eq_RFAL_NFCA_NFCDEP - [((RFAL_NFCA_SEL_RES_CONF_MASK & (uint8_t)RFAL_NFCA_NFCDEP) == (uint8_t)RFAL_NFCA_NFCDEP) ? - 1 : - (-1)]; -extern uint8_t guard_eq_RFAL_NFCA_T4T_NFCDEP - [((RFAL_NFCA_SEL_RES_CONF_MASK & (uint8_t)RFAL_NFCA_T4T_NFCDEP) == - (uint8_t)RFAL_NFCA_T4T_NFCDEP) ? - 1 : - (-1)]; -#endif /* RFAL_FEATURE_NFCA */ diff --git a/lib/ST25RFAL002/source/rfal_nfcb.c b/lib/ST25RFAL002/source/rfal_nfcb.c deleted file mode 100644 index 841b2554a..000000000 --- a/lib/ST25RFAL002/source/rfal_nfcb.c +++ /dev/null @@ -1,519 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfcb.c - * - * \author Gustavo Patricio - * - * \brief Implementation of NFC-B (ISO14443B) helpers - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_nfcb.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_NFCB -#define RFAL_FEATURE_NFCB false /* NFC-B module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_NFCB - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_NFCB_SENSB_REQ_EXT_SENSB_RES_SUPPORTED \ - 0x10U /*!< Bit mask for Extended SensB Response support in SENSB_REQ */ -#define RFAL_NFCB_SENSB_RES_PROT_TYPE_RFU \ - 0x08U /*!< Bit mask for Protocol Type RFU in SENSB_RES */ -#define RFAL_NFCB_SLOT_MARKER_SC_SHIFT \ - 4U /*!< Slot Code position on SLOT_MARKER APn */ - -#define RFAL_NFCB_SLOTMARKER_SLOTCODE_MIN \ - 1U /*!< SLOT_MARKER Slot Code minimum Digital 1.1 Table 37 */ -#define RFAL_NFCB_SLOTMARKER_SLOTCODE_MAX \ - 16U /*!< SLOT_MARKER Slot Code maximum Digital 1.1 Table 37 */ - -#define RFAL_NFCB_ACTIVATION_FWT \ - (RFAL_NFCB_FWTSENSB + RFAL_NFCB_DTPOLL_20) /*!< FWT(SENSB) + dTbPoll Digital 2.0 7.9.1.3 */ - -/*! Advanced and Extended bit mask in Parameter of SENSB_REQ */ -#define RFAL_NFCB_SENSB_REQ_PARAM \ - (RFAL_NFCB_SENSB_REQ_ADV_FEATURE | RFAL_NFCB_SENSB_REQ_EXT_SENSB_RES_SUPPORTED) - -/*! NFC-B commands definition */ -enum { - RFAL_NFCB_CMD_SENSB_REQ = 0x05, /*!< SENSB_REQ (REQB) & SLOT_MARKER Digital 1.1 Table 24 */ - RFAL_NFCB_CMD_SENSB_RES = 0x50, /*!< SENSB_RES (ATQB) & SLOT_MARKER Digital 1.1 Table 27 */ - RFAL_NFCB_CMD_SLPB_REQ = 0x50, /*!< SLPB_REQ (HLTB command) Digital 1.1 Table 38 */ - RFAL_NFCB_CMD_SLPB_RES = 0x00 /*!< SLPB_RES (HLTB Answer) Digital 1.1 Table 39 */ -}; - -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ - -#define rfalNfcbNI2NumberOfSlots(ni) \ - (uint8_t)(1U << (ni)) /*!< Converts the Number of slots Identifier to slot number */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! ALLB_REQ (WUPB) and SENSB_REQ (REQB) Command Format Digital 1.1 7.6.1 */ -typedef struct { - uint8_t cmd; /*!< xxxxB_REQ: 05h */ - uint8_t AFI; /*!< NFC Identifier */ - uint8_t PARAM; /*!< Application Data */ -} rfalNfcbSensbReq; - -/*! SLOT_MARKER Command format Digital 1.1 7.7.1 */ -typedef struct { - uint8_t APn; /*!< Slot number 2..16 | 0101b */ -} rfalNfcbSlotMarker; - -/*! SLPB_REQ (HLTB) Command Format Digital 1.1 7.8.1 */ -typedef struct { - uint8_t cmd; /*!< SLPB_REQ: 50h */ - uint8_t nfcid0[RFAL_NFCB_NFCID0_LEN]; /*!< NFC Identifier (PUPI)*/ -} rfalNfcbSlpbReq; - -/*! SLPB_RES (HLTB) Response Format Digital 1.1 7.8.2 */ -typedef struct { - uint8_t cmd; /*!< SLPB_RES: 00h */ -} rfalNfcbSlpbRes; - -/*! RFAL NFC-B instance */ -typedef struct { - uint8_t AFI; /*!< AFI to be used */ - uint8_t PARAM; /*!< PARAM to be used */ -} rfalNfcb; - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -static ReturnCode rfalNfcbCheckSensbRes(const rfalNfcbSensbRes* sensbRes, uint8_t sensbResLen); - -/* -****************************************************************************** -* LOCAL VARIABLES -****************************************************************************** -*/ - -static rfalNfcb gRfalNfcb; /*!< RFAL NFC-B Instance */ - -/* -****************************************************************************** -* LOCAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -static ReturnCode rfalNfcbCheckSensbRes(const rfalNfcbSensbRes* sensbRes, uint8_t sensbResLen) { - /* Check response length */ - if(((sensbResLen != RFAL_NFCB_SENSB_RES_LEN) && - (sensbResLen != RFAL_NFCB_SENSB_RES_EXT_LEN))) { - return ERR_PROTO; - } - - /* Check SENSB_RES and Protocol Type Digital 1.1 7.6.2.19 */ - if(((sensbRes->protInfo.FsciProType & RFAL_NFCB_SENSB_RES_PROT_TYPE_RFU) != 0U) || - (sensbRes->cmd != (uint8_t)RFAL_NFCB_CMD_SENSB_RES)) { - return ERR_PROTO; - } - return ERR_NONE; -} - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -ReturnCode rfalNfcbPollerInitialize(void) { - ReturnCode ret; - - EXIT_ON_ERR(ret, rfalSetMode(RFAL_MODE_POLL_NFCB, RFAL_BR_106, RFAL_BR_106)); - rfalSetErrorHandling(RFAL_ERRORHANDLING_NFC); - - rfalSetGT(RFAL_GT_NFCB); - rfalSetFDTListen(RFAL_FDT_LISTEN_NFCB_POLLER); - rfalSetFDTPoll(RFAL_FDT_POLL_NFCB_POLLER); - - gRfalNfcb.AFI = RFAL_NFCB_AFI; - gRfalNfcb.PARAM = RFAL_NFCB_PARAM; - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcbPollerInitializeWithParams(uint8_t AFI, uint8_t PARAM) { - ReturnCode ret; - - EXIT_ON_ERR(ret, rfalNfcbPollerInitialize()); - - gRfalNfcb.AFI = AFI; - gRfalNfcb.PARAM = (PARAM & RFAL_NFCB_SENSB_REQ_PARAM); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcbPollerCheckPresence( - rfalNfcbSensCmd cmd, - rfalNfcbSlots slots, - rfalNfcbSensbRes* sensbRes, - uint8_t* sensbResLen) { - uint16_t rxLen; - ReturnCode ret; - rfalNfcbSensbReq sensbReq; - - /* Check if the command requested and given the slot number are valid */ - if(((RFAL_NFCB_SENS_CMD_SENSB_REQ != cmd) && (RFAL_NFCB_SENS_CMD_ALLB_REQ != cmd)) || - (slots > RFAL_NFCB_SLOT_NUM_16) || (sensbRes == NULL) || (sensbResLen == NULL)) { - return ERR_PARAM; - } - - *sensbResLen = 0; - ST_MEMSET(sensbRes, 0x00, sizeof(rfalNfcbSensbRes)); - - /* Compute SENSB_REQ */ - sensbReq.cmd = RFAL_NFCB_CMD_SENSB_REQ; - sensbReq.AFI = gRfalNfcb.AFI; - sensbReq.PARAM = - (((uint8_t)gRfalNfcb.PARAM & RFAL_NFCB_SENSB_REQ_PARAM) | (uint8_t)cmd | (uint8_t)slots); - - /* Send SENSB_REQ and disable AGC to detect collisions */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&sensbReq, - sizeof(rfalNfcbSensbReq), - (uint8_t*)sensbRes, - sizeof(rfalNfcbSensbRes), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCB_FWTSENSB); - - *sensbResLen = (uint8_t)rxLen; - - /* Check if a transmission error was detected */ - if((ret == ERR_CRC) || (ret == ERR_FRAMING)) { - /* Invalidate received frame as an error was detected (CollisionResolution checks if valid) */ - *sensbResLen = 0; - return ERR_NONE; - } - - if(ret == ERR_NONE) { - return rfalNfcbCheckSensbRes(sensbRes, *sensbResLen); - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalNfcbPollerSleep(const uint8_t* nfcid0) { - uint16_t rxLen; - ReturnCode ret; - rfalNfcbSlpbReq slpbReq; - rfalNfcbSlpbRes slpbRes; - - if(nfcid0 == NULL) { - return ERR_PARAM; - } - - /* Compute SLPB_REQ */ - slpbReq.cmd = RFAL_NFCB_CMD_SLPB_REQ; - ST_MEMCPY(slpbReq.nfcid0, nfcid0, RFAL_NFCB_NFCID0_LEN); - - EXIT_ON_ERR( - ret, - rfalTransceiveBlockingTxRx( - (uint8_t*)&slpbReq, - sizeof(rfalNfcbSlpbReq), - (uint8_t*)&slpbRes, - sizeof(rfalNfcbSlpbRes), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCB_ACTIVATION_FWT)); - - /* Check SLPB_RES */ - if((rxLen != sizeof(rfalNfcbSlpbRes)) || (slpbRes.cmd != (uint8_t)RFAL_NFCB_CMD_SLPB_RES)) { - return ERR_PROTO; - } - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode - rfalNfcbPollerSlotMarker(uint8_t slotCode, rfalNfcbSensbRes* sensbRes, uint8_t* sensbResLen) { - ReturnCode ret; - rfalNfcbSlotMarker slotMarker; - uint16_t rxLen; - - /* Check parameters */ - if((sensbRes == NULL) || (sensbResLen == NULL) || - (slotCode < RFAL_NFCB_SLOTMARKER_SLOTCODE_MIN) || - (slotCode > RFAL_NFCB_SLOTMARKER_SLOTCODE_MAX)) { - return ERR_PARAM; - } - /* Compose and send SLOT_MARKER with disabled AGC to detect collisions */ - slotMarker.APn = - ((slotCode << RFAL_NFCB_SLOT_MARKER_SC_SHIFT) | (uint8_t)RFAL_NFCB_CMD_SENSB_REQ); - - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&slotMarker, - sizeof(rfalNfcbSlotMarker), - (uint8_t*)sensbRes, - sizeof(rfalNfcbSensbRes), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCB_ACTIVATION_FWT); - - *sensbResLen = (uint8_t)rxLen; - - /* Check if a transmission error was detected */ - if((ret == ERR_CRC) || (ret == ERR_FRAMING)) { - return ERR_RF_COLLISION; - } - - if(ret == ERR_NONE) { - return rfalNfcbCheckSensbRes(sensbRes, *sensbResLen); - } - - return ret; -} - -ReturnCode rfalNfcbPollerTechnologyDetection( - rfalComplianceMode compMode, - rfalNfcbSensbRes* sensbRes, - uint8_t* sensbResLen) { - NO_WARNING(compMode); - - return rfalNfcbPollerCheckPresence( - RFAL_NFCB_SENS_CMD_SENSB_REQ, RFAL_NFCB_SLOT_NUM_1, sensbRes, sensbResLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcbPollerCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcbListenDevice* nfcbDevList, - uint8_t* devCnt) { - bool colPending; /* dummy */ - return rfalNfcbPollerSlottedCollisionResolution( - compMode, - devLimit, - RFAL_NFCB_SLOT_NUM_1, - RFAL_NFCB_SLOT_NUM_16, - nfcbDevList, - devCnt, - &colPending); -} - -/*******************************************************************************/ -ReturnCode rfalNfcbPollerSlottedCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcbSlots initSlots, - rfalNfcbSlots endSlots, - rfalNfcbListenDevice* nfcbDevList, - uint8_t* devCnt, - bool* colPending) { - ReturnCode ret; - uint8_t slotsNum; - uint8_t slotCode; - uint8_t curDevCnt; - - /* Check parameters. In ISO | Activity 1.0 mode the initial slots must be 1 as continuation of Technology Detection */ - if((nfcbDevList == NULL) || (devCnt == NULL) || (colPending == NULL) || - (initSlots > RFAL_NFCB_SLOT_NUM_16) || (endSlots > RFAL_NFCB_SLOT_NUM_16) || - ((compMode == RFAL_COMPLIANCE_MODE_ISO) && (initSlots != RFAL_NFCB_SLOT_NUM_1))) { - return ERR_PARAM; - } - - /* Initialise as no error in case Activity 1.0 where the previous SENSB_RES from technology detection should be used */ - ret = ERR_NONE; - *devCnt = 0; - curDevCnt = 0; - *colPending = false; - - /* Send ALLB_REQ Activity 1.1 9.3.5.2 and 9.3.5.3 (Symbol 1 and 2) */ - if(compMode != RFAL_COMPLIANCE_MODE_ISO) { - ret = rfalNfcbPollerCheckPresence( - RFAL_NFCB_SENS_CMD_ALLB_REQ, - initSlots, - &nfcbDevList->sensbRes, - &nfcbDevList->sensbResLen); - if((ret != ERR_NONE) && (initSlots == RFAL_NFCB_SLOT_NUM_1)) { - return ret; - } - } - - /* Check if there was a transmission error on WUPB EMVCo 2.6 9.3.3.1 */ - if((compMode == RFAL_COMPLIANCE_MODE_EMV) && (nfcbDevList->sensbResLen == 0U)) { - return ERR_FRAMING; - } - - for(slotsNum = (uint8_t)initSlots; slotsNum <= (uint8_t)endSlots; slotsNum++) { - do { - /* Activity 1.1 9.3.5.23 - Symbol 22 */ - if((compMode == RFAL_COMPLIANCE_MODE_NFC) && (curDevCnt != 0U)) { - rfalNfcbPollerSleep(nfcbDevList[((*devCnt) - (uint8_t)1U)].sensbRes.nfcid0); - nfcbDevList[((*devCnt) - (uint8_t)1U)].isSleep = true; - } - - /* Send SENSB_REQ with number of slots if not the first Activity 1.1 9.3.5.24 - Symbol 23 */ - if((slotsNum != (uint8_t)initSlots) || *colPending) { - /* PRQA S 4342 1 # MISRA 10.5 - Layout of rfalNfcbSlots and above loop guarantee that no invalid enum values are created. */ - ret = rfalNfcbPollerCheckPresence( - RFAL_NFCB_SENS_CMD_SENSB_REQ, - (rfalNfcbSlots)slotsNum, - &nfcbDevList[*devCnt].sensbRes, - &nfcbDevList[*devCnt].sensbResLen); - } - - /* Activity 1.1 9.3.5.6 - Symbol 5 */ - slotCode = 0; - curDevCnt = 0; - *colPending = false; - - do { - /* Activity 1.1 9.3.5.26 - Symbol 25 */ - if(slotCode != 0U) { - ret = rfalNfcbPollerSlotMarker( - slotCode, - &nfcbDevList[*devCnt].sensbRes, - &nfcbDevList[*devCnt].sensbResLen); - } - - /* Activity 1.1 9.3.5.7 and 9.3.5.8 - Symbol 6 */ - if(ret != ERR_TIMEOUT) { - /* Activity 1.1 9.3.5.8 - Symbol 7 */ - if((rfalNfcbCheckSensbRes( - &nfcbDevList[*devCnt].sensbRes, nfcbDevList[*devCnt].sensbResLen) == - ERR_NONE) && - (ret == ERR_NONE)) { - nfcbDevList[*devCnt].isSleep = false; - - if(compMode == RFAL_COMPLIANCE_MODE_EMV) { - (*devCnt)++; - return ret; - } else if(compMode == RFAL_COMPLIANCE_MODE_ISO) { - /* Activity 1.0 9.3.5.8 - Symbol 7 */ - (*devCnt)++; - curDevCnt++; - - /* Activity 1.0 9.3.5.10 - Symbol 9 */ - if((*devCnt >= devLimit) || - (slotsNum == (uint8_t)RFAL_NFCB_SLOT_NUM_1)) { - return ret; - } - - /* Activity 1.0 9.3.5.11 - Symbol 10 */ - rfalNfcbPollerSleep(nfcbDevList[*devCnt - 1U].sensbRes.nfcid0); - nfcbDevList[*devCnt - 1U].isSleep = true; - } else if(compMode == RFAL_COMPLIANCE_MODE_NFC) { - /* Activity 1.1 9.3.5.10 and 9.3.5.11 - Symbol 9 and Symbol 11*/ - if(curDevCnt != 0U) { - rfalNfcbPollerSleep( - nfcbDevList[(*devCnt) - (uint8_t)1U].sensbRes.nfcid0); - nfcbDevList[(*devCnt) - (uint8_t)1U].isSleep = true; - } - - /* Activity 1.1 9.3.5.12 - Symbol 11 */ - (*devCnt)++; - curDevCnt++; - - /* Activity 1.1 9.3.5.6 - Symbol 13 */ - if((*devCnt >= devLimit) || - (slotsNum == (uint8_t)RFAL_NFCB_SLOT_NUM_1)) { - return ret; - } - } else { - /* MISRA 15.7 - Empty else */ - } - } else { - /* If deviceLimit is set to 0 the NFC Forum Device is configured to perform collision detection only Activity 1.0 and 1.1 9.3.5.5 - Symbol 4 */ - if((devLimit == 0U) && (slotsNum == (uint8_t)RFAL_NFCB_SLOT_NUM_1)) { - return ERR_RF_COLLISION; - } - - /* Activity 1.1 9.3.5.9 - Symbol 8 */ - *colPending = true; - } - } - - /* Activity 1.1 9.3.5.15 - Symbol 14 */ - slotCode++; - } while(slotCode < rfalNfcbNI2NumberOfSlots(slotsNum)); - - /* Activity 1.1 9.3.5.17 - Symbol 16 */ - if(!(*colPending)) { - return ERR_NONE; - } - - /* Activity 1.1 9.3.5.18 - Symbol 17 */ - } while( - curDevCnt != - 0U); /* If a collision is detected and card(s) were found on this loop keep the same number of available slots */ - } - - return ERR_NONE; -} - -/*******************************************************************************/ -uint32_t rfalNfcbTR2ToFDT(uint8_t tr2Code) { - /*******************************************************************************/ - /* MISRA 8.9 An object should be defined at block scope if its identifier only appears in a single function */ - /*! TR2 Table according to Digital 1.1 Table 33 */ - const uint16_t rfalNfcbTr2Table[] = {1792, 3328, 5376, 9472}; - /*******************************************************************************/ - - return rfalNfcbTr2Table[(tr2Code & RFAL_NFCB_SENSB_RES_PROTO_TR2_MASK)]; -} - -#endif /* RFAL_FEATURE_NFCB */ diff --git a/lib/ST25RFAL002/source/rfal_nfcf.c b/lib/ST25RFAL002/source/rfal_nfcf.c deleted file mode 100644 index 7b5e4d58f..000000000 --- a/lib/ST25RFAL002/source/rfal_nfcf.c +++ /dev/null @@ -1,585 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfcf.c - * - * \author Gustavo Patricio - * - * \brief Implementation of NFC-F Poller (FeliCa PCD) device - * - * The definitions and helpers methods provided by this module are - * aligned with NFC-F (FeliCa - JIS X6319-4) - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_nfcf.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_NFCF -#define RFAL_FEATURE_NFCF false /* NFC-F module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_NFCF - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ -#define RFAL_NFCF_SENSF_REQ_LEN_MIN \ - 5U /*!< SENSF_RES minimum length */ - -#define RFAL_NFCF_READ_WO_ENCRYPTION_MIN_LEN \ - 15U /*!< Minimum length for a Check Command T3T 5.4.1 */ -#define RFAL_NFCF_WRITE_WO_ENCRYPTION_MIN_LEN \ - 31U /*!< Minimum length for an Update Command T3T 5.5.1 */ - -#define RFAL_NFCF_CHECK_RES_MIN_LEN \ - 11U /*!< CHECK Response minimum length T3T 1.0 Table 8 */ -#define RFAL_NFCF_UPDATE_RES_MIN_LEN \ - 11U /*!< UPDATE Response minimum length T3T 1.0 Table 8 */ - -#define RFAL_NFCF_CHECK_REQ_MAX_LEN \ - 86U /*!< Max length of a Check request T3T 1.0 Table 7 */ -#define RFAL_NFCF_CHECK_REQ_MAX_SERV \ - 15U /*!< Max Services number on Check request T3T 1.0 5.4.1.5 */ -#define RFAL_NFCF_CHECK_REQ_MAX_BLOCK \ - 15U /*!< Max Blocks number on Check request T3T 1.0 5.4.1.10 */ -#define RFAL_NFCF_UPDATE_REQ_MAX_SERV \ - 15U /*!< Max Services number Update request T3T 1.0 5.4.1.5 */ -#define RFAL_NFCF_UPDATE_REQ_MAX_BLOCK \ - 13U /*!< Max Blocks number on Update request T3T 1.0 5.4.1.10 */ - -/*! MRT Check | Uupdate = (Tt3t x ((A+1) + n (B+1)) x 4^E) + dRWTt3t T3T 5.8 - Max values used: A = 7 ; B = 7 ; E = 3 ; n = 15 (NFC Forum n = 15, JIS n = 32) -*/ -#define RFAL_NFCF_MRT_CHECK_UPDATE ((4096 * (8 + (15 * 8)) * 64) + 16) - -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ -#define rfalNfcfSlots2CardNum(s) \ - ((uint8_t)(s) + 1U) /*!< Converts Time Slot Number (TSN) into num of slots */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! Structure/Buffer to hold the SENSF_RES with LEN byte prepended */ -typedef struct { - uint8_t LEN; /*!< NFC-F LEN byte */ - rfalNfcfSensfRes SENSF_RES; /*!< SENSF_RES */ -} rfalNfcfSensfResBuf; - -/*! Greedy collection for NFCF GRE_POLL_F Activity 1.0 Table 10 */ -typedef struct { - uint8_t pollFound; /*!< Number of devices found by the Poll */ - uint8_t pollCollision; /*!< Number of collisions detected */ - rfalFeliCaPollRes POLL_F[RFAL_NFCF_POLL_MAXCARDS]; /*!< GRE_POLL_F Activity 1.0 Table 10 */ -} rfalNfcfGreedyF; - -/*! NFC-F SENSF_REQ format Digital 1.1 8.6.1 */ -typedef struct { - uint8_t CMD; /*!< Command code: 00h */ - uint8_t SC[RFAL_NFCF_SENSF_SC_LEN]; /*!< System Code */ - uint8_t RC; /*!< Request Code */ - uint8_t TSN; /*!< Time Slot Number */ -} rfalNfcfSensfReq; - -/* -****************************************************************************** -* LOCAL VARIABLES -****************************************************************************** -*/ -static rfalNfcfGreedyF gRfalNfcfGreedyF; /*!< Activity's NFCF Greedy collection */ - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -static void rfalNfcfComputeValidSENF( - rfalNfcfListenDevice* outDevInfo, - uint8_t* curDevIdx, - uint8_t devLimit, - bool overwrite, - bool* nfcDepFound); - -/* -****************************************************************************** -* LOCAL VARIABLES -****************************************************************************** -*/ - -/*******************************************************************************/ -static void rfalNfcfComputeValidSENF( - rfalNfcfListenDevice* outDevInfo, - uint8_t* curDevIdx, - uint8_t devLimit, - bool overwrite, - bool* nfcDepFound) { - uint8_t tmpIdx; - bool duplicate; - const rfalNfcfSensfResBuf* sensfBuf; - rfalNfcfSensfResBuf sensfCopy; - - /*******************************************************************************/ - /* Go through all responses check if valid and duplicates */ - /*******************************************************************************/ - while((gRfalNfcfGreedyF.pollFound > 0U) && ((*curDevIdx) < devLimit)) { - duplicate = false; - gRfalNfcfGreedyF.pollFound--; - - /* MISRA 11.3 - Cannot point directly into different object type, use local copy */ - ST_MEMCPY( - (uint8_t*)&sensfCopy, - (uint8_t*)&gRfalNfcfGreedyF.POLL_F[gRfalNfcfGreedyF.pollFound], - sizeof(rfalNfcfSensfResBuf)); - - /* Point to received SENSF_RES */ - sensfBuf = &sensfCopy; - - /* Check for devices that are already in device list */ - for(tmpIdx = 0; tmpIdx < (*curDevIdx); tmpIdx++) { - if(ST_BYTECMP( - sensfBuf->SENSF_RES.NFCID2, - outDevInfo[tmpIdx].sensfRes.NFCID2, - RFAL_NFCF_NFCID2_LEN) == 0) { - duplicate = true; - break; - } - } - - /* If is a duplicate skip this (and not to overwrite)*/ - if(duplicate && !overwrite) { - continue; - } - - /* Check if response length is OK */ - if(((sensfBuf->LEN - RFAL_NFCF_HEADER_LEN) < RFAL_NFCF_SENSF_RES_LEN_MIN) || - ((sensfBuf->LEN - RFAL_NFCF_HEADER_LEN) > RFAL_NFCF_SENSF_RES_LEN_MAX)) { - continue; - } - - /* Check if the response is a SENSF_RES / Polling response */ - if(sensfBuf->SENSF_RES.CMD != (uint8_t)RFAL_NFCF_CMD_POLLING_RES) { - continue; - } - - /* Check if is an overwrite request or new device*/ - if(duplicate && overwrite) { - /* overwrite deviceInfo/GRE_SENSF_RES with SENSF_RES */ - outDevInfo[tmpIdx].sensfResLen = (sensfBuf->LEN - RFAL_NFCF_LENGTH_LEN); - ST_MEMCPY( - &outDevInfo[tmpIdx].sensfRes, - &sensfBuf->SENSF_RES, - outDevInfo[tmpIdx].sensfResLen); - continue; - } else { - /* fill deviceInfo/GRE_SENSF_RES with new SENSF_RES */ - outDevInfo[(*curDevIdx)].sensfResLen = (sensfBuf->LEN - RFAL_NFCF_LENGTH_LEN); - ST_MEMCPY( - &outDevInfo[(*curDevIdx)].sensfRes, - &sensfBuf->SENSF_RES, - outDevInfo[(*curDevIdx)].sensfResLen); - } - - /* Check if this device supports NFC-DEP and signal it (ACTIVITY 1.1 9.3.6.63) */ - *nfcDepFound = rfalNfcfIsNfcDepSupported(&outDevInfo[(*curDevIdx)]); - - (*curDevIdx)++; - } -} - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -ReturnCode rfalNfcfPollerInitialize(rfalBitRate bitRate) { - ReturnCode ret; - - if((bitRate != RFAL_BR_212) && (bitRate != RFAL_BR_424)) { - return ERR_PARAM; - } - - EXIT_ON_ERR(ret, rfalSetMode(RFAL_MODE_POLL_NFCF, bitRate, bitRate)); - rfalSetErrorHandling(RFAL_ERRORHANDLING_NFC); - - rfalSetGT(RFAL_GT_NFCF); - rfalSetFDTListen(RFAL_FDT_LISTEN_NFCF_POLLER); - rfalSetFDTPoll(RFAL_FDT_POLL_NFCF_POLLER); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcfPollerPoll( - rfalFeliCaPollSlots slots, - uint16_t sysCode, - uint8_t reqCode, - rfalFeliCaPollRes* cardList, - uint8_t* devCnt, - uint8_t* collisions) { - return rfalFeliCaPoll( - slots, sysCode, reqCode, cardList, rfalNfcfSlots2CardNum(slots), devCnt, collisions); -} - -/*******************************************************************************/ -ReturnCode rfalNfcfPollerCheckPresence(void) { - gRfalNfcfGreedyF.pollFound = 0; - gRfalNfcfGreedyF.pollCollision = 0; - - /* ACTIVITY 1.0 & 1.1 - 9.2.3.17 SENSF_REQ must be with number of slots equal to 4 - * SC must be 0xFFFF - * RC must be 0x00 (No system code info required) */ - return rfalFeliCaPoll( - RFAL_FELICA_4_SLOTS, - RFAL_NFCF_SYSTEMCODE, - RFAL_FELICA_POLL_RC_NO_REQUEST, - gRfalNfcfGreedyF.POLL_F, - rfalNfcfSlots2CardNum(RFAL_FELICA_4_SLOTS), - &gRfalNfcfGreedyF.pollFound, - &gRfalNfcfGreedyF.pollCollision); -} - -/*******************************************************************************/ -ReturnCode rfalNfcfPollerCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcfListenDevice* nfcfDevList, - uint8_t* devCnt) { - ReturnCode ret; - bool nfcDepFound; - - if((nfcfDevList == NULL) || (devCnt == NULL)) { - return ERR_PARAM; - } - - *devCnt = 0; - nfcDepFound = false; - - /*******************************************************************************************/ - /* ACTIVITY 1.0 - 9.3.6.3 Copy valid SENSF_RES in GRE_POLL_F into GRE_SENSF_RES */ - /* ACTIVITY 1.0 - 9.3.6.6 The NFC Forum Device MUST remove all entries from GRE_SENSF_RES[]*/ - /* ACTIVITY 1.1 - 9.3.63.59 Populate GRE_SENSF_RES with data from GRE_POLL_F */ - /* */ - /* CON_DEVICES_LIMIT = 0 Just check if devices from Tech Detection exceeds -> always true */ - /* Allow the number of slots open on Technology Detection */ - /*******************************************************************************************/ - rfalNfcfComputeValidSENF( - nfcfDevList, - devCnt, - ((devLimit == 0U) ? rfalNfcfSlots2CardNum(RFAL_FELICA_4_SLOTS) : devLimit), - false, - &nfcDepFound); - - /*******************************************************************************/ - /* ACTIVITY 1.0 - 9.3.6.4 */ - /* ACTIVITY 1.1 - 9.3.63.60 Check if devices found are lower than the limit */ - /* and send a SENSF_REQ if so */ - /*******************************************************************************/ - if(*devCnt < devLimit) { - /* ACTIVITY 1.0 - 9.3.6.5 Copy valid SENSF_RES and then to remove it - * ACTIVITY 1.1 - 9.3.6.65 Copy and filter duplicates - * For now, due to some devices keep generating different nfcid2, we use 1.0 - * Phones detected: Samsung Galaxy Nexus,Samsung Galaxy S3,Samsung Nexus S */ - *devCnt = 0; - - ret = rfalNfcfPollerPoll( - RFAL_FELICA_16_SLOTS, - RFAL_NFCF_SYSTEMCODE, - RFAL_FELICA_POLL_RC_NO_REQUEST, - gRfalNfcfGreedyF.POLL_F, - &gRfalNfcfGreedyF.pollFound, - &gRfalNfcfGreedyF.pollCollision); - if(ret == ERR_NONE) { - rfalNfcfComputeValidSENF(nfcfDevList, devCnt, devLimit, false, &nfcDepFound); - } - - /*******************************************************************************/ - /* ACTIVITY 1.1 - 9.3.6.63 Check if any device supports NFC DEP */ - /*******************************************************************************/ - if(nfcDepFound && (compMode == RFAL_COMPLIANCE_MODE_NFC)) { - ret = rfalNfcfPollerPoll( - RFAL_FELICA_16_SLOTS, - RFAL_NFCF_SYSTEMCODE, - RFAL_FELICA_POLL_RC_SYSTEM_CODE, - gRfalNfcfGreedyF.POLL_F, - &gRfalNfcfGreedyF.pollFound, - &gRfalNfcfGreedyF.pollCollision); - if(ret == ERR_NONE) { - rfalNfcfComputeValidSENF(nfcfDevList, devCnt, devLimit, true, &nfcDepFound); - } - } - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcfPollerCheck( - const uint8_t* nfcid2, - const rfalNfcfServBlockListParam* servBlock, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvdLen) { - uint8_t txBuf[RFAL_NFCF_CHECK_REQ_MAX_LEN]; - uint8_t msgIt; - uint8_t i; - ReturnCode ret; - const uint8_t* checkRes; - - /* Check parameters */ - if((nfcid2 == NULL) || (rxBuf == NULL) || (servBlock == NULL) || (servBlock->numBlock == 0U) || - (servBlock->numBlock > RFAL_NFCF_CHECK_REQ_MAX_BLOCK) || (servBlock->numServ == 0U) || - (servBlock->numServ > RFAL_NFCF_CHECK_REQ_MAX_SERV) || - (rxBufLen < (RFAL_NFCF_LENGTH_LEN + RFAL_NFCF_CHECK_RES_MIN_LEN))) { - return ERR_PARAM; - } - - msgIt = 0; - - /*******************************************************************************/ - /* Compose CHECK command/request */ - - txBuf[msgIt++] = RFAL_NFCF_CMD_READ_WITHOUT_ENCRYPTION; /* Command Code */ - - ST_MEMCPY(&txBuf[msgIt], nfcid2, RFAL_NFCF_NFCID2_LEN); /* NFCID2 */ - msgIt += RFAL_NFCF_NFCID2_LEN; - - txBuf[msgIt++] = servBlock->numServ; /* NoS */ - for(i = 0; i < servBlock->numServ; i++) { - txBuf[msgIt++] = (uint8_t)((servBlock->servList[i] >> 0U) & 0xFFU); /* Service Code */ - txBuf[msgIt++] = (uint8_t)((servBlock->servList[i] >> 8U) & 0xFFU); - } - - txBuf[msgIt++] = servBlock->numBlock; /* NoB */ - for(i = 0; i < servBlock->numBlock; i++) { - txBuf[msgIt++] = - servBlock->blockList[i].conf; /* Block list element conf (Flag|Access|Service) */ - if((servBlock->blockList[i].conf & 0x80U) != - 0U) /* Check if 2 or 3 byte block list element */ - { - txBuf[msgIt++] = - (uint8_t)(servBlock->blockList[i].blockNum & 0xFFU); /* 1byte Block Num */ - } else { - txBuf[msgIt++] = - (uint8_t)((servBlock->blockList[i].blockNum >> 0U) & 0xFFU); /* 2byte Block Num */ - txBuf[msgIt++] = (uint8_t)((servBlock->blockList[i].blockNum >> 8U) & 0xFFU); - } - } - - /*******************************************************************************/ - /* Transceive CHECK command/request */ - ret = rfalTransceiveBlockingTxRx( - txBuf, - msgIt, - rxBuf, - rxBufLen, - rcvdLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCF_MRT_CHECK_UPDATE); - - if(ret == ERR_NONE) { - /* Skip LEN byte */ - checkRes = (rxBuf + RFAL_NFCF_LENGTH_LEN); - - /* Check response length */ - if(*rcvdLen < (RFAL_NFCF_LENGTH_LEN + RFAL_NFCF_CHECKUPDATE_RES_ST2_POS)) { - ret = ERR_PROTO; - } - /* Check for a valid response */ - else if( - (checkRes[RFAL_NFCF_CMD_POS] != (uint8_t)RFAL_NFCF_CMD_READ_WITHOUT_ENCRYPTION_RES) || - (checkRes[RFAL_NFCF_CHECKUPDATE_RES_ST1_POS] != RFAL_NFCF_STATUS_FLAG_SUCCESS) || - (checkRes[RFAL_NFCF_CHECKUPDATE_RES_ST2_POS] != RFAL_NFCF_STATUS_FLAG_SUCCESS)) { - ret = ERR_REQUEST; - } - /* CHECK succesfull, remove header */ - else { - (*rcvdLen) -= (RFAL_NFCF_LENGTH_LEN + RFAL_NFCF_CHECKUPDATE_RES_NOB_POS); - - if(*rcvdLen > 0U) { - ST_MEMMOVE(rxBuf, &checkRes[RFAL_NFCF_CHECKUPDATE_RES_NOB_POS], (*rcvdLen)); - } - } - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalNfcfPollerUpdate( - const uint8_t* nfcid2, - const rfalNfcfServBlockListParam* servBlock, - uint8_t* txBuf, - uint16_t txBufLen, - const uint8_t* blockData, - uint8_t* rxBuf, - uint16_t rxBufLen) { - uint8_t i; - uint16_t msgIt; - uint16_t rcvdLen; - uint16_t auxLen; - const uint8_t* updateRes; - ReturnCode ret; - - /* Check parameters */ - if((nfcid2 == NULL) || (rxBuf == NULL) || (servBlock == NULL) || (txBuf == NULL) || - (servBlock->numBlock == 0U) || (servBlock->numBlock > RFAL_NFCF_UPDATE_REQ_MAX_BLOCK) || - (servBlock->numServ == 0U) || (servBlock->numServ > RFAL_NFCF_UPDATE_REQ_MAX_SERV) || - (rxBufLen < (RFAL_NFCF_LENGTH_LEN + RFAL_NFCF_UPDATE_RES_MIN_LEN))) { - return ERR_PARAM; - } - - /* Calculate required txBuffer lenth */ - auxLen = (uint16_t)( RFAL_NFCF_CMD_LEN + RFAL_NFCF_NFCID2_LEN + ( servBlock->numServ * sizeof(rfalNfcfServ) ) + - (servBlock->numBlock * sizeof(rfalNfcfBlockListElem)) + (uint16_t)((uint16_t)servBlock->numBlock * RFAL_NFCF_BLOCK_LEN) ); - - /* Check whether the provided buffer is sufficient for this request */ - if(txBufLen < auxLen) { - return ERR_PARAM; - } - - msgIt = 0; - - /*******************************************************************************/ - /* Compose UPDATE command/request */ - - txBuf[msgIt++] = RFAL_NFCF_CMD_WRITE_WITHOUT_ENCRYPTION; /* Command Code */ - - ST_MEMCPY(&txBuf[msgIt], nfcid2, RFAL_NFCF_NFCID2_LEN); /* NFCID2 */ - msgIt += RFAL_NFCF_NFCID2_LEN; - - txBuf[msgIt++] = servBlock->numServ; /* NoS */ - for(i = 0; i < servBlock->numServ; i++) { - txBuf[msgIt++] = (uint8_t)((servBlock->servList[i] >> 0U) & 0xFFU); /* Service Code */ - txBuf[msgIt++] = (uint8_t)((servBlock->servList[i] >> 8U) & 0xFFU); - } - - txBuf[msgIt++] = servBlock->numBlock; /* NoB */ - for(i = 0; i < servBlock->numBlock; i++) { - txBuf[msgIt++] = - servBlock->blockList[i].conf; /* Block list element conf (Flag|Access|Service) */ - if((servBlock->blockList[i].conf & 0x80U) != - 0U) /* Check if 2 or 3 byte block list element */ - { - txBuf[msgIt++] = - (uint8_t)(servBlock->blockList[i].blockNum & 0xFFU); /* 1byte Block Num */ - } else { - txBuf[msgIt++] = - (uint8_t)((servBlock->blockList[i].blockNum >> 0U) & 0xFFU); /* 2byte Block Num */ - txBuf[msgIt++] = (uint8_t)((servBlock->blockList[i].blockNum >> 8U) & 0xFFU); - } - } - - auxLen = ((uint16_t)servBlock->numBlock * RFAL_NFCF_BLOCK_LEN); - ST_MEMCPY(&txBuf[msgIt], blockData, auxLen); /* Block Data */ - msgIt += auxLen; - - /*******************************************************************************/ - /* Transceive UPDATE command/request */ - ret = rfalTransceiveBlockingTxRx( - txBuf, - msgIt, - rxBuf, - rxBufLen, - &rcvdLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCF_MRT_CHECK_UPDATE); - - if(ret == ERR_NONE) { - /* Skip LEN byte */ - updateRes = (rxBuf + RFAL_NFCF_LENGTH_LEN); - - /* Check response length */ - if(rcvdLen < (RFAL_NFCF_LENGTH_LEN + RFAL_NFCF_CHECKUPDATE_RES_ST2_POS)) { - ret = ERR_PROTO; - } - /* Check for a valid response */ - else if( - (updateRes[RFAL_NFCF_CMD_POS] != - (uint8_t)RFAL_NFCF_CMD_WRITE_WITHOUT_ENCRYPTION_RES) || - (updateRes[RFAL_NFCF_CHECKUPDATE_RES_ST1_POS] != RFAL_NFCF_STATUS_FLAG_SUCCESS) || - (updateRes[RFAL_NFCF_CHECKUPDATE_RES_ST2_POS] != RFAL_NFCF_STATUS_FLAG_SUCCESS)) { - ret = ERR_REQUEST; - } else { - /* MISRA 15.7 - Empty else */ - } - } - - return ret; -} - -/*******************************************************************************/ -bool rfalNfcfListenerIsT3TReq(const uint8_t* buf, uint16_t bufLen, uint8_t* nfcid2) { - /* Check cmd byte */ - switch(*buf) { - case RFAL_NFCF_CMD_READ_WITHOUT_ENCRYPTION: - if(bufLen < RFAL_NFCF_READ_WO_ENCRYPTION_MIN_LEN) { - return false; - } - break; - - case RFAL_NFCF_CMD_WRITE_WITHOUT_ENCRYPTION: - if(bufLen < RFAL_NFCF_WRITE_WO_ENCRYPTION_MIN_LEN) { - return false; - } - break; - - default: - return false; - } - - /* Output NFID2 if requested */ - if(nfcid2 != NULL) { - ST_MEMCPY(nfcid2, &buf[RFAL_NFCF_CMD_LEN], RFAL_NFCF_NFCID2_LEN); - } - - return true; -} - -#endif /* RFAL_FEATURE_NFCF */ diff --git a/lib/ST25RFAL002/source/rfal_nfcv.c b/lib/ST25RFAL002/source/rfal_nfcv.c deleted file mode 100644 index 22c9b8741..000000000 --- a/lib/ST25RFAL002/source/rfal_nfcv.c +++ /dev/null @@ -1,1057 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_nfcv.c - * - * \author Gustavo Patricio - * - * \brief Implementation of NFC-V Poller (ISO15693) device - * - * The definitions and helpers methods provided by this module are - * aligned with NFC-V (ISO15693) - * - * The definitions and helpers methods provided by this module - * are aligned with NFC-V Digital 2.1 - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_nfcv.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_NFCV -#define RFAL_FEATURE_NFCV false /* NFC-V module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_NFCV - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_NFCV_INV_REQ_FLAG \ - 0x06U /*!< INVENTORY_REQ INV_FLAG Digital 2.1 9.6.1 */ -#define RFAL_NFCV_MASKVAL_MAX_LEN \ - 8U /*!< Mask value max length: 64 bits (UID length) */ -#define RFAL_NFCV_MASKVAL_MAX_1SLOT_LEN \ - 64U /*!< Mask value max length in 1 Slot mode in bits Digital 2.1 9.6.1.6 */ -#define RFAL_NFCV_MASKVAL_MAX_16SLOT_LEN \ - 60U /*!< Mask value max length in 16 Slot mode in bits Digital 2.1 9.6.1.6 */ -#define RFAL_NFCV_MAX_SLOTS \ - 16U /*!< NFC-V max number of Slots */ -#define RFAL_NFCV_INV_REQ_HEADER_LEN \ - 3U /*!< INVENTORY_REQ header length (INV_FLAG, CMD, MASK_LEN) */ -#define RFAL_NFCV_INV_RES_LEN \ - 10U /*!< INVENTORY_RES length */ -#define RFAL_NFCV_WR_MUL_REQ_HEADER_LEN \ - 4U /*!< Write Multiple header length (INV_FLAG, CMD, [UID], BNo, Bno) */ - -#define RFAL_NFCV_CMD_LEN \ - 1U /*!< Commandbyte length */ -#define RFAL_NFCV_FLAG_POS \ - 0U /*!< Flag byte position */ -#define RFAL_NFCV_FLAG_LEN \ - 1U /*!< Flag byte length */ -#define RFAL_NFCV_DATASTART_POS \ - 1U /*!< Position of start of data */ -#define RFAL_NFCV_DSFI_LEN \ - 1U /*!< DSFID length */ -#define RFAL_NFCV_SLPREQ_REQ_FLAG \ - 0x22U /*!< SLPV_REQ request flags Digital 2.0 (Candidate) 9.7.1.1 */ -#define RFAL_NFCV_RES_FLAG_NOERROR \ - 0x00U /*!< RES_FLAG indicating no error (checked during activation) */ - -#define RFAL_NFCV_MAX_COLL_SUPPORTED \ - 16U /*!< Maximum number of collisions supported by the Anticollision loop */ - -#define RFAL_NFCV_FDT_MAX \ - rfalConvMsTo1fc(20) /*!< Maximum Wait time FDTV,EOF and MAX2 Digital 2.1 B.5*/ -#define RFAL_NFCV_FDT_MAX1 \ - 4394U /*!< Read alike command FWT FDTV,LISTEN,MAX1 Digital 2.0 B.5 */ - -/*! Time from special frame to EOF - * ISO15693 2009 10.4.2 : 20ms - * NFC Forum defines Digital 2.0 9.7.4 : FDTV,EOF = [10 ; 20]ms - */ -#define RFAL_NFCV_FDT_EOF 20U - -/*! Time between slots - ISO 15693 defines t3min depending on modulation depth and data rate. - * With only high-bitrate supported, AM modulation and a length of 12 bytes (96bits) for INV_RES we get: - * - ISO t3min = 96/26 ms + 300us = 4 ms - * - NFC Forum defines FDTV,INVENT_NORES = (4394 + 2048)/fc. Digital 2.0 B.5*/ -#define RFAL_NFCV_FDT_V_INVENT_NORES 4U - -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ - -/*! Checks if a valid INVENTORY_RES is valid Digital 2.2 9.6.2.1 & 9.6.2.3 */ -#define rfalNfcvCheckInvRes(f, l) \ - (((l) == rfalConvBytesToBits(RFAL_NFCV_INV_RES_LEN + RFAL_NFCV_CRC_LEN)) && \ - ((f) == RFAL_NFCV_RES_FLAG_NOERROR)) - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! NFC-V INVENTORY_REQ format Digital 2.0 9.6.1 */ -typedef struct { - uint8_t INV_FLAG; /*!< Inventory Flags */ - uint8_t CMD; /*!< Command code: 01h */ - uint8_t MASK_LEN; /*!< Mask Value Length */ - uint8_t MASK_VALUE[RFAL_NFCV_MASKVAL_MAX_LEN]; /*!< Mask Value */ -} rfalNfcvInventoryReq; - -/*! NFC-V SLP_REQ format Digital 2.0 (Candidate) 9.7.1 */ -typedef struct { - uint8_t REQ_FLAG; /*!< Request Flags */ - uint8_t CMD; /*!< Command code: 02h */ - uint8_t UID[RFAL_NFCV_UID_LEN]; /*!< Mask Value */ -} rfalNfcvSlpvReq; - -/*! Container for a collision found during Anticollision loop */ -typedef struct { - uint8_t maskLen; - uint8_t maskVal[RFAL_NFCV_MASKVAL_MAX_LEN]; -} rfalNfcvCollision; - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -static ReturnCode rfalNfcvParseError(uint8_t err); - -/* -****************************************************************************** -* LOCAL VARIABLES -****************************************************************************** -*/ - -/* -****************************************************************************** -* LOCAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -static ReturnCode rfalNfcvParseError(uint8_t err) { - switch(err) { - case RFAL_NFCV_ERROR_CMD_NOT_SUPPORTED: - case RFAL_NFCV_ERROR_OPTION_NOT_SUPPORTED: - return ERR_NOTSUPP; - - case RFAL_NFCV_ERROR_CMD_NOT_RECOGNIZED: - return ERR_PROTO; - - case RFAL_NFCV_ERROR_WRITE_FAILED: - return ERR_WRITE; - - default: - return ERR_REQUEST; - } -} - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerInitialize(void) { - ReturnCode ret; - - EXIT_ON_ERR(ret, rfalSetMode(RFAL_MODE_POLL_NFCV, RFAL_BR_26p48, RFAL_BR_26p48)); - rfalSetErrorHandling(RFAL_ERRORHANDLING_NFC); - - rfalSetGT(RFAL_GT_NFCV); - rfalSetFDTListen(RFAL_FDT_LISTEN_NFCV_POLLER); - rfalSetFDTPoll(RFAL_FDT_POLL_NFCV_POLLER); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerCheckPresence(rfalNfcvInventoryRes* invRes) { - ReturnCode ret; - - /* INVENTORY_REQ with 1 slot and no Mask Activity 2.0 (Candidate) 9.2.3.32 */ - ret = rfalNfcvPollerInventory(RFAL_NFCV_NUM_SLOTS_1, 0, NULL, invRes, NULL); - - if((ret == ERR_RF_COLLISION) || (ret == ERR_CRC) || (ret == ERR_FRAMING) || - (ret == ERR_PROTO)) { - ret = ERR_NONE; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerInventory( - rfalNfcvNumSlots nSlots, - uint8_t maskLen, - const uint8_t* maskVal, - rfalNfcvInventoryRes* invRes, - uint16_t* rcvdLen) { - ReturnCode ret; - rfalNfcvInventoryReq invReq; - uint16_t rxLen; - - if(((maskVal == NULL) && (maskLen != 0U)) || (invRes == NULL)) { - return ERR_PARAM; - } - - invReq.INV_FLAG = (RFAL_NFCV_INV_REQ_FLAG | (uint8_t)nSlots); - invReq.CMD = RFAL_NFCV_CMD_INVENTORY; - invReq.MASK_LEN = (uint8_t)MIN( - maskLen, - ((nSlots == RFAL_NFCV_NUM_SLOTS_1) ? - RFAL_NFCV_MASKVAL_MAX_1SLOT_LEN : - RFAL_NFCV_MASKVAL_MAX_16SLOT_LEN)); /* Digital 2.0 9.6.1.6 */ - - if((rfalConvBitsToBytes(invReq.MASK_LEN) > 0U) && (maskVal != NULL)) /* MISRA 21.18 & 1.3 */ - { - ST_MEMCPY(invReq.MASK_VALUE, maskVal, rfalConvBitsToBytes(invReq.MASK_LEN)); - } - - ret = rfalISO15693TransceiveAnticollisionFrame( - (uint8_t*)&invReq, - (uint8_t)(RFAL_NFCV_INV_REQ_HEADER_LEN + rfalConvBitsToBytes(invReq.MASK_LEN)), - (uint8_t*)invRes, - sizeof(rfalNfcvInventoryRes), - &rxLen); - - /* Check for optional output parameter */ - if(rcvdLen != NULL) { - *rcvdLen = rxLen; - } - - if(ret == ERR_NONE) { - /* Check for valid INVENTORY_RES Digital 2.2 9.6.2.1 & 9.6.2.3 */ - if(!rfalNfcvCheckInvRes(invRes->RES_FLAG, rxLen)) { - return ERR_PROTO; - } - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerCollisionResolution( - rfalComplianceMode compMode, - uint8_t devLimit, - rfalNfcvListenDevice* nfcvDevList, - uint8_t* devCnt) { - ReturnCode ret; - uint8_t slotNum; - uint16_t rcvdLen; - uint8_t colIt; - uint8_t colCnt; - uint8_t colPos; - bool colPending; - rfalNfcvCollision colFound[RFAL_NFCV_MAX_COLL_SUPPORTED]; - - if((nfcvDevList == NULL) || (devCnt == NULL)) { - return ERR_PARAM; - } - - /* Initialize parameters */ - *devCnt = 0; - colIt = 0; - colCnt = 0; - colPending = false; - ST_MEMSET(colFound, 0x00, (sizeof(rfalNfcvCollision) * RFAL_NFCV_MAX_COLL_SUPPORTED)); - - if(devLimit > 0U) /* MISRA 21.18 */ - { - ST_MEMSET(nfcvDevList, 0x00, (sizeof(rfalNfcvListenDevice) * devLimit)); - } - - NO_WARNING( - colPending); /* colPending is not exposed externally, in future it might become exposed/ouput parameter */ - - if(compMode == RFAL_COMPLIANCE_MODE_NFC) { - /* Send INVENTORY_REQ with one slot Activity 2.1 9.3.7.1 (Symbol 0) */ - ret = rfalNfcvPollerInventory(RFAL_NFCV_NUM_SLOTS_1, 0, NULL, &nfcvDevList->InvRes, NULL); - - if(ret == ERR_TIMEOUT) /* Exit if no device found Activity 2.1 9.3.7.2 (Symbol 1) */ - { - return ERR_NONE; - } - if(ret == - ERR_NONE) /* Device found without transmission error/collision Activity 2.1 9.3.7.3 (Symbol 2) */ - { - (*devCnt)++; - return ERR_NONE; - } - - /* A Collision has been identified Activity 2.1 9.3.7.4 (Symbol 3) */ - colPending = true; - colCnt = 1; - - /* Check if the Collision Resolution is set to perform only Collision detection Activity 2.1 9.3.7.5 (Symbol 4)*/ - if(devLimit == 0U) { - return ERR_RF_COLLISION; - } - - platformDelay(RFAL_NFCV_FDT_V_INVENT_NORES); - - /*******************************************************************************/ - /* Collisions pending, Anticollision loop must be executed */ - /*******************************************************************************/ - } else { - /* Advance to 16 slots below without mask. Will give a good chance to identify multiple cards */ - colPending = true; - colCnt = 1; - } - - /* Execute until all collisions are resolved Activity 2.1 9.3.7.18 (Symbol 17) */ - do { - /* Activity 2.1 9.3.7.7 (Symbol 6 / 7) */ - colPending = false; - slotNum = 0; - - do { - if(slotNum == 0U) { - /* Send INVENTORY_REQ with 16 slots Activity 2.1 9.3.7.9 (Symbol 8) */ - ret = rfalNfcvPollerInventory( - RFAL_NFCV_NUM_SLOTS_16, - colFound[colIt].maskLen, - colFound[colIt].maskVal, - &nfcvDevList[(*devCnt)].InvRes, - &rcvdLen); - } else { - ret = rfalISO15693TransceiveEOFAnticollision( - (uint8_t*)&nfcvDevList[(*devCnt)].InvRes, - sizeof(rfalNfcvInventoryRes), - &rcvdLen); - } - slotNum++; - - /*******************************************************************************/ - if(ret != ERR_TIMEOUT) { - if(rcvdLen < - rfalConvBytesToBits( - RFAL_NFCV_INV_RES_LEN + - RFAL_NFCV_CRC_LEN)) { /* If only a partial frame was received make sure the FDT_V_INVENT_NORES is fulfilled */ - platformDelay(RFAL_NFCV_FDT_V_INVENT_NORES); - } - - /* Check if response is a correct frame (no TxRx error) Activity 2.1 9.3.7.11 (Symbol 10)*/ - if((ret == ERR_NONE) || (ret == ERR_PROTO)) { - /* Check if the device found is already on the list and its response is a valid INVENTORY_RES */ - if(rfalNfcvCheckInvRes(nfcvDevList[(*devCnt)].InvRes.RES_FLAG, rcvdLen)) { - /* Activity 2.1 9.3.7.12 (Symbol 11) */ - (*devCnt)++; - } - } else /* Treat everything else as collision */ - { - /* Activity 2.1 9.3.7.17 (Symbol 16) */ - colPending = true; - - /*******************************************************************************/ - /* Ensure that this collision still fits on the container */ - if(colCnt < RFAL_NFCV_MAX_COLL_SUPPORTED) { - /* Store this collision on the container to be resolved later */ - /* Activity 2.1 9.3.7.17 (Symbol 16): add the collision information - * (MASK_VAL + SN) to the list containing the collision information */ - ST_MEMCPY( - colFound[colCnt].maskVal, colFound[colIt].maskVal, RFAL_NFCV_UID_LEN); - colPos = colFound[colIt].maskLen; - colFound[colCnt].maskVal[(colPos / RFAL_BITS_IN_BYTE)] &= - (uint8_t)((1U << (colPos % RFAL_BITS_IN_BYTE)) - 1U); - colFound[colCnt].maskVal[(colPos / RFAL_BITS_IN_BYTE)] |= - (uint8_t)((slotNum - 1U) << (colPos % RFAL_BITS_IN_BYTE)); - colFound[colCnt].maskVal[((colPos / RFAL_BITS_IN_BYTE) + 1U)] = - (uint8_t)((slotNum - 1U) >> (RFAL_BITS_IN_BYTE - (colPos % RFAL_BITS_IN_BYTE))); - - colFound[colCnt].maskLen = (colFound[colIt].maskLen + 4U); - - colCnt++; - } - } - } else { - /* Timeout */ - platformDelay(RFAL_NFCV_FDT_V_INVENT_NORES); - } - - /* Check if devices found have reached device limit Activity 2.1 9.3.7.13 (Symbol 12) */ - if(*devCnt >= devLimit) { - return ERR_NONE; - } - - } while(slotNum < RFAL_NFCV_MAX_SLOTS); /* Slot loop */ - colIt++; - } while(colIt < colCnt); /* Collisions found loop */ - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerSleepCollisionResolution( - uint8_t devLimit, - rfalNfcvListenDevice* nfcvDevList, - uint8_t* devCnt) { - uint8_t tmpDevCnt; - ReturnCode ret; - uint8_t i; - - if((nfcvDevList == NULL) || (devCnt == NULL)) { - return ERR_PARAM; - } - - *devCnt = 0; - - do { - tmpDevCnt = 0; - ret = rfalNfcvPollerCollisionResolution( - RFAL_COMPLIANCE_MODE_ISO, (devLimit - *devCnt), &nfcvDevList[*devCnt], &tmpDevCnt); - - for(i = *devCnt; i < (*devCnt + tmpDevCnt); i++) { - rfalNfcvPollerSleep(0x00, nfcvDevList[i].InvRes.UID); - nfcvDevList[i].isSleep = true; - } - *devCnt += tmpDevCnt; - } while((ret == ERR_NONE) && (tmpDevCnt > 0U) && (*devCnt < devLimit)); - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerSleep(uint8_t flags, const uint8_t* uid) { - ReturnCode ret; - rfalNfcvSlpvReq slpReq; - uint8_t rxBuf; /* dummy buffer, just to perform Rx */ - - if(uid == NULL) { - return ERR_PARAM; - } - - /* Compute SLPV_REQ */ - slpReq.REQ_FLAG = - (flags | - (uint8_t) - RFAL_NFCV_REQ_FLAG_ADDRESS); /* Should be with UID according Digital 2.0 (Candidate) 9.7.1.1 */ - slpReq.CMD = RFAL_NFCV_CMD_SLPV; - ST_MEMCPY(slpReq.UID, uid, RFAL_NFCV_UID_LEN); - - /* NFC Forum device SHALL wait at least FDTVpp to consider the SLPV acknowledged (FDTVpp = FDTVpoll) Digital 2.0 (Candidate) 9.7 9.8.2 */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&slpReq, - sizeof(rfalNfcvSlpvReq), - &rxBuf, - sizeof(rxBuf), - NULL, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCV_FDT_MAX1); - if(ret != ERR_TIMEOUT) { - return ret; - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerSelect(uint8_t flags, const uint8_t* uid) { - uint16_t rcvLen; - rfalNfcvGenericRes res; - - if(uid == NULL) { - return ERR_PARAM; - } - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_SELECT, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - NULL, - 0U, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint8_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t bn; - - bn = blockNum; - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_READ_SINGLE_BLOCK, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - &bn, - sizeof(uint8_t), - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerWriteSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint8_t blockNum, - const uint8_t* wrData, - uint8_t blockLen) { - uint8_t data[(RFAL_NFCV_BLOCKNUM_LEN + RFAL_NFCV_MAX_BLOCK_LEN)]; - uint8_t dataLen; - uint16_t rcvLen; - rfalNfcvGenericRes res; - - /* Check for valid parameters */ - if((blockLen == 0U) || (blockLen > (uint8_t)RFAL_NFCV_MAX_BLOCK_LEN) || (wrData == NULL)) { - return ERR_PARAM; - } - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = blockNum; /* Set Block Number (8 bits) */ - ST_MEMCPY(&data[dataLen], wrData, blockLen); /* Append Block data to write */ - dataLen += blockLen; - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_WRITE_SINGLE_BLOCK, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - data, - dataLen, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerLockBlock(uint8_t flags, const uint8_t* uid, uint8_t blockNum) { - uint16_t rcvLen; - rfalNfcvGenericRes res; - uint8_t bn; - - bn = blockNum; - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_LOCK_BLOCK, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - &bn, - sizeof(uint8_t), - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint8_t firstBlockNum, - uint8_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[(RFAL_NFCV_BLOCKNUM_LEN + RFAL_NFCV_BLOCKNUM_LEN)]; - uint8_t dataLen; - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = firstBlockNum; /* Set first Block Number */ - data[dataLen++] = numOfBlocks; /* Set number of blocks to read */ - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_READ_MULTIPLE_BLOCKS, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerWriteMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint8_t firstBlockNum, - uint8_t numOfBlocks, - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t blockLen, - const uint8_t* wrData, - uint16_t wrDataLen) { - ReturnCode ret; - uint16_t rcvLen; - uint16_t reqLen; - rfalNfcvGenericRes res; - uint16_t msgIt; - - /* Calculate required buffer length */ - reqLen = - (uint16_t)((uid != NULL) ? (RFAL_NFCV_WR_MUL_REQ_HEADER_LEN + RFAL_NFCV_UID_LEN + wrDataLen) : (RFAL_NFCV_WR_MUL_REQ_HEADER_LEN + wrDataLen)); - - if((reqLen > txBufLen) || (blockLen > (uint8_t)RFAL_NFCV_MAX_BLOCK_LEN) || - ((((uint16_t)numOfBlocks) * (uint16_t)blockLen) != wrDataLen) || (numOfBlocks == 0U) || - (wrData == NULL)) { - return ERR_PARAM; - } - - msgIt = 0; - - /* Compute Request Command */ - txBuf[msgIt++] = (uint8_t)(flags & (~((uint32_t)RFAL_NFCV_REQ_FLAG_ADDRESS))); - txBuf[msgIt++] = RFAL_NFCV_CMD_WRITE_MULTIPLE_BLOCKS; - - /* Check if Request is to be sent in Addressed mode. Select mode flag shall be set by user */ - if(uid != NULL) { - txBuf[RFAL_NFCV_FLAG_POS] |= (uint8_t)RFAL_NFCV_REQ_FLAG_ADDRESS; - ST_MEMCPY(&txBuf[msgIt], uid, RFAL_NFCV_UID_LEN); - msgIt += (uint8_t)RFAL_NFCV_UID_LEN; - } - - txBuf[msgIt++] = firstBlockNum; - txBuf[msgIt++] = (numOfBlocks - 1U); - - if(wrDataLen > 0U) /* MISRA 21.18 */ - { - ST_MEMCPY(&txBuf[msgIt], wrData, wrDataLen); - msgIt += wrDataLen; - } - - /* Transceive Command */ - ret = rfalTransceiveBlockingTxRx( - txBuf, - msgIt, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCV_FDT_MAX); - - if(ret != ERR_NONE) { - return ret; - } - - /* Check if the response minimum length has been received */ - if(rcvLen < (uint8_t)RFAL_NFCV_FLAG_LEN) { - return ERR_PROTO; - } - - /* Check if an error has been signalled */ - if((res.RES_FLAG & (uint8_t)RFAL_NFCV_RES_FLAG_ERROR) != 0U) { - return rfalNfcvParseError(*res.data); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerExtendedReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[RFAL_NFCV_BLOCKNUM_EXTENDED_LEN]; - uint8_t dataLen; - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t) - blockNum; /* TS T5T 1.0 BNo is considered as a multi-byte field. TS T5T 1.0 5.1.1.13 multi-byte field follows [DIGITAL]. [DIGITAL] 9.3.1 A multiple byte field is transmitted LSB first. */ - data[dataLen++] = (uint8_t)((blockNum >> 8U) & 0xFFU); - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_EXTENDED_READ_SINGLE_BLOCK, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerExtendedWriteSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - const uint8_t* wrData, - uint8_t blockLen) { - uint8_t data[(RFAL_NFCV_BLOCKNUM_EXTENDED_LEN + RFAL_NFCV_MAX_BLOCK_LEN)]; - uint8_t dataLen; - uint16_t rcvLen; - rfalNfcvGenericRes res; - - /* Check for valid parameters */ - if((blockLen == 0U) || (blockLen > (uint8_t)RFAL_NFCV_MAX_BLOCK_LEN)) { - return ERR_PARAM; - } - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t) - blockNum; /* TS T5T 1.0 BNo is considered as a multi-byte field. TS T5T 1.0 5.1.1.13 multi-byte field follows [DIGITAL]. [DIGITAL] 9.3.1 A multiple byte field is transmitted LSB first. */ - data[dataLen++] = (uint8_t)((blockNum >> 8U) & 0xFFU); - ST_MEMCPY(&data[dataLen], wrData, blockLen); /* Append Block data to write */ - dataLen += blockLen; - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_EXTENDED_WRITE_SINGLE_BLOCK, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - data, - dataLen, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); -} - -/*******************************************************************************/ -ReturnCode - rfalNfcvPollerExtendedLockSingleBlock(uint8_t flags, const uint8_t* uid, uint16_t blockNum) { - uint8_t data[RFAL_NFCV_BLOCKNUM_EXTENDED_LEN]; - uint8_t dataLen; - uint16_t rcvLen; - rfalNfcvGenericRes res; - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t) - blockNum; /* TS T5T 1.0 BNo is considered as a multi-byte field. TS T5T 1.0 5.1.1.13 multi-byte field follows [DIGITAL]. [DIGITAL] 9.3.1 A multiple byte field is transmitted LSB first. */ - data[dataLen++] = (uint8_t)((blockNum >> 8U) & 0xFFU); - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_EXTENDED_LOCK_SINGLE_BLOCK, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - data, - dataLen, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerExtendedReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint16_t firstBlockNum, - uint16_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[(RFAL_NFCV_BLOCKNUM_EXTENDED_LEN + RFAL_NFCV_BLOCKNUM_EXTENDED_LEN)]; - uint8_t dataLen; - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t)((firstBlockNum >> 0U) & 0xFFU); - data[dataLen++] = (uint8_t)((firstBlockNum >> 8U) & 0xFFU); - data[dataLen++] = (uint8_t)((numOfBlocks >> 0U) & 0xFFU); - data[dataLen++] = (uint8_t)((numOfBlocks >> 8U) & 0xFFU); - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_EXTENDED_READ_MULTIPLE_BLOCK, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerExtendedWriteMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint16_t firstBlockNum, - uint16_t numOfBlocks, - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t blockLen, - const uint8_t* wrData, - uint16_t wrDataLen) { - ReturnCode ret; - uint16_t rcvLen; - uint16_t reqLen; - rfalNfcvGenericRes res; - uint16_t msgIt; - uint16_t nBlocks; - - /* Calculate required buffer length */ - reqLen = - ((uid != NULL) ? (RFAL_NFCV_WR_MUL_REQ_HEADER_LEN + RFAL_NFCV_UID_LEN + wrDataLen) : - (RFAL_NFCV_WR_MUL_REQ_HEADER_LEN + wrDataLen)); - - if((reqLen > txBufLen) || (blockLen > (uint8_t)RFAL_NFCV_MAX_BLOCK_LEN) || - (((uint16_t)numOfBlocks * (uint16_t)blockLen) != wrDataLen) || (numOfBlocks == 0U)) { - return ERR_PARAM; - } - - msgIt = 0; - nBlocks = (numOfBlocks - 1U); - - /* Compute Request Command */ - txBuf[msgIt++] = (uint8_t)(flags & (~((uint32_t)RFAL_NFCV_REQ_FLAG_ADDRESS))); - txBuf[msgIt++] = RFAL_NFCV_CMD_EXTENDED_WRITE_MULTIPLE_BLOCK; - - /* Check if Request is to be sent in Addressed mode. Select mode flag shall be set by user */ - if(uid != NULL) { - txBuf[RFAL_NFCV_FLAG_POS] |= (uint8_t)RFAL_NFCV_REQ_FLAG_ADDRESS; - ST_MEMCPY(&txBuf[msgIt], uid, RFAL_NFCV_UID_LEN); - msgIt += (uint8_t)RFAL_NFCV_UID_LEN; - } - - txBuf[msgIt++] = (uint8_t)((firstBlockNum >> 0) & 0xFFU); - txBuf[msgIt++] = (uint8_t)((firstBlockNum >> 8) & 0xFFU); - txBuf[msgIt++] = (uint8_t)((nBlocks >> 0) & 0xFFU); - txBuf[msgIt++] = (uint8_t)((nBlocks >> 8) & 0xFFU); - - if(wrDataLen > 0U) /* MISRA 21.18 */ - { - ST_MEMCPY(&txBuf[msgIt], wrData, wrDataLen); - msgIt += wrDataLen; - } - - /* Transceive Command */ - ret = rfalTransceiveBlockingTxRx( - txBuf, - msgIt, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCV_FDT_MAX); - - if(ret != ERR_NONE) { - return ret; - } - - /* Check if the response minimum length has been received */ - if(rcvLen < (uint8_t)RFAL_NFCV_FLAG_LEN) { - return ERR_PROTO; - } - - /* Check if an error has been signalled */ - if((res.RES_FLAG & (uint8_t)RFAL_NFCV_RES_FLAG_ERROR) != 0U) { - return rfalNfcvParseError(*res.data); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerGetSystemInformation( - uint8_t flags, - const uint8_t* uid, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_GET_SYS_INFO, - flags, - RFAL_NFCV_PARAM_SKIP, - uid, - NULL, - 0U, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerExtendedGetSystemInformation( - uint8_t flags, - const uint8_t* uid, - uint8_t requestField, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_EXTENDED_GET_SYS_INFO, - flags, - requestField, - uid, - NULL, - 0U, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalNfcvPollerTransceiveReq( - uint8_t cmd, - uint8_t flags, - uint8_t param, - const uint8_t* uid, - const uint8_t* data, - uint16_t dataLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - ReturnCode ret; - rfalNfcvGenericReq req; - uint8_t msgIt; - rfalBitRate rxBR; - bool fastMode; - - msgIt = 0; - fastMode = false; - - /* Check for valid parameters */ - if((rxBuf == NULL) || (rcvLen == NULL) || ((dataLen > 0U) && (data == NULL)) || - (dataLen > ((uid != NULL) ? RFAL_NFCV_MAX_GEN_DATA_LEN : - (RFAL_NFCV_MAX_GEN_DATA_LEN - RFAL_NFCV_UID_LEN)))) { - return ERR_PARAM; - } - - /* Check if the command is an ST's Fast command */ - if((cmd == (uint8_t)RFAL_NFCV_CMD_FAST_READ_SINGLE_BLOCK) || - (cmd == (uint8_t)RFAL_NFCV_CMD_FAST_EXTENDED_READ_SINGLE_BLOCK) || - (cmd == (uint8_t)RFAL_NFCV_CMD_FAST_READ_MULTIPLE_BLOCKS) || - (cmd == (uint8_t)RFAL_NFCV_CMD_FAST_EXTENDED_READ_MULTIPLE_BLOCKS) || - (cmd == (uint8_t)RFAL_NFCV_CMD_FAST_WRITE_MESSAGE) || - (cmd == (uint8_t)RFAL_NFCV_CMD_FAST_READ_MESSAGE_LENGTH) || - (cmd == (uint8_t)RFAL_NFCV_CMD_FAST_READ_MESSAGE) || - (cmd == (uint8_t)RFAL_NFCV_CMD_FAST_READ_DYN_CONFIGURATION) || - (cmd == (uint8_t)RFAL_NFCV_CMD_FAST_WRITE_DYN_CONFIGURATION)) { - /* Store current Rx bit rate and move to fast mode */ - rfalGetBitRate(NULL, &rxBR); - rfalSetBitRate(RFAL_BR_KEEP, RFAL_BR_52p97); - - fastMode = true; - } - - /* Compute Request Command */ - req.REQ_FLAG = (uint8_t)(flags & (~((uint32_t)RFAL_NFCV_REQ_FLAG_ADDRESS))); - req.CMD = cmd; - - /* Prepend parameter on ceratin proprietary requests: IC Manuf, Parameters */ - if(param != RFAL_NFCV_PARAM_SKIP) { - req.payload.data[msgIt++] = param; - } - - /* Check if Request is to be sent in Addressed mode. Select mode flag shall be set by user */ - if(uid != NULL) { - req.REQ_FLAG |= (uint8_t)RFAL_NFCV_REQ_FLAG_ADDRESS; - ST_MEMCPY(&req.payload.data[msgIt], uid, RFAL_NFCV_UID_LEN); - msgIt += RFAL_NFCV_UID_LEN; - } - - if(dataLen > 0U) { - ST_MEMCPY(&req.payload.data[msgIt], data, dataLen); - msgIt += (uint8_t)dataLen; - } - - /* Transceive Command */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&req, - (RFAL_NFCV_CMD_LEN + RFAL_NFCV_FLAG_LEN + (uint16_t)msgIt), - rxBuf, - rxBufLen, - rcvLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_NFCV_FDT_MAX); - - /* If the Option Flag is set in certain commands an EOF needs to be sent after 20ms to retrieve the VICC response ISO15693-3 2009 10.4.2 & 10.4.3 & 10.4.5 */ - if(((flags & (uint8_t)RFAL_NFCV_REQ_FLAG_OPTION) != 0U) && - ((cmd == (uint8_t)RFAL_NFCV_CMD_WRITE_SINGLE_BLOCK) || - (cmd == (uint8_t)RFAL_NFCV_CMD_WRITE_MULTIPLE_BLOCKS) || - (cmd == (uint8_t)RFAL_NFCV_CMD_LOCK_BLOCK) || - (cmd == (uint8_t)RFAL_NFCV_CMD_EXTENDED_WRITE_SINGLE_BLOCK) || - (cmd == (uint8_t)RFAL_NFCV_CMD_EXTENDED_LOCK_SINGLE_BLOCK) || - (cmd == (uint8_t)RFAL_NFCV_CMD_EXTENDED_WRITE_MULTIPLE_BLOCK))) { - ret = rfalISO15693TransceiveEOF(rxBuf, (uint8_t)rxBufLen, rcvLen); - } - - /* Restore Rx BitRate */ - if(fastMode) { - rfalSetBitRate(RFAL_BR_KEEP, rxBR); - } - - if(ret != ERR_NONE) { - return ret; - } - - /* Check if the response minimum length has been received */ - if((*rcvLen) < (uint8_t)RFAL_NFCV_FLAG_LEN) { - return ERR_PROTO; - } - - /* Check if an error has been signalled */ - if((rxBuf[RFAL_NFCV_FLAG_POS] & (uint8_t)RFAL_NFCV_RES_FLAG_ERROR) != 0U) { - return rfalNfcvParseError(rxBuf[RFAL_NFCV_DATASTART_POS]); - } - - return ERR_NONE; -} - -#endif /* RFAL_FEATURE_NFCV */ diff --git a/lib/ST25RFAL002/source/rfal_st25tb.c b/lib/ST25RFAL002/source/rfal_st25tb.c deleted file mode 100644 index 00f699104..000000000 --- a/lib/ST25RFAL002/source/rfal_st25tb.c +++ /dev/null @@ -1,563 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_st25tb.c - * - * \author Gustavo Patricio - * - * \brief Implementation of ST25TB interface - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_st25tb.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ -#ifndef RFAL_FEATURE_ST25TB -#define RFAL_FEATURE_ST25TB false /* ST25TB module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_ST25TB - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_ST25TB_CMD_LEN 1U /*!< ST25TB length of a command */ -#define RFAL_ST25TB_SLOTS 16U /*!< ST25TB number of slots */ -#define RFAL_ST25TB_SLOTNUM_MASK 0x0FU /*!< ST25TB Slot Number bit mask on SlotMarker */ -#define RFAL_ST25TB_SLOTNUM_SHIFT 4U /*!< ST25TB Slot Number shift on SlotMarker */ - -#define RFAL_ST25TB_INITIATE_CMD1 0x06U /*!< ST25TB Initiate command byte1 */ -#define RFAL_ST25TB_INITIATE_CMD2 0x00U /*!< ST25TB Initiate command byte2 */ -#define RFAL_ST25TB_PCALL_CMD1 0x06U /*!< ST25TB Pcall16 command byte1 */ -#define RFAL_ST25TB_PCALL_CMD2 0x04U /*!< ST25TB Pcall16 command byte2 */ -#define RFAL_ST25TB_SELECT_CMD 0x0EU /*!< ST25TB Select command */ -#define RFAL_ST25TB_GET_UID_CMD 0x0BU /*!< ST25TB Get UID command */ -#define RFAL_ST25TB_COMPLETION_CMD 0x0FU /*!< ST25TB Completion command */ -#define RFAL_ST25TB_RESET_INV_CMD 0x0CU /*!< ST25TB Reset to Inventory command */ -#define RFAL_ST25TB_READ_BLOCK_CMD 0x08U /*!< ST25TB Read Block command */ -#define RFAL_ST25TB_WRITE_BLOCK_CMD 0x09U /*!< ST25TB Write Block command */ - -#define RFAL_ST25TB_T0 2157U /*!< ST25TB t0 159 us ST25TB RF characteristics */ -#define RFAL_ST25TB_T1 2048U /*!< ST25TB t1 151 us ST25TB RF characteristics */ - -#define RFAL_ST25TB_FWT \ - (RFAL_ST25TB_T0 + RFAL_ST25TB_T1) /*!< ST25TB FWT = T0 + T1 */ -#define RFAL_ST25TB_TW rfalConvMsTo1fc(7U) /*!< ST25TB TW : Programming time for write max 7ms */ - -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! Initiate Request */ -typedef struct { - uint8_t cmd1; /*!< Initiate Request cmd1: 0x06 */ - uint8_t cmd2; /*!< Initiate Request cmd2: 0x00 */ -} rfalSt25tbInitiateReq; - -/*! Pcall16 Request */ -typedef struct { - uint8_t cmd1; /*!< Pcal16 Request cmd1: 0x06 */ - uint8_t cmd2; /*!< Pcal16 Request cmd2: 0x04 */ -} rfalSt25tbPcallReq; - -/*! Select Request */ -typedef struct { - uint8_t cmd; /*!< Select Request cmd: 0x0E */ - uint8_t chipId; /*!< Chip ID */ -} rfalSt25tbSelectReq; - -/*! Read Block Request */ -typedef struct { - uint8_t cmd; /*!< Select Request cmd: 0x08 */ - uint8_t address; /*!< Block address */ -} rfalSt25tbReadBlockReq; - -/*! Write Block Request */ -typedef struct { - uint8_t cmd; /*!< Select Request cmd: 0x09 */ - uint8_t address; /*!< Block address */ - rfalSt25tbBlock data; /*!< Block Data */ -} rfalSt25tbWriteBlockReq; - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -/*! - ***************************************************************************** - * \brief ST25TB Poller Do Collision Resolution - * - * This method performs ST25TB Collision resolution loop for each slot - * - * \param[in] devLimit : device limit value, and size st25tbDevList - * \param[out] st25tbDevList : ST35TB listener device info - * \param[out] devCnt : Devices found counter - * - * \return colPending : true if a collision was detected - ***************************************************************************** - */ -static bool rfalSt25tbPollerDoCollisionResolution( - uint8_t devLimit, - rfalSt25tbListenDevice* st25tbDevList, - uint8_t* devCnt); - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -static bool rfalSt25tbPollerDoCollisionResolution( - uint8_t devLimit, - rfalSt25tbListenDevice* st25tbDevList, - uint8_t* devCnt) { - uint8_t i; - uint8_t chipId; - ReturnCode ret; - bool col; - - col = false; - - for(i = 0; i < RFAL_ST25TB_SLOTS; i++) { - platformDelay(1); /* Wait t2: Answer to new request delay */ - - if(i == 0U) { - /* Step 2: Send Pcall16 */ - ret = rfalSt25tbPollerPcall(&chipId); - } else { - /* Step 3-17: Send Pcall16 */ - ret = rfalSt25tbPollerSlotMarker(i, &chipId); - } - - if(ret == ERR_NONE) { - /* Found another device */ - st25tbDevList[*devCnt].chipID = chipId; - st25tbDevList[*devCnt].isDeselected = false; - - /* Select Device, retrieve its UID */ - ret = rfalSt25tbPollerSelect(chipId); - - /* By Selecting this device, the previous gets Deselected */ - if((*devCnt) > 0U) { - st25tbDevList[(*devCnt) - 1U].isDeselected = true; - } - - if(ERR_NONE == ret) { - rfalSt25tbPollerGetUID(&st25tbDevList[*devCnt].UID); - } - - if(ERR_NONE == ret) { - (*devCnt)++; - } - } else if((ret == ERR_CRC) || (ret == ERR_FRAMING)) { - col = true; - } else { - /* MISRA 15.7 - Empty else */ - } - - if(*devCnt >= devLimit) { - break; - } - } - return col; -} - -/* -****************************************************************************** -* LOCAL VARIABLES -****************************************************************************** -*/ - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerInitialize(void) { - return rfalNfcbPollerInitialize(); -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerCheckPresence(uint8_t* chipId) { - ReturnCode ret; - uint8_t chipIdRes; - - chipIdRes = 0x00; - - /* Send Initiate Request */ - ret = rfalSt25tbPollerInitiate(&chipIdRes); - - /* Check if a transmission error was detected */ - if((ret == ERR_CRC) || (ret == ERR_FRAMING)) { - return ERR_NONE; - } - - /* Copy chip ID if requested */ - if(chipId != NULL) { - *chipId = chipIdRes; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerInitiate(uint8_t* chipId) { - ReturnCode ret; - uint16_t rxLen; - rfalSt25tbInitiateReq initiateReq; - uint8_t rxBuf - [RFAL_ST25TB_CHIP_ID_LEN + - RFAL_ST25TB_CRC_LEN]; /* In case we receive less data that CRC, RF layer will not remove the CRC from buffer */ - - /* Compute Initiate Request */ - initiateReq.cmd1 = RFAL_ST25TB_INITIATE_CMD1; - initiateReq.cmd2 = RFAL_ST25TB_INITIATE_CMD2; - - /* Send Initiate Request */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&initiateReq, - sizeof(rfalSt25tbInitiateReq), - (uint8_t*)rxBuf, - sizeof(rxBuf), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ST25TB_FWT); - - /* Check for valid Select Response */ - if((ret == ERR_NONE) && (rxLen != RFAL_ST25TB_CHIP_ID_LEN)) { - return ERR_PROTO; - } - - /* Copy chip ID if requested */ - if(chipId != NULL) { - *chipId = *rxBuf; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerPcall(uint8_t* chipId) { - ReturnCode ret; - uint16_t rxLen; - rfalSt25tbPcallReq pcallReq; - - /* Compute Pcal16 Request */ - pcallReq.cmd1 = RFAL_ST25TB_PCALL_CMD1; - pcallReq.cmd2 = RFAL_ST25TB_PCALL_CMD2; - - /* Send Pcal16 Request */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&pcallReq, - sizeof(rfalSt25tbPcallReq), - (uint8_t*)chipId, - RFAL_ST25TB_CHIP_ID_LEN, - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ST25TB_FWT); - - /* Check for valid Select Response */ - if((ret == ERR_NONE) && (rxLen != RFAL_ST25TB_CHIP_ID_LEN)) { - return ERR_PROTO; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerSlotMarker(uint8_t slotNum, uint8_t* chipIdRes) { - ReturnCode ret; - uint16_t rxLen; - uint8_t slotMarker; - - if((slotNum == 0U) || (slotNum > 15U)) { - return ERR_PARAM; - } - - /* Compute SlotMarker */ - slotMarker = - (((slotNum & RFAL_ST25TB_SLOTNUM_MASK) << RFAL_ST25TB_SLOTNUM_SHIFT) | - RFAL_ST25TB_PCALL_CMD1); - - /* Send SlotMarker */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&slotMarker, - RFAL_ST25TB_CMD_LEN, - (uint8_t*)chipIdRes, - RFAL_ST25TB_CHIP_ID_LEN, - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ST25TB_FWT); - - /* Check for valid ChipID Response */ - if((ret == ERR_NONE) && (rxLen != RFAL_ST25TB_CHIP_ID_LEN)) { - return ERR_PROTO; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerSelect(uint8_t chipId) { - ReturnCode ret; - uint16_t rxLen; - rfalSt25tbSelectReq selectReq; - uint8_t chipIdRes; - - /* Compute Select Request */ - selectReq.cmd = RFAL_ST25TB_SELECT_CMD; - selectReq.chipId = chipId; - - /* Send Select Request */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&selectReq, - sizeof(rfalSt25tbSelectReq), - (uint8_t*)&chipIdRes, - RFAL_ST25TB_CHIP_ID_LEN, - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ST25TB_FWT); - - /* Check for valid Select Response */ - if((ret == ERR_NONE) && ((rxLen != RFAL_ST25TB_CHIP_ID_LEN) || (chipIdRes != chipId))) { - return ERR_PROTO; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerGetUID(rfalSt25tbUID* UID) { - ReturnCode ret; - uint16_t rxLen; - uint8_t getUidReq; - - /* Compute Get UID Request */ - getUidReq = RFAL_ST25TB_GET_UID_CMD; - - /* Send Select Request */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&getUidReq, - RFAL_ST25TB_CMD_LEN, - (uint8_t*)UID, - sizeof(rfalSt25tbUID), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ST25TB_FWT); - - /* Check for valid UID Response */ - if((ret == ERR_NONE) && (rxLen != RFAL_ST25TB_UID_LEN)) { - return ERR_PROTO; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerCollisionResolution( - uint8_t devLimit, - rfalSt25tbListenDevice* st25tbDevList, - uint8_t* devCnt) { - uint8_t chipId; - ReturnCode ret; - bool detected; /* collision or device was detected */ - - if((st25tbDevList == NULL) || (devCnt == NULL) || (devLimit == 0U)) { - return ERR_PARAM; - } - - *devCnt = 0; - - /* Step 1: Send Initiate */ - ret = rfalSt25tbPollerInitiate(&chipId); - if(ret == ERR_NONE) { - /* If only 1 answer is detected */ - st25tbDevList[*devCnt].chipID = chipId; - st25tbDevList[*devCnt].isDeselected = false; - - /* Retrieve its UID and keep it Selected*/ - ret = rfalSt25tbPollerSelect(chipId); - - if(ERR_NONE == ret) { - ret = rfalSt25tbPollerGetUID(&st25tbDevList[*devCnt].UID); - } - - if(ERR_NONE == ret) { - (*devCnt)++; - } - } - /* Always proceed to Pcall16 anticollision as phase differences of tags can lead to no tag recognized, even if there is one */ - if(*devCnt < devLimit) { - /* Multiple device responses */ - do { - detected = rfalSt25tbPollerDoCollisionResolution(devLimit, st25tbDevList, devCnt); - } while((detected == true) && (*devCnt < devLimit)); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerReadBlock(uint8_t blockAddress, rfalSt25tbBlock* blockData) { - ReturnCode ret; - uint16_t rxLen; - rfalSt25tbReadBlockReq readBlockReq; - - /* Compute Read Block Request */ - readBlockReq.cmd = RFAL_ST25TB_READ_BLOCK_CMD; - readBlockReq.address = blockAddress; - - /* Send Read Block Request */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&readBlockReq, - sizeof(rfalSt25tbReadBlockReq), - (uint8_t*)blockData, - sizeof(rfalSt25tbBlock), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ST25TB_FWT); - - /* Check for valid UID Response */ - if((ret == ERR_NONE) && (rxLen != RFAL_ST25TB_BLOCK_LEN)) { - return ERR_PROTO; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerWriteBlock(uint8_t blockAddress, const rfalSt25tbBlock* blockData) { - ReturnCode ret; - uint16_t rxLen; - rfalSt25tbWriteBlockReq writeBlockReq; - rfalSt25tbBlock tmpBlockData; - - /* Compute Write Block Request */ - writeBlockReq.cmd = RFAL_ST25TB_WRITE_BLOCK_CMD; - writeBlockReq.address = blockAddress; - ST_MEMCPY(&writeBlockReq.data, blockData, RFAL_ST25TB_BLOCK_LEN); - - /* Send Write Block Request */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&writeBlockReq, - sizeof(rfalSt25tbWriteBlockReq), - tmpBlockData, - RFAL_ST25TB_BLOCK_LEN, - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - (RFAL_ST25TB_FWT + RFAL_ST25TB_TW)); - - /* Check if there was any error besides timeout */ - if(ret != ERR_TIMEOUT) { - /* Check if an unexpected answer was received */ - if(ret == ERR_NONE) { - return ERR_PROTO; - } - - /* Check whether a transmission error occurred */ - if((ret != ERR_CRC) && (ret != ERR_FRAMING) && (ret != ERR_NOMEM) && - (ret != ERR_RF_COLLISION)) { - return ret; - } - - /* If a transmission error occurred (maybe noise while committing data) wait maximum programming time and verify data afterwards */ - rfalSetGT((RFAL_ST25TB_FWT + RFAL_ST25TB_TW)); - rfalFieldOnAndStartGT(); - } - - ret = rfalSt25tbPollerReadBlock(blockAddress, &tmpBlockData); - if(ret == ERR_NONE) { - if(ST_BYTECMP(&tmpBlockData, blockData, RFAL_ST25TB_BLOCK_LEN) == 0) { - return ERR_NONE; - } - return ERR_PROTO; - } - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerCompletion(void) { - uint8_t completionReq; - - /* Compute Completion Request */ - completionReq = RFAL_ST25TB_COMPLETION_CMD; - - /* Send Completion Request, no response is expected */ - return rfalTransceiveBlockingTxRx( - (uint8_t*)&completionReq, - RFAL_ST25TB_CMD_LEN, - NULL, - 0, - NULL, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ST25TB_FWT); -} - -/*******************************************************************************/ -ReturnCode rfalSt25tbPollerResetToInventory(void) { - uint8_t resetInvReq; - - /* Compute Completion Request */ - resetInvReq = RFAL_ST25TB_RESET_INV_CMD; - - /* Send Completion Request, no response is expected */ - return rfalTransceiveBlockingTxRx( - (uint8_t*)&resetInvReq, - RFAL_ST25TB_CMD_LEN, - NULL, - 0, - NULL, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ST25TB_FWT); -} - -#endif /* RFAL_FEATURE_ST25TB */ diff --git a/lib/ST25RFAL002/source/rfal_st25xv.c b/lib/ST25RFAL002/source/rfal_st25xv.c deleted file mode 100644 index 56c9ccb6f..000000000 --- a/lib/ST25RFAL002/source/rfal_st25xv.c +++ /dev/null @@ -1,818 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_st25xv.c - * - * \author Gustavo Patricio - * - * \brief NFC-V ST25 NFC-V Tag specific features - * - * This module provides support for ST's specific features available on - * NFC-V (ISO15693) tag families: ST25D, ST25TV, M24LR - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_st25xv.h" -#include "rfal_nfcv.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_ST25xV -#define RFAL_FEATURE_ST25xV false /* ST25xV module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_ST25xV - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_ST25xV_READ_CONFIG_LEN \ - 2U /*!< READ CONFIGURATION length */ -#define RFAL_ST25xV_READ_MSG_LEN_LEN \ - 2U /*!< READ MESSAGE LENGTH length */ -#define RFAL_ST25xV_CONF_POINTER_LEN \ - 1U /*!< READ/WRITE CONFIGURATION Pointer length */ -#define RFAL_ST25xV_CONF_REGISTER_LEN \ - 1U /*!< READ/WRITE CONFIGURATION Register length */ -#define RFAL_ST25xV_PWDNUM_LEN \ - 1U /*!< Password Number length */ -#define RFAL_ST25xV_PWD_LEN \ - 8U /*!< Password length */ -#define RFAL_ST25xV_MBPOINTER_LEN \ - 1U /*!< Read Message MBPointer length */ -#define RFAL_ST25xV_NUMBYTES_LEN \ - 1U /*!< Read Message Number of Bytes length */ - -#define RFAL_ST25TV02K_TBOOT_RF \ - 1U /*!< RF Boot time (Minimum time from carrier generation to first data) */ -#define RFAL_ST25TV02K_TRF_OFF \ - 2U /*!< RF OFF time */ - -#define RFAL_ST25xV_FDT_POLL_MAX \ - rfalConvMsTo1fc(20) /*!< Maximum Wait time FDTV,EOF 20 ms Digital 2.1 B.5 */ -#define RFAL_NFCV_FLAG_POS \ - 0U /*!< Flag byte position */ -#define RFAL_NFCV_FLAG_LEN \ - 1U /*!< Flag byte length */ - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -static ReturnCode rfalST25xVPollerGenericReadConfiguration( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t* regValue); -static ReturnCode rfalST25xVPollerGenericWriteConfiguration( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t regValue); -static ReturnCode rfalST25xVPollerGenericReadMessageLength( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t* msgLen); -static ReturnCode rfalST25xVPollerGenericReadMessage( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t mbPointer, - uint8_t numBytes, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen); -static ReturnCode rfalST25xVPollerGenericWriteMessage( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t msgLen, - const uint8_t* msgData, - uint8_t* txBuf, - uint16_t txBufLen); -/* -****************************************************************************** -* LOCAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -static ReturnCode rfalST25xVPollerGenericReadConfiguration( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t* regValue) { - ReturnCode ret; - uint8_t p; - uint16_t rcvLen; - rfalNfcvGenericRes res; - - if(regValue == NULL) { - return ERR_PARAM; - } - - p = pointer; - - ret = rfalNfcvPollerTransceiveReq( - cmd, - flags, - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - &p, - sizeof(uint8_t), - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); - if(ret == ERR_NONE) { - if(rcvLen < RFAL_ST25xV_READ_CONFIG_LEN) { - ret = ERR_PROTO; - } else { - *regValue = res.data[0]; - } - } - return ret; -} - -/*******************************************************************************/ -static ReturnCode rfalST25xVPollerGenericWriteConfiguration( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t regValue) { - uint8_t data[RFAL_ST25xV_CONF_POINTER_LEN + RFAL_ST25xV_CONF_REGISTER_LEN]; - uint8_t dataLen; - uint16_t rcvLen; - rfalNfcvGenericRes res; - - dataLen = 0U; - - data[dataLen++] = pointer; - data[dataLen++] = regValue; - - return rfalNfcvPollerTransceiveReq( - cmd, - flags, - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - data, - dataLen, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); -} - -/*******************************************************************************/ -static ReturnCode rfalST25xVPollerGenericReadMessageLength( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t* msgLen) { - ReturnCode ret; - uint16_t rcvLen; - rfalNfcvGenericRes res; - - if(msgLen == NULL) { - return ERR_PARAM; - } - - ret = rfalNfcvPollerTransceiveReq( - cmd, - flags, - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - NULL, - 0, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); - if(ret == ERR_NONE) { - if(rcvLen < RFAL_ST25xV_READ_MSG_LEN_LEN) { - ret = ERR_PROTO; - } else { - *msgLen = res.data[0]; - } - } - return ret; -} - -/*******************************************************************************/ -static ReturnCode rfalST25xVPollerGenericReadMessage( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t mbPointer, - uint8_t numBytes, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[RFAL_ST25xV_MBPOINTER_LEN + RFAL_ST25xV_NUMBYTES_LEN]; - uint8_t dataLen; - - dataLen = 0; - - /* Compute Request Data */ - data[dataLen++] = mbPointer; - data[dataLen++] = numBytes; - - return rfalNfcvPollerTransceiveReq( - cmd, flags, RFAL_NFCV_ST_IC_MFG_CODE, uid, data, dataLen, rxBuf, rxBufLen, rcvLen); -} - -/*******************************************************************************/ -static ReturnCode rfalST25xVPollerGenericWriteMessage( - uint8_t cmd, - uint8_t flags, - const uint8_t* uid, - uint8_t msgLen, - const uint8_t* msgData, - uint8_t* txBuf, - uint16_t txBufLen) { - ReturnCode ret; - uint8_t reqFlag; - uint16_t msgIt; - rfalBitRate rxBR; - bool fastMode; - rfalNfcvGenericRes res; - uint16_t rcvLen; - - /* Calculate required Tx buf length: Mfg Code UID MSGLen MSGLen+1 */ - msgIt = - (uint16_t)(msgLen + sizeof(flags) + sizeof(cmd) + 1U + ((uid != NULL) ? RFAL_NFCV_UID_LEN : 0U) + 1U + 1U); - /* Note: MSGlength parameter of the command is the number of Data bytes minus - 1 (00 for 1 byte of data, FFh for 256 bytes of data) */ - - /* Check for valid parameters */ - if((txBuf == NULL) || (msgData == NULL) || (txBufLen < msgIt)) { - return ERR_PARAM; - } - - msgIt = 0; - fastMode = false; - - /* Check if the command is an ST's Fast command */ - if(cmd == (uint8_t)RFAL_NFCV_CMD_FAST_WRITE_MESSAGE) { - /* Store current Rx bit rate and move to fast mode */ - rfalGetBitRate(NULL, &rxBR); - rfalSetBitRate(RFAL_BR_KEEP, RFAL_BR_52p97); - - fastMode = true; - } - - /* Compute Request Command */ - reqFlag = - (uint8_t)(flags & (~((uint32_t)RFAL_NFCV_REQ_FLAG_ADDRESS) & ~((uint32_t)RFAL_NFCV_REQ_FLAG_SELECT))); - reqFlag |= - ((uid != NULL) ? (uint8_t)RFAL_NFCV_REQ_FLAG_ADDRESS : (uint8_t)RFAL_NFCV_REQ_FLAG_SELECT); - - txBuf[msgIt++] = reqFlag; - txBuf[msgIt++] = cmd; - txBuf[msgIt++] = RFAL_NFCV_ST_IC_MFG_CODE; - - if(uid != NULL) { - ST_MEMCPY(&txBuf[msgIt], uid, RFAL_NFCV_UID_LEN); - msgIt += RFAL_NFCV_UID_LEN; - } - txBuf[msgIt++] = msgLen; - ST_MEMCPY( - &txBuf[msgIt], - msgData, - (uint16_t)(msgLen + (uint16_t)1U)); /* Message Data contains (MSGLength + 1) bytes */ - msgIt += (uint16_t)(msgLen + (uint16_t)1U); - - /* Transceive Command */ - ret = rfalTransceiveBlockingTxRx( - txBuf, - msgIt, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_ST25xV_FDT_POLL_MAX); - - /* Restore Rx BitRate */ - if(fastMode) { - rfalSetBitRate(RFAL_BR_KEEP, rxBR); - } - - if(ret != ERR_NONE) { - return ret; - } - - /* Check if the response minimum length has been received */ - if(rcvLen < (uint8_t)RFAL_NFCV_FLAG_LEN) { - return ERR_PROTO; - } - - /* Check if an error has been signalled */ - if((res.RES_FLAG & (uint8_t)RFAL_NFCV_RES_FLAG_ERROR) != 0U) { - return ERR_PROTO; - } - - return ERR_NONE; -} - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerM24LRReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[RFAL_NFCV_BLOCKNUM_M24LR_LEN]; - uint8_t dataLen; - - dataLen = 0; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t)blockNum; /* Set M24LR Block Number (16 bits) LSB */ - data[dataLen++] = (uint8_t)(blockNum >> 8U); /* Set M24LR Block Number (16 bits) MSB */ - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_READ_SINGLE_BLOCK, - (flags | (uint8_t)RFAL_NFCV_REQ_FLAG_PROTOCOL_EXT), - RFAL_NFCV_PARAM_SKIP, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerM24LRWriteSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - const uint8_t* wrData, - uint8_t blockLen) { - uint8_t data[(RFAL_NFCV_BLOCKNUM_M24LR_LEN + RFAL_NFCV_MAX_BLOCK_LEN)]; - uint8_t dataLen; - uint16_t rcvLen; - rfalNfcvGenericRes res; - - /* Check for valid parameters */ - if((blockLen == 0U) || (blockLen > (uint8_t)RFAL_NFCV_MAX_BLOCK_LEN) || (wrData == NULL)) { - return ERR_PARAM; - } - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t)blockNum; /* Set M24LR Block Number (16 bits) LSB */ - data[dataLen++] = (uint8_t)(blockNum >> 8U); /* Set M24LR Block Number (16 bits) MSB */ - ST_MEMCPY(&data[dataLen], wrData, blockLen); /* Append Block data to write */ - dataLen += blockLen; - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_WRITE_SINGLE_BLOCK, - (flags | (uint8_t)RFAL_NFCV_REQ_FLAG_PROTOCOL_EXT), - RFAL_NFCV_PARAM_SKIP, - uid, - data, - dataLen, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerM24LRReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint16_t firstBlockNum, - uint8_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[(RFAL_NFCV_BLOCKNUM_M24LR_LEN + RFAL_NFCV_BLOCKNUM_M24LR_LEN)]; - uint8_t dataLen; - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t)firstBlockNum; /* Set M24LR Block Number (16 bits) LSB */ - data[dataLen++] = (uint8_t)(firstBlockNum >> 8U); /* Set M24LR Block Number (16 bits) MSB */ - data[dataLen++] = numOfBlocks; /* Set number of blocks to read */ - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_READ_MULTIPLE_BLOCKS, - (flags | (uint8_t)RFAL_NFCV_REQ_FLAG_PROTOCOL_EXT), - RFAL_NFCV_PARAM_SKIP, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerFastReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint8_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t bn; - - bn = blockNum; - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_FAST_READ_SINGLE_BLOCK, - flags, - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - &bn, - sizeof(uint8_t), - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerM24LRFastReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[RFAL_NFCV_BLOCKNUM_M24LR_LEN]; - uint8_t dataLen; - - dataLen = 0; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t)blockNum; /* Set M24LR Block Number (16 bits) LSB */ - data[dataLen++] = (uint8_t)(blockNum >> 8U); /* Set M24LR Block Number (16 bits) MSB */ - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_FAST_READ_SINGLE_BLOCK, - (flags | (uint8_t)RFAL_NFCV_REQ_FLAG_PROTOCOL_EXT), - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerM24LRFastReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint16_t firstBlockNum, - uint8_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[(RFAL_NFCV_BLOCKNUM_M24LR_LEN + RFAL_NFCV_BLOCKNUM_M24LR_LEN)]; - uint8_t dataLen; - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t)firstBlockNum; /* Set M24LR Block Number (16 bits) LSB */ - data[dataLen++] = (uint8_t)(firstBlockNum >> 8U); /* Set M24LR Block Number (16 bits) MSB */ - data[dataLen++] = numOfBlocks; /* Set number of blocks to read */ - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_FAST_READ_MULTIPLE_BLOCKS, - (flags | (uint8_t)RFAL_NFCV_REQ_FLAG_PROTOCOL_EXT), - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerFastReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint8_t firstBlockNum, - uint8_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[(RFAL_NFCV_BLOCKNUM_LEN + RFAL_NFCV_BLOCKNUM_LEN)]; - uint8_t dataLen; - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = firstBlockNum; /* Set first Block Number */ - data[dataLen++] = numOfBlocks; /* Set number of blocks to read */ - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_FAST_READ_MULTIPLE_BLOCKS, - flags, - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerFastExtendedReadSingleBlock( - uint8_t flags, - const uint8_t* uid, - uint16_t blockNum, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[RFAL_NFCV_BLOCKNUM_EXTENDED_LEN]; - uint8_t dataLen; - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t) - blockNum; /* TS T5T 1.0 BNo is considered as a multi-byte field. TS T5T 1.0 5.1.1.13 multi-byte field follows [DIGITAL]. [DIGITAL] 9.3.1 A multiple byte field is transmitted LSB first. */ - data[dataLen++] = (uint8_t)((blockNum >> 8U) & 0xFFU); - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_FAST_EXTENDED_READ_SINGLE_BLOCK, - flags, - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerFastExtReadMultipleBlocks( - uint8_t flags, - const uint8_t* uid, - uint16_t firstBlockNum, - uint16_t numOfBlocks, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - uint8_t data[(RFAL_NFCV_BLOCKNUM_EXTENDED_LEN + RFAL_NFCV_BLOCKNUM_EXTENDED_LEN)]; - uint8_t dataLen; - - dataLen = 0U; - - /* Compute Request Data */ - data[dataLen++] = (uint8_t)((firstBlockNum >> 0U) & 0xFFU); - data[dataLen++] = (uint8_t)((firstBlockNum >> 8U) & 0xFFU); - data[dataLen++] = (uint8_t)((numOfBlocks >> 0U) & 0xFFU); - data[dataLen++] = (uint8_t)((numOfBlocks >> 8U) & 0xFFU); - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_FAST_EXTENDED_READ_MULTIPLE_BLOCKS, - flags, - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - data, - dataLen, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerReadConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t* regValue) { - return rfalST25xVPollerGenericReadConfiguration( - RFAL_NFCV_CMD_READ_CONFIGURATION, flags, uid, pointer, regValue); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerWriteConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t regValue) { - return rfalST25xVPollerGenericWriteConfiguration( - RFAL_NFCV_CMD_WRITE_CONFIGURATION, flags, uid, pointer, regValue); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerReadDynamicConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t* regValue) { - return rfalST25xVPollerGenericReadConfiguration( - RFAL_NFCV_CMD_READ_DYN_CONFIGURATION, flags, uid, pointer, regValue); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerWriteDynamicConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t regValue) { - return rfalST25xVPollerGenericWriteConfiguration( - RFAL_NFCV_CMD_WRITE_DYN_CONFIGURATION, flags, uid, pointer, regValue); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerFastReadDynamicConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t* regValue) { - return rfalST25xVPollerGenericReadConfiguration( - RFAL_NFCV_CMD_FAST_READ_DYN_CONFIGURATION, flags, uid, pointer, regValue); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerFastWriteDynamicConfiguration( - uint8_t flags, - const uint8_t* uid, - uint8_t pointer, - uint8_t regValue) { - return rfalST25xVPollerGenericWriteConfiguration( - RFAL_NFCV_CMD_FAST_WRITE_DYN_CONFIGURATION, flags, uid, pointer, regValue); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerPresentPassword( - uint8_t flags, - const uint8_t* uid, - uint8_t pwdNum, - const uint8_t* pwd, - uint8_t pwdLen) { - uint8_t data[RFAL_ST25xV_PWDNUM_LEN + RFAL_ST25xV_PWD_LEN]; - uint8_t dataLen; - uint16_t rcvLen; - rfalNfcvGenericRes res; - - if((pwdLen > RFAL_ST25xV_PWD_LEN) || (pwd == NULL)) { - return ERR_PARAM; - } - - dataLen = 0U; - data[dataLen++] = pwdNum; - if(pwdLen > 0U) { - ST_MEMCPY(&data[dataLen], pwd, pwdLen); - } - dataLen += pwdLen; - - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_PRESENT_PASSWORD, - flags, - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - data, - dataLen, - (uint8_t*)&res, - sizeof(rfalNfcvGenericRes), - &rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerGetRandomNumber( - uint8_t flags, - const uint8_t* uid, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - rfalFieldOff(); - platformDelay(RFAL_ST25TV02K_TRF_OFF); - rfalNfcvPollerInitialize(); - rfalFieldOnAndStartGT(); - platformDelay(RFAL_ST25TV02K_TBOOT_RF); - return rfalNfcvPollerTransceiveReq( - RFAL_NFCV_CMD_GET_RANDOM_NUMBER, - flags, - RFAL_NFCV_ST_IC_MFG_CODE, - uid, - NULL, - 0U, - rxBuf, - rxBufLen, - rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerWriteMessage( - uint8_t flags, - const uint8_t* uid, - uint8_t msgLen, - const uint8_t* msgData, - uint8_t* txBuf, - uint16_t txBufLen) { - return rfalST25xVPollerGenericWriteMessage( - RFAL_NFCV_CMD_WRITE_MESSAGE, flags, uid, msgLen, msgData, txBuf, txBufLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerFastWriteMessage( - uint8_t flags, - const uint8_t* uid, - uint8_t msgLen, - const uint8_t* msgData, - uint8_t* txBuf, - uint16_t txBufLen) { - return rfalST25xVPollerGenericWriteMessage( - RFAL_NFCV_CMD_FAST_WRITE_MESSAGE, flags, uid, msgLen, msgData, txBuf, txBufLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerReadMessageLength(uint8_t flags, const uint8_t* uid, uint8_t* msgLen) { - return rfalST25xVPollerGenericReadMessageLength( - RFAL_NFCV_CMD_READ_MESSAGE_LENGTH, flags, uid, msgLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerFastReadMsgLength(uint8_t flags, const uint8_t* uid, uint8_t* msgLen) { - return rfalST25xVPollerGenericReadMessageLength( - RFAL_NFCV_CMD_FAST_READ_MESSAGE_LENGTH, flags, uid, msgLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerReadMessage( - uint8_t flags, - const uint8_t* uid, - uint8_t mbPointer, - uint8_t numBytes, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - return rfalST25xVPollerGenericReadMessage( - RFAL_NFCV_CMD_READ_MESSAGE, flags, uid, mbPointer, numBytes, rxBuf, rxBufLen, rcvLen); -} - -/*******************************************************************************/ -ReturnCode rfalST25xVPollerFastReadMessage( - uint8_t flags, - const uint8_t* uid, - uint8_t mbPointer, - uint8_t numBytes, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rcvLen) { - return rfalST25xVPollerGenericReadMessage( - RFAL_NFCV_CMD_FAST_READ_MESSAGE, flags, uid, mbPointer, numBytes, rxBuf, rxBufLen, rcvLen); -} - -#endif /* RFAL_FEATURE_ST25xV */ diff --git a/lib/ST25RFAL002/source/rfal_t1t.c b/lib/ST25RFAL002/source/rfal_t1t.c deleted file mode 100644 index be990efcd..000000000 --- a/lib/ST25RFAL002/source/rfal_t1t.c +++ /dev/null @@ -1,233 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_t1t.c - * - * \author Gustavo Patricio - * - * \brief Provides NFC-A T1T convenience methods and definitions - * - * This module provides an interface to perform as a NFC-A Reader/Writer - * to handle a Type 1 Tag T1T (Topaz) - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_t1t.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_T1T -#define RFAL_FEATURE_T1T false /* T1T module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_T1T - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ - -#define RFAL_T1T_DRD_READ \ - (1236U * 2U) /*!< DRD for Reads with n=9 => 1236/fc ~= 91 us T1T 1.2 4.4.2 */ -#define RFAL_T1T_DRD_WRITE \ - 36052U /*!< DRD for Write with n=281 => 36052/fc ~= 2659 us T1T 1.2 4.4.2 */ -#define RFAL_T1T_DRD_WRITE_E \ - 70996U /*!< DRD for Write/Erase with n=554 => 70996/fc ~= 5236 us T1T 1.2 4.4.2 */ - -#define RFAL_T1T_RID_RES_HR0_VAL \ - 0x10U /*!< HR0 indicating NDEF support Digital 2.0 (Candidate) 11.6.2.1 */ -#define RFAL_T1T_RID_RES_HR0_MASK \ - 0xF0U /*!< HR0 most significant nibble mask */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! NFC-A T1T (Topaz) RID_REQ Digital 1.1 10.6.1 & Table 49 */ -typedef struct { - uint8_t cmd; /*!< T1T cmd: RID */ - uint8_t add; /*!< ADD: undefined value */ - uint8_t data; /*!< DATA: undefined value */ - uint8_t uid[RFAL_T1T_UID_LEN]; /*!< UID-echo: undefined value */ -} rfalT1TRidReq; - -/*! NFC-A T1T (Topaz) RALL_REQ T1T 1.2 Table 4 */ -typedef struct { - uint8_t cmd; /*!< T1T cmd: RALL */ - uint8_t add1; /*!< ADD: 0x00 */ - uint8_t add0; /*!< ADD: 0x00 */ - uint8_t uid[RFAL_T1T_UID_LEN]; /*!< UID */ -} rfalT1TRallReq; - -/*! NFC-A T1T (Topaz) WRITE_REQ T1T 1.2 Table 4 */ -typedef struct { - uint8_t cmd; /*!< T1T cmd: RALL */ - uint8_t add; /*!< ADD */ - uint8_t data; /*!< DAT */ - uint8_t uid[RFAL_T1T_UID_LEN]; /*!< UID */ -} rfalT1TWriteReq; - -/*! NFC-A T1T (Topaz) WRITE_RES T1T 1.2 Table 4 */ -typedef struct { - uint8_t add; /*!< ADD */ - uint8_t data; /*!< DAT */ -} rfalT1TWriteRes; - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -ReturnCode rfalT1TPollerInitialize(void) { - ReturnCode ret; - - EXIT_ON_ERR(ret, rfalSetMode(RFAL_MODE_POLL_NFCA_T1T, RFAL_BR_106, RFAL_BR_106)); - rfalSetErrorHandling(RFAL_ERRORHANDLING_NFC); - - rfalSetGT( - RFAL_GT_NONE); /* T1T should only be initialized after NFC-A mode, therefore the GT has been fulfilled */ - rfalSetFDTListen( - RFAL_FDT_LISTEN_NFCA_POLLER); /* T1T uses NFC-A FDT Listen with n=9 Digital 1.1 10.7.2 */ - rfalSetFDTPoll(RFAL_FDT_POLL_NFCA_T1T_POLLER); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalT1TPollerRid(rfalT1TRidRes* ridRes) { - ReturnCode ret; - rfalT1TRidReq ridReq; - uint16_t rcvdLen; - - if(ridRes == NULL) { - return ERR_PARAM; - } - - /* Compute RID command and set Undefined Values to 0x00 Digital 1.1 10.6.1 */ - ST_MEMSET(&ridReq, 0x00, sizeof(rfalT1TRidReq)); - ridReq.cmd = (uint8_t)RFAL_T1T_CMD_RID; - - EXIT_ON_ERR( - ret, - rfalTransceiveBlockingTxRx( - (uint8_t*)&ridReq, - sizeof(rfalT1TRidReq), - (uint8_t*)ridRes, - sizeof(rfalT1TRidRes), - &rcvdLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_T1T_DRD_READ)); - - /* Check expected RID response length and the HR0 Digital 2.0 (Candidate) 11.6.2.1 */ - if((rcvdLen != sizeof(rfalT1TRidRes)) || - ((ridRes->hr0 & RFAL_T1T_RID_RES_HR0_MASK) != RFAL_T1T_RID_RES_HR0_VAL)) { - return ERR_PROTO; - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode - rfalT1TPollerRall(const uint8_t* uid, uint8_t* rxBuf, uint16_t rxBufLen, uint16_t* rxRcvdLen) { - rfalT1TRallReq rallReq; - - if((rxBuf == NULL) || (uid == NULL) || (rxRcvdLen == NULL)) { - return ERR_PARAM; - } - - /* Compute RALL command and set Add to 0x00 */ - ST_MEMSET(&rallReq, 0x00, sizeof(rfalT1TRallReq)); - rallReq.cmd = (uint8_t)RFAL_T1T_CMD_RALL; - ST_MEMCPY(rallReq.uid, uid, RFAL_T1T_UID_LEN); - - return rfalTransceiveBlockingTxRx( - (uint8_t*)&rallReq, - sizeof(rfalT1TRallReq), - (uint8_t*)rxBuf, - rxBufLen, - rxRcvdLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_T1T_DRD_READ); -} - -/*******************************************************************************/ -ReturnCode rfalT1TPollerWrite(const uint8_t* uid, uint8_t address, uint8_t data) { - rfalT1TWriteReq writeReq; - rfalT1TWriteRes writeRes; - uint16_t rxRcvdLen; - ReturnCode err; - - if(uid == NULL) { - return ERR_PARAM; - } - - writeReq.cmd = (uint8_t)RFAL_T1T_CMD_WRITE_E; - writeReq.add = address; - writeReq.data = data; - ST_MEMCPY(writeReq.uid, uid, RFAL_T1T_UID_LEN); - - err = rfalTransceiveBlockingTxRx( - (uint8_t*)&writeReq, - sizeof(rfalT1TWriteReq), - (uint8_t*)&writeRes, - sizeof(rfalT1TWriteRes), - &rxRcvdLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_T1T_DRD_WRITE_E); - - if(err == ERR_NONE) { - if((writeReq.add != writeRes.add) || (writeReq.data != writeRes.data) || - (rxRcvdLen != sizeof(rfalT1TWriteRes))) { - return ERR_PROTO; - } - } - return err; -} - -#endif /* RFAL_FEATURE_T1T */ diff --git a/lib/ST25RFAL002/source/rfal_t2t.c b/lib/ST25RFAL002/source/rfal_t2t.c deleted file mode 100644 index 2837898a7..000000000 --- a/lib/ST25RFAL002/source/rfal_t2t.c +++ /dev/null @@ -1,253 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_t2t.c - * - * \author - * - * \brief Provides NFC-A T2T convenience methods and definitions - * - * This module provides an interface to perform as a NFC-A Reader/Writer - * to handle a Type 2 Tag T2T - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_t2t.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_T2T -#define RFAL_FEATURE_T2T false /* T2T module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_T2T - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ -#define RFAL_FDT_POLL_READ_MAX \ - rfalConvMsTo1fc( \ - 5U) /*!< Maximum Wait time for Read command as defined in TS T2T 1.0 table 18 */ -#define RFAL_FDT_POLL_WRITE_MAX \ - rfalConvMsTo1fc( \ - 10U) /*!< Maximum Wait time for Write command as defined in TS T2T 1.0 table 18 */ -#define RFAL_FDT_POLL_SL_MAX \ - rfalConvMsTo1fc( \ - 1U) /*!< Maximum Wait time for Sector Select as defined in TS T2T 1.0 table 18 */ -#define RFAL_T2T_ACK_NACK_LEN \ - 1U /*!< Len of NACK in bytes (4 bits) */ -#define RFAL_T2T_ACK \ - 0x0AU /*!< ACK value */ -#define RFAL_T2T_ACK_MASK \ - 0x0FU /*!< ACK value */ - -#define RFAL_T2T_SECTOR_SELECT_P1_BYTE2 \ - 0xFFU /*!< Sector Select Packet 1 byte 2 */ -#define RFAL_T2T_SECTOR_SELECT_P2_RFU_LEN \ - 3U /*!< Sector Select RFU length */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! NFC-A T2T command set T2T 1.0 5.1 */ -typedef enum { - RFAL_T2T_CMD_READ = 0x30, /*!< T2T Read */ - RFAL_T2T_CMD_WRITE = 0xA2, /*!< T2T Write */ - RFAL_T2T_CMD_SECTOR_SELECT = 0xC2 /*!< T2T Sector Select */ -} rfalT2Tcmds; - -/*! NFC-A T2T READ T2T 1.0 5.2 and table 11 */ -typedef struct { - uint8_t code; /*!< Command code */ - uint8_t blNo; /*!< Block number */ -} rfalT2TReadReq; - -/*! NFC-A T2T WRITE T2T 1.0 5.3 and table 12 */ -typedef struct { - uint8_t code; /*!< Command code */ - uint8_t blNo; /*!< Block number */ - uint8_t data[RFAL_T2T_WRITE_DATA_LEN]; /*!< Data */ -} rfalT2TWriteReq; - -/*! NFC-A T2T SECTOR SELECT Packet 1 T2T 1.0 5.4 and table 13 */ -typedef struct { - uint8_t code; /*!< Command code */ - uint8_t byte2; /*!< Sector Select Packet 1 byte 2 */ -} rfalT2TSectorSelectP1Req; - -/*! NFC-A T2T SECTOR SELECT Packet 2 T2T 1.0 5.4 and table 13 */ -typedef struct { - uint8_t secNo; /*!< Block number */ - uint8_t rfu[RFAL_T2T_SECTOR_SELECT_P2_RFU_LEN]; /*!< Sector Select Packet RFU */ -} rfalT2TSectorSelectP2Req; - -/* - ****************************************************************************** - * GLOBAL FUNCTIONS - ****************************************************************************** - */ - -ReturnCode - rfalT2TPollerRead(uint8_t blockNum, uint8_t* rxBuf, uint16_t rxBufLen, uint16_t* rcvLen) { - ReturnCode ret; - rfalT2TReadReq req; - - if((rxBuf == NULL) || (rcvLen == NULL)) { - return ERR_PARAM; - } - - req.code = (uint8_t)RFAL_T2T_CMD_READ; - req.blNo = blockNum; - - /* Transceive Command */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&req, - sizeof(rfalT2TReadReq), - rxBuf, - rxBufLen, - rcvLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_FDT_POLL_READ_MAX); - - /* T2T 1.0 5.2.1.7 The Reader/Writer SHALL treat a NACK in response to a READ Command as a Protocol Error */ - if((ret == ERR_INCOMPLETE_BYTE) && (*rcvLen == RFAL_T2T_ACK_NACK_LEN) && - ((*rxBuf & RFAL_T2T_ACK_MASK) != RFAL_T2T_ACK)) { - return ERR_PROTO; - } - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalT2TPollerWrite(uint8_t blockNum, const uint8_t* wrData) { - ReturnCode ret; - rfalT2TWriteReq req; - uint8_t res; - uint16_t rxLen; - - req.code = (uint8_t)RFAL_T2T_CMD_WRITE; - req.blNo = blockNum; - ST_MEMCPY(req.data, wrData, RFAL_T2T_WRITE_DATA_LEN); - - /* Transceive WRITE Command */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&req, - sizeof(rfalT2TWriteReq), - &res, - sizeof(uint8_t), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_FDT_POLL_READ_MAX); - - /* Check for a valid ACK */ - if((ret == ERR_INCOMPLETE_BYTE) || (ret == ERR_NONE)) { - ret = ERR_PROTO; - - if((rxLen == RFAL_T2T_ACK_NACK_LEN) && ((res & RFAL_T2T_ACK_MASK) == RFAL_T2T_ACK)) { - ret = ERR_NONE; - } - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalT2TPollerSectorSelect(uint8_t sectorNum) { - rfalT2TSectorSelectP1Req p1Req; - rfalT2TSectorSelectP2Req p2Req; - ReturnCode ret; - uint8_t res; - uint16_t rxLen; - - /* Compute SECTOR SELECT Packet 1 */ - p1Req.code = (uint8_t)RFAL_T2T_CMD_SECTOR_SELECT; - p1Req.byte2 = RFAL_T2T_SECTOR_SELECT_P1_BYTE2; - - /* Transceive SECTOR SELECT Packet 1 */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&p1Req, - sizeof(rfalT2TSectorSelectP1Req), - &res, - sizeof(uint8_t), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_FDT_POLL_SL_MAX); - - /* Check and report any transmission error */ - if((ret != ERR_INCOMPLETE_BYTE) && (ret != ERR_NONE)) { - return ret; - } - - /* Ensure that an ACK was received */ - if((ret != ERR_INCOMPLETE_BYTE) || (rxLen != RFAL_T2T_ACK_NACK_LEN) || - ((res & RFAL_T2T_ACK_MASK) != RFAL_T2T_ACK)) { - return ERR_PROTO; - } - - /* Compute SECTOR SELECT Packet 2 */ - p2Req.secNo = sectorNum; - ST_MEMSET(&p2Req.rfu, 0x00, RFAL_T2T_SECTOR_SELECT_P2_RFU_LEN); - - /* Transceive SECTOR SELECT Packet 2 */ - ret = rfalTransceiveBlockingTxRx( - (uint8_t*)&p2Req, - sizeof(rfalT2TSectorSelectP2Req), - &res, - sizeof(uint8_t), - &rxLen, - RFAL_TXRX_FLAGS_DEFAULT, - RFAL_FDT_POLL_SL_MAX); - - /* T2T 1.0 5.4.1.14 The Reader/Writer SHALL treat any response received before the end of PATT2T,SL,MAX as a Protocol Error */ - if((ret == ERR_NONE) || (ret == ERR_INCOMPLETE_BYTE)) { - return ERR_PROTO; - } - - /* T2T 1.0 5.4.1.13 The Reader/Writer SHALL treat the transmission of the SECTOR SELECT Command Packet 2 as being successful when it receives no response until PATT2T,SL,MAX. */ - if(ret == ERR_TIMEOUT) { - return ERR_NONE; - } - - return ret; -} - -#endif /* RFAL_FEATURE_T2T */ diff --git a/lib/ST25RFAL002/source/rfal_t4t.c b/lib/ST25RFAL002/source/rfal_t4t.c deleted file mode 100644 index 4c29d79b0..000000000 --- a/lib/ST25RFAL002/source/rfal_t4t.c +++ /dev/null @@ -1,397 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_t4t.h - * - * \author Gustavo Patricio - * - * \brief Provides convenience methods and definitions for T4T (ISO7816-4) - * - * This module provides an interface to exchange T4T APDUs according to - * NFC Forum T4T and ISO7816-4 - * - * This implementation was based on the following specs: - * - ISO/IEC 7816-4 3rd Edition 2013-04-15 - * - NFC Forum T4T Technical Specification 1.0 2017-08-28 - * - */ - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_t4t.h" -#include "utils.h" - -/* - ****************************************************************************** - * ENABLE SWITCH - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_T4T -#define RFAL_FEATURE_T4T false /* T4T module configuration missing. Disabled by default */ -#endif - -#if RFAL_FEATURE_T4T - -/* - ****************************************************************************** - * GLOBAL DEFINES - ****************************************************************************** - */ -#define RFAL_T4T_OFFSET_DO 0x54U /*!< Tag value for offset BER-TLV data object */ -#define RFAL_T4T_LENGTH_DO 0x03U /*!< Len value for offset BER-TLV data object */ -#define RFAL_T4T_DATA_DO 0x53U /*!< Tag value for data BER-TLV data object */ - -#define RFAL_T4T_MAX_LC 255U /*!< Maximum Lc value for short Lc coding */ -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ - -/* - ****************************************************************************** - * LOCAL VARIABLES - ****************************************************************************** - */ - -/* - ****************************************************************************** - * GLOBAL FUNCTIONS - ****************************************************************************** - */ - -/*******************************************************************************/ -ReturnCode rfalT4TPollerComposeCAPDU(const rfalT4tCApduParam* apduParam) { - uint8_t hdrLen; - uint16_t msgIt; - - if((apduParam == NULL) || (apduParam->cApduBuf == NULL) || (apduParam->cApduLen == NULL)) { - return ERR_PARAM; - } - - msgIt = 0; - *(apduParam->cApduLen) = 0; - - /*******************************************************************************/ - /* Compute Command-APDU according to the format T4T 1.0 5.1.2 & ISO7816-4 2013 Table 1 */ - - /* Check if Data is present */ - if(apduParam->LcFlag) { - if(apduParam->Lc == 0U) { - /* Extended field coding not supported */ - return ERR_PARAM; - } - - /* Check whether requested Lc fits */ -#pragma GCC diagnostic ignored "-Wtype-limits" - if((uint16_t)apduParam->Lc > - (uint16_t)(RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN - RFAL_T4T_LE_LEN)) { - return ERR_PARAM; /* PRQA S 2880 # MISRA 2.1 - Unreachable code due to configuration option being set/unset */ - } - - /* Calculate the header length a place the data/body where it should be */ - hdrLen = RFAL_T4T_MAX_CAPDU_PROLOGUE_LEN + RFAL_T4T_LC_LEN; - - /* make sure not to exceed buffer size */ - if(((uint16_t)hdrLen + (uint16_t)apduParam->Lc + - (apduParam->LeFlag ? RFAL_T4T_LC_LEN : 0U)) > RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN) { - return ERR_NOMEM; /* PRQA S 2880 # MISRA 2.1 - Unreachable code due to configuration option being set/unset */ - } - ST_MEMMOVE(&apduParam->cApduBuf->apdu[hdrLen], apduParam->cApduBuf->apdu, apduParam->Lc); - } - - /* Prepend the ADPDU's header */ - apduParam->cApduBuf->apdu[msgIt++] = apduParam->CLA; - apduParam->cApduBuf->apdu[msgIt++] = apduParam->INS; - apduParam->cApduBuf->apdu[msgIt++] = apduParam->P1; - apduParam->cApduBuf->apdu[msgIt++] = apduParam->P2; - - /* Check if Data field length is to be added */ - if(apduParam->LcFlag) { - apduParam->cApduBuf->apdu[msgIt++] = apduParam->Lc; - msgIt += apduParam->Lc; - } - - /* Check if Expected Response Length is to be added */ - if(apduParam->LeFlag) { - apduParam->cApduBuf->apdu[msgIt++] = apduParam->Le; - } - - *(apduParam->cApduLen) = msgIt; - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalT4TPollerParseRAPDU(rfalT4tRApduParam* apduParam) { - if((apduParam == NULL) || (apduParam->rApduBuf == NULL)) { - return ERR_PARAM; - } - - if(apduParam->rcvdLen < RFAL_T4T_MAX_RAPDU_SW1SW2_LEN) { - return ERR_PROTO; - } - - apduParam->rApduBodyLen = (apduParam->rcvdLen - (uint16_t)RFAL_T4T_MAX_RAPDU_SW1SW2_LEN); - apduParam->statusWord = GETU16((&apduParam->rApduBuf->apdu[apduParam->rApduBodyLen])); - - /* Check SW1 SW2 T4T 1.0 5.1.3 NOTE */ - if(apduParam->statusWord == RFAL_T4T_ISO7816_STATUS_COMPLETE) { - return ERR_NONE; - } - - return ERR_REQUEST; -} - -/*******************************************************************************/ -ReturnCode rfalT4TPollerComposeSelectAppl( - rfalIsoDepApduBufFormat* cApduBuf, - const uint8_t* aid, - uint8_t aidLen, - uint16_t* cApduLen) { - rfalT4tCApduParam cAPDU; - - /* CLA INS P1 P2 Lc Data Le */ - /* 00h A4h 00h 00h 07h AID 00h */ - cAPDU.CLA = RFAL_T4T_CLA; - cAPDU.INS = (uint8_t)RFAL_T4T_INS_SELECT; - cAPDU.P1 = RFAL_T4T_ISO7816_P1_SELECT_BY_DF_NAME; - cAPDU.P2 = RFAL_T4T_ISO7816_P2_SELECT_FIRST_OR_ONLY_OCCURENCE | - RFAL_T4T_ISO7816_P2_SELECT_RETURN_FCI_TEMPLATE; - cAPDU.Lc = aidLen; - cAPDU.Le = 0x00; - cAPDU.LcFlag = true; - cAPDU.LeFlag = true; - cAPDU.cApduBuf = cApduBuf; - cAPDU.cApduLen = cApduLen; - - if(aidLen > 0U) { - ST_MEMCPY(cAPDU.cApduBuf->apdu, aid, aidLen); - } - - return rfalT4TPollerComposeCAPDU(&cAPDU); -} - -/*******************************************************************************/ -ReturnCode rfalT4TPollerComposeSelectFile( - rfalIsoDepApduBufFormat* cApduBuf, - const uint8_t* fid, - uint8_t fidLen, - uint16_t* cApduLen) { - rfalT4tCApduParam cAPDU; - - /* CLA INS P1 P2 Lc Data Le */ - /* 00h A4h 00h 0Ch 02h FID - */ - cAPDU.CLA = RFAL_T4T_CLA; - cAPDU.INS = (uint8_t)RFAL_T4T_INS_SELECT; - cAPDU.P1 = RFAL_T4T_ISO7816_P1_SELECT_BY_FILEID; - cAPDU.P2 = RFAL_T4T_ISO7816_P2_SELECT_FIRST_OR_ONLY_OCCURENCE | - RFAL_T4T_ISO7816_P2_SELECT_NO_RESPONSE_DATA; - cAPDU.Lc = fidLen; - cAPDU.Le = 0x00; - cAPDU.LcFlag = true; - cAPDU.LeFlag = false; - cAPDU.cApduBuf = cApduBuf; - cAPDU.cApduLen = cApduLen; - - if(fidLen > 0U) { - ST_MEMCPY(cAPDU.cApduBuf->apdu, fid, fidLen); - } - - return rfalT4TPollerComposeCAPDU(&cAPDU); -} - -/*******************************************************************************/ -ReturnCode rfalT4TPollerComposeSelectFileV1Mapping( - rfalIsoDepApduBufFormat* cApduBuf, - const uint8_t* fid, - uint8_t fidLen, - uint16_t* cApduLen) { - rfalT4tCApduParam cAPDU; - - /* CLA INS P1 P2 Lc Data Le */ - /* 00h A4h 00h 00h 02h FID - */ - cAPDU.CLA = RFAL_T4T_CLA; - cAPDU.INS = (uint8_t)RFAL_T4T_INS_SELECT; - cAPDU.P1 = RFAL_T4T_ISO7816_P1_SELECT_BY_FILEID; - cAPDU.P2 = RFAL_T4T_ISO7816_P2_SELECT_FIRST_OR_ONLY_OCCURENCE | - RFAL_T4T_ISO7816_P2_SELECT_RETURN_FCI_TEMPLATE; - cAPDU.Lc = fidLen; - cAPDU.Le = 0x00; - cAPDU.LcFlag = true; - cAPDU.LeFlag = false; - cAPDU.cApduBuf = cApduBuf; - cAPDU.cApduLen = cApduLen; - - if(fidLen > 0U) { - ST_MEMCPY(cAPDU.cApduBuf->apdu, fid, fidLen); - } - - return rfalT4TPollerComposeCAPDU(&cAPDU); -} - -/*******************************************************************************/ -ReturnCode rfalT4TPollerComposeReadData( - rfalIsoDepApduBufFormat* cApduBuf, - uint16_t offset, - uint8_t expLen, - uint16_t* cApduLen) { - rfalT4tCApduParam cAPDU; - - /* CLA INS P1 P2 Lc Data Le */ - /* 00h B0h [Offset] - - len */ - cAPDU.CLA = RFAL_T4T_CLA; - cAPDU.INS = (uint8_t)RFAL_T4T_INS_READBINARY; - cAPDU.P1 = (uint8_t)((offset >> 8U) & 0xFFU); - cAPDU.P2 = (uint8_t)((offset >> 0U) & 0xFFU); - cAPDU.Le = expLen; - cAPDU.LcFlag = false; - cAPDU.LeFlag = true; - cAPDU.cApduBuf = cApduBuf; - cAPDU.cApduLen = cApduLen; - - return rfalT4TPollerComposeCAPDU(&cAPDU); -} - -/*******************************************************************************/ -ReturnCode rfalT4TPollerComposeReadDataODO( - rfalIsoDepApduBufFormat* cApduBuf, - uint32_t offset, - uint8_t expLen, - uint16_t* cApduLen) { - rfalT4tCApduParam cAPDU; - uint8_t dataIt; - - /* CLA INS P1 P2 Lc Data Le */ - /* 00h B1h 00h 00h Lc 54 03 xxyyzz len */ - /* [Offset] */ - cAPDU.CLA = RFAL_T4T_CLA; - cAPDU.INS = (uint8_t)RFAL_T4T_INS_READBINARY_ODO; - cAPDU.P1 = 0x00U; - cAPDU.P2 = 0x00U; - cAPDU.Le = expLen; - cAPDU.LcFlag = true; - cAPDU.LeFlag = true; - cAPDU.cApduBuf = cApduBuf; - cAPDU.cApduLen = cApduLen; - - dataIt = 0U; - cApduBuf->apdu[dataIt++] = RFAL_T4T_OFFSET_DO; - cApduBuf->apdu[dataIt++] = RFAL_T4T_LENGTH_DO; - cApduBuf->apdu[dataIt++] = (uint8_t)(offset >> 16U); - cApduBuf->apdu[dataIt++] = (uint8_t)(offset >> 8U); - cApduBuf->apdu[dataIt++] = (uint8_t)(offset); - cAPDU.Lc = dataIt; - - return rfalT4TPollerComposeCAPDU(&cAPDU); -} - -/*******************************************************************************/ -ReturnCode rfalT4TPollerComposeWriteData( - rfalIsoDepApduBufFormat* cApduBuf, - uint16_t offset, - const uint8_t* data, - uint8_t dataLen, - uint16_t* cApduLen) { - rfalT4tCApduParam cAPDU; - - /* CLA INS P1 P2 Lc Data Le */ - /* 00h D6h [Offset] len Data - */ - cAPDU.CLA = RFAL_T4T_CLA; - cAPDU.INS = (uint8_t)RFAL_T4T_INS_UPDATEBINARY; - cAPDU.P1 = (uint8_t)((offset >> 8U) & 0xFFU); - cAPDU.P2 = (uint8_t)((offset >> 0U) & 0xFFU); - cAPDU.Lc = dataLen; - cAPDU.LcFlag = true; - cAPDU.LeFlag = false; - cAPDU.cApduBuf = cApduBuf; - cAPDU.cApduLen = cApduLen; - - if(dataLen > 0U) { - ST_MEMCPY(cAPDU.cApduBuf->apdu, data, dataLen); - } - - return rfalT4TPollerComposeCAPDU(&cAPDU); -} - -/*******************************************************************************/ -ReturnCode rfalT4TPollerComposeWriteDataODO( - rfalIsoDepApduBufFormat* cApduBuf, - uint32_t offset, - const uint8_t* data, - uint8_t dataLen, - uint16_t* cApduLen) { - rfalT4tCApduParam cAPDU; - uint8_t dataIt; - - /* CLA INS P1 P2 Lc Data Le */ - /* 00h D7h 00h 00h len 54 03 xxyyzz 53 Ld data - */ - /* [offset] [data] */ - cAPDU.CLA = RFAL_T4T_CLA; - cAPDU.INS = (uint8_t)RFAL_T4T_INS_UPDATEBINARY_ODO; - cAPDU.P1 = 0x00U; - cAPDU.P2 = 0x00U; - cAPDU.LcFlag = true; - cAPDU.LeFlag = false; - cAPDU.cApduBuf = cApduBuf; - cAPDU.cApduLen = cApduLen; - - dataIt = 0U; - cApduBuf->apdu[dataIt++] = RFAL_T4T_OFFSET_DO; - cApduBuf->apdu[dataIt++] = RFAL_T4T_LENGTH_DO; - cApduBuf->apdu[dataIt++] = (uint8_t)(offset >> 16U); - cApduBuf->apdu[dataIt++] = (uint8_t)(offset >> 8U); - cApduBuf->apdu[dataIt++] = (uint8_t)(offset); - cApduBuf->apdu[dataIt++] = RFAL_T4T_DATA_DO; - cApduBuf->apdu[dataIt++] = dataLen; - - if((((uint32_t)dataLen + (uint32_t)dataIt) >= RFAL_T4T_MAX_LC) || - (((uint32_t)dataLen + (uint32_t)dataIt) >= RFAL_FEATURE_ISO_DEP_APDU_MAX_LEN)) { - return (ERR_NOMEM); - } - - if(dataLen > 0U) { - ST_MEMCPY(&cAPDU.cApduBuf->apdu[dataIt], data, dataLen); - } - dataIt += dataLen; - cAPDU.Lc = dataIt; - - return rfalT4TPollerComposeCAPDU(&cAPDU); -} - -#endif /* RFAL_FEATURE_T4T */ diff --git a/lib/ST25RFAL002/source/st25r3916/rfal_analogConfigTbl.h b/lib/ST25RFAL002/source/st25r3916/rfal_analogConfigTbl.h deleted file mode 100644 index 554d6539a..000000000 --- a/lib/ST25RFAL002/source/st25r3916/rfal_analogConfigTbl.h +++ /dev/null @@ -1,1477 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file rfal_analogConfig.h - * - * \author bkam - * - * \brief ST25R3916 Analog Configuration Settings - * - */ - -#ifndef ST25R3916_ANALOGCONFIG_H -#define ST25R3916_ANALOGCONFIG_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_analogConfig.h" -#include "st25r3916_com.h" - -/* - ****************************************************************************** - * DEFINES - ****************************************************************************** - */ - -/* - ****************************************************************************** - * GLOBAL MACROS - ****************************************************************************** - */ - -/*! Macro for Configuration Setting with only one register-mask-value set: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1] */ -#define MODE_ENTRY_1_REG(MODE, R0, M0, V0) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 1, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0) - -/*! Macro for Configuration Setting with only two register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1] */ -#define MODE_ENTRY_2_REG(MODE, R0, M0, V0, R1, M1, V1) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 2, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1) - -/*! Macro for Configuration Setting with only three register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_3_REG(MODE, R0, M0, V0, R1, M1, V1, R2, M2, V2) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 3, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2) - -/*! Macro for Configuration Setting with only four register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_4_REG(MODE, R0, M0, V0, R1, M1, V1, R2, M2, V2, R3, M3, V3) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 4, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3) - -/*! Macro for Configuration Setting with only five register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_5_REG(MODE, R0, M0, V0, R1, M1, V1, R2, M2, V2, R3, M3, V3, R4, M4, V4) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 5, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8U), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4) - -/*! Macro for Configuration Setting with only six register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_6_REG( \ - MODE, R0, M0, V0, R1, M1, V1, R2, M2, V2, R3, M3, V3, R4, M4, V4, R5, M5, V5) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 6, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8U), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8U), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5) - -/*! Macro for Configuration Setting with only seven register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_7_REG( \ - MODE, R0, M0, V0, R1, M1, V1, R2, M2, V2, R3, M3, V3, R4, M4, V4, R5, M5, V5, R6, M6, V6) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 7, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8U), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8U), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8U), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6) - -/*! Macro for Configuration Setting with only eight register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_8_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 8, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8U), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8U), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8U), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8U), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7) - -/*! Macro for Configuration Setting with only nine register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_9_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7, \ - R8, \ - M8, \ - V8) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 9, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8U), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8U), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8U), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8U), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7), \ - (uint8_t)((uint16_t)(R8) >> 8U), (uint8_t)((R8)&0xFFU), (uint8_t)(M8), (uint8_t)(V8) - -/*! Macro for Configuration Setting with only ten register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_10_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7, \ - R8, \ - M8, \ - V8, \ - R9, \ - M9, \ - V9) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 10, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8U), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8U), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8U), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8U), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7), \ - (uint8_t)((uint16_t)(R8) >> 8U), (uint8_t)((R8)&0xFFU), (uint8_t)(M8), (uint8_t)(V8), \ - (uint8_t)((uint16_t)(R9) >> 8U), (uint8_t)((R9)&0xFFU), (uint8_t)(M9), (uint8_t)(V9) - -/*! Macro for Configuration Setting with eleven register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_11_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7, \ - R8, \ - M8, \ - V8, \ - R9, \ - M9, \ - V9, \ - R10, \ - M10, \ - V10) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 11, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8U), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8U), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8U), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8U), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7), \ - (uint8_t)((uint16_t)(R8) >> 8U), (uint8_t)((R8)&0xFFU), (uint8_t)(M8), (uint8_t)(V8), \ - (uint8_t)((uint16_t)(R9) >> 8U), (uint8_t)((R9)&0xFFU), (uint8_t)(M9), (uint8_t)(V9), \ - (uint8_t)((uint16_t)(R10) >> 8U), (uint8_t)((R10)&0xFFU), (uint8_t)(M10), (uint8_t)(V10) - -/*! Macro for Configuration Setting with twelve register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_12_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7, \ - R8, \ - M8, \ - V8, \ - R9, \ - M9, \ - V9, \ - R10, \ - M10, \ - V10, \ - R11, \ - M11, \ - V11) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 12, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8U), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8U), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8U), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8U), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7), \ - (uint8_t)((uint16_t)(R8) >> 8U), (uint8_t)((R8)&0xFFU), (uint8_t)(M8), (uint8_t)(V8), \ - (uint8_t)((uint16_t)(R9) >> 8U), (uint8_t)((R9)&0xFFU), (uint8_t)(M9), (uint8_t)(V9), \ - (uint8_t)((uint16_t)(R10) >> 8U), (uint8_t)((R10)&0xFFU), (uint8_t)(M10), (uint8_t)(V10), \ - (uint8_t)((uint16_t)(R11) >> 8U), (uint8_t)((R11)&0xFFU), (uint8_t)(M11), (uint8_t)(V11) - -/*! Macro for Configuration Setting with thirteen register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_13_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7, \ - R8, \ - M8, \ - V8, \ - R9, \ - M9, \ - V9, \ - R10, \ - M10, \ - V10, \ - R11, \ - M11, \ - V11, \ - R12, \ - M12, \ - V12) \ - (uint8_t)((uint16_t)(MODE) >> 8U), (uint8_t)((MODE)&0xFFU), 13, \ - (uint8_t)((uint16_t)(R0) >> 8U), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8U), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8U), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8U), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8U), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8U), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8U), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8U), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7), \ - (uint8_t)((uint16_t)(R8) >> 8U), (uint8_t)((R8)&0xFFU), (uint8_t)(M8), (uint8_t)(V8), \ - (uint8_t)((uint16_t)(R9) >> 8U), (uint8_t)((R9)&0xFFU), (uint8_t)(M9), (uint8_t)(V9), \ - (uint8_t)((uint16_t)(R10) >> 8U), (uint8_t)((R10)&0xFFU), (uint8_t)(M10), (uint8_t)(V10), \ - (uint8_t)((uint16_t)(R11) >> 8U), (uint8_t)((R11)&0xFFU), (uint8_t)(M11), (uint8_t)(V11), \ - (uint8_t)((uint16_t)(R12) >> 8U), (uint8_t)((R12)&0xFFU), (uint8_t)(M12), (uint8_t)(V12) - -/*! Macro for Configuration Setting with fourteen register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_14_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7, \ - R8, \ - M8, \ - V8, \ - R9, \ - M9, \ - V9, \ - R10, \ - M10, \ - V10, \ - R11, \ - M11, \ - V11, \ - R12, \ - M12, \ - V12, \ - R13, \ - M13, \ - V13, \ - R14, \ - M14, \ - V14, \ - R15, \ - M15, \ - V15) \ - (uint8_t)((uint16_t)(MODE) >> 8), (uint8_t)((MODE)&0xFFU), 14, \ - (uint8_t)((uint16_t)(R0) >> 8), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7), \ - (uint8_t)((uint16_t)(R8) >> 8), (uint8_t)((R8)&0xFFU), (uint8_t)(M8), (uint8_t)(V8), \ - (uint8_t)((uint16_t)(R9) >> 8), (uint8_t)((R9)&0xFFU), (uint8_t)(M9), (uint8_t)(V9), \ - (uint8_t)((uint16_t)(R10) >> 8), (uint8_t)((R10)&0xFFU), (uint8_t)(M10), (uint8_t)(V10), \ - (uint8_t)((uint16_t)(R11) >> 8), (uint8_t)((R11)&0xFFU), (uint8_t)(M11), (uint8_t)(V11), \ - (uint8_t)((uint16_t)(R12) >> 8), (uint8_t)((R12)&0xFFU), (uint8_t)(M12), (uint8_t)(V12), \ - (uint8_t)((uint16_t)(R13) >> 8), (uint8_t)((R13)&0xFFU), (uint8_t)(M13), (uint8_t)(V13) - -/*! Macro for Configuration Setting with fifteen register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_15_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7, \ - R8, \ - M8, \ - V8, \ - R9, \ - M9, \ - V9, \ - R10, \ - M10, \ - V10, \ - R11, \ - M11, \ - V11, \ - R12, \ - M12, \ - V12, \ - R13, \ - M13, \ - V13, \ - R14, \ - M14, \ - V14, \ - R15, \ - M15, \ - V15) \ - (uint8_t)((uint16_t)(MODE) >> 8), (uint8_t)((MODE)&0xFFU), 15, \ - (uint8_t)((uint16_t)(R0) >> 8), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7), \ - (uint8_t)((uint16_t)(R8) >> 8), (uint8_t)((R8)&0xFFU), (uint8_t)(M8), (uint8_t)(V8), \ - (uint8_t)((uint16_t)(R9) >> 8), (uint8_t)((R9)&0xFFU), (uint8_t)(M9), (uint8_t)(V9), \ - (uint8_t)((uint16_t)(R10) >> 8), (uint8_t)((R10)&0xFFU), (uint8_t)(M10), (uint8_t)(V10), \ - (uint8_t)((uint16_t)(R11) >> 8), (uint8_t)((R11)&0xFFU), (uint8_t)(M11), (uint8_t)(V11), \ - (uint8_t)((uint16_t)(R12) >> 8), (uint8_t)((R12)&0xFFU), (uint8_t)(M12), (uint8_t)(V12), \ - (uint8_t)((uint16_t)(R13) >> 8), (uint8_t)((R13)&0xFFU), (uint8_t)(M13), (uint8_t)(V13), \ - (uint8_t)((uint16_t)(R14) >> 8), (uint8_t)((R14)&0xFFU), (uint8_t)(M14), (uint8_t)(V14) - -/*! Macro for Configuration Setting with sixteen register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_16_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7, \ - R8, \ - M8, \ - V8, \ - R9, \ - M9, \ - V9, \ - R10, \ - M10, \ - V10, \ - R11, \ - M11, \ - V11, \ - R12, \ - M12, \ - V12, \ - R13, \ - M13, \ - V13, \ - R14, \ - M14, \ - V14, \ - R15, \ - M15, \ - V15) \ - (uint8_t)((uint16_t)(MODE) >> 8), (uint8_t)((MODE)&0xFFU), 16, \ - (uint8_t)((uint16_t)(R0) >> 8), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7), \ - (uint8_t)((uint16_t)(R8) >> 8), (uint8_t)((R8)&0xFFU), (uint8_t)(M8), (uint8_t)(V8), \ - (uint8_t)((uint16_t)(R9) >> 8), (uint8_t)((R9)&0xFFU), (uint8_t)(M9), (uint8_t)(V9), \ - (uint8_t)((uint16_t)(R10) >> 8), (uint8_t)((R10)&0xFFU), (uint8_t)(M10), (uint8_t)(V10), \ - (uint8_t)((uint16_t)(R11) >> 8), (uint8_t)((R11)&0xFFU), (uint8_t)(M11), (uint8_t)(V11), \ - (uint8_t)((uint16_t)(R12) >> 8), (uint8_t)((R12)&0xFFU), (uint8_t)(M12), (uint8_t)(V12), \ - (uint8_t)((uint16_t)(R13) >> 8), (uint8_t)((R13)&0xFFU), (uint8_t)(M13), (uint8_t)(V13), \ - (uint8_t)((uint16_t)(R14) >> 8), (uint8_t)((R14)&0xFFU), (uint8_t)(M14), (uint8_t)(V14), \ - (uint8_t)((uint16_t)(R15) >> 8), (uint8_t)((R15)&0xFFU), (uint8_t)(M15), (uint8_t)(V15) - -/*! Macro for Configuration Setting with seventeen register-mask-value sets: - * - Configuration ID[2], Number of Register sets to follow[1], Register[2], Mask[1], Value[1], Register[2], Mask[1], Value[1], Register[2]... */ -#define MODE_ENTRY_17_REG( \ - MODE, \ - R0, \ - M0, \ - V0, \ - R1, \ - M1, \ - V1, \ - R2, \ - M2, \ - V2, \ - R3, \ - M3, \ - V3, \ - R4, \ - M4, \ - V4, \ - R5, \ - M5, \ - V5, \ - R6, \ - M6, \ - V6, \ - R7, \ - M7, \ - V7, \ - R8, \ - M8, \ - V8, \ - R9, \ - M9, \ - V9, \ - R10, \ - M10, \ - V10, \ - R11, \ - M11, \ - V11, \ - R12, \ - M12, \ - V12, \ - R13, \ - M13, \ - V13, \ - R14, \ - M14, \ - V14, \ - R15, \ - M15, \ - V15, \ - R16, \ - M16, \ - V16) \ - (uint8_t)((uint16_t)(MODE) >> 8), (uint8_t)((MODE)&0xFFU), 17, \ - (uint8_t)((uint16_t)(R0) >> 8), (uint8_t)((R0)&0xFFU), (uint8_t)(M0), (uint8_t)(V0), \ - (uint8_t)((uint16_t)(R1) >> 8), (uint8_t)((R1)&0xFFU), (uint8_t)(M1), (uint8_t)(V1), \ - (uint8_t)((uint16_t)(R2) >> 8), (uint8_t)((R2)&0xFFU), (uint8_t)(M2), (uint8_t)(V2), \ - (uint8_t)((uint16_t)(R3) >> 8), (uint8_t)((R3)&0xFFU), (uint8_t)(M3), (uint8_t)(V3), \ - (uint8_t)((uint16_t)(R4) >> 8), (uint8_t)((R4)&0xFFU), (uint8_t)(M4), (uint8_t)(V4), \ - (uint8_t)((uint16_t)(R5) >> 8), (uint8_t)((R5)&0xFFU), (uint8_t)(M5), (uint8_t)(V5), \ - (uint8_t)((uint16_t)(R6) >> 8), (uint8_t)((R6)&0xFFU), (uint8_t)(M6), (uint8_t)(V6), \ - (uint8_t)((uint16_t)(R7) >> 8), (uint8_t)((R7)&0xFFU), (uint8_t)(M7), (uint8_t)(V7), \ - (uint8_t)((uint16_t)(R8) >> 8), (uint8_t)((R8)&0xFFU), (uint8_t)(M8), (uint8_t)(V8), \ - (uint8_t)((uint16_t)(R9) >> 8), (uint8_t)((R9)&0xFFU), (uint8_t)(M9), (uint8_t)(V9), \ - (uint8_t)((uint16_t)(R10) >> 8), (uint8_t)((R10)&0xFFU), (uint8_t)(M10), (uint8_t)(V10), \ - (uint8_t)((uint16_t)(R11) >> 8), (uint8_t)((R11)&0xFFU), (uint8_t)(M11), (uint8_t)(V11), \ - (uint8_t)((uint16_t)(R12) >> 8), (uint8_t)((R12)&0xFFU), (uint8_t)(M12), (uint8_t)(V12), \ - (uint8_t)((uint16_t)(R13) >> 8), (uint8_t)((R13)&0xFFU), (uint8_t)(M13), (uint8_t)(V13), \ - (uint8_t)((uint16_t)(R14) >> 8), (uint8_t)((R14)&0xFFU), (uint8_t)(M14), (uint8_t)(V14), \ - (uint8_t)((uint16_t)(R15) >> 8), (uint8_t)((R15)&0xFFU), (uint8_t)(M15), (uint8_t)(V15), \ - (uint8_t)((uint16_t)(R16) >> 8), (uint8_t)((R16)&0xFFU), (uint8_t)(M16), (uint8_t)(V16) -/* - ****************************************************************************** - * GLOBAL DATA TYPES - ****************************************************************************** - */ -/* PRQA S 3406 1 # MISRA 8.6 - Externally generated table included by the library */ /* PRQA S 1514 1 # MISRA 8.9 - Externally generated table included by the library */ -const uint8_t rfalAnalogConfigDefaultSettings[] = { - - /****** Default Analog Configuration for Chip-Specific Reset ******/ - MODE_ENTRY_17_REG( - (RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_INIT), - ST25R3916_REG_IO_CONF1, - (ST25R3916_REG_IO_CONF1_out_cl_mask | ST25R3916_REG_IO_CONF1_lf_clk_off), - 0x07 /* Disable MCU_CLK */ - , - ST25R3916_REG_IO_CONF2, - (ST25R3916_REG_IO_CONF2_miso_pd1 | ST25R3916_REG_IO_CONF2_miso_pd2), - 0x18 /* SPI Pull downs */ - , - ST25R3916_REG_IO_CONF2, - ST25R3916_REG_IO_CONF2_aat_en, - ST25R3916_REG_IO_CONF2_aat_en /* Enable AAT */ - , - ST25R3916_REG_TX_DRIVER, - ST25R3916_REG_TX_DRIVER_d_res_mask, - 0x00 /* Set RFO resistance Active Tx */ - , - ST25R3916_REG_RES_AM_MOD, - 0xFF, - 0x80 /* Use minimum non-overlap */ - , - ST25R3916_REG_FIELD_THRESHOLD_ACTV, - ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_mask, - ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_105mV /* Lower activation threshold (higher than deactivation)*/ - , - ST25R3916_REG_FIELD_THRESHOLD_ACTV, - ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_mask, - ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_105mV /* Lower activation threshold (higher than deactivation)*/ - , - ST25R3916_REG_FIELD_THRESHOLD_DEACTV, - ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_mask, - ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_75mV /* Lower deactivation threshold */ - , - ST25R3916_REG_FIELD_THRESHOLD_DEACTV, - ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_mask, - ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_75mV /* Lower deactivation threshold */ - , - ST25R3916_REG_AUX_MOD, - ST25R3916_REG_AUX_MOD_lm_ext, - 0x00 /* Disable External Load Modulation */ - , - ST25R3916_REG_AUX_MOD, - ST25R3916_REG_AUX_MOD_lm_dri, - ST25R3916_REG_AUX_MOD_lm_dri /* Use internal Load Modulation */ - , - ST25R3916_REG_PASSIVE_TARGET, - ST25R3916_REG_PASSIVE_TARGET_fdel_mask, - (5U - << ST25R3916_REG_PASSIVE_TARGET_fdel_shift) /* Adjust the FDT to be aligned with the bitgrid */ - , - ST25R3916_REG_PT_MOD, - (ST25R3916_REG_PT_MOD_ptm_res_mask | ST25R3916_REG_PT_MOD_pt_res_mask), - 0x5f /* Reduce RFO resistance in Modulated state */ - , - ST25R3916_REG_EMD_SUP_CONF, - ST25R3916_REG_EMD_SUP_CONF_rx_start_emv, - ST25R3916_REG_EMD_SUP_CONF_rx_start_emv_on /* Enable start on first 4 bits */ - , - ST25R3916_REG_ANT_TUNE_A, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_ANT_TUNE_B, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - 0x84U, - 0x10, - 0x10 /* Avoid chip internal overheat protection */ - ) - - /****** Default Analog Configuration for Chip-Specific Poll Common ******/ - , - MODE_ENTRY_9_REG( - (RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_POLL_COMMON), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - , - ST25R3916_REG_TX_DRIVER, - ST25R3916_REG_TX_DRIVER_am_mod_mask, - ST25R3916_REG_TX_DRIVER_am_mod_12percent /* Set Modulation index */ - , - ST25R3916_REG_AUX_MOD, - (ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am), - 0x00 /* Use AM via regulator */ - , - ST25R3916_REG_ANT_TUNE_A, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_ANT_TUNE_B, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx Common ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_correlator /* Use Correlator Receiver */ - ) - - /****** Default Analog Configuration for Poll NFC-A Tx 106 ******/ - , - MODE_ENTRY_5_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_106 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_ook /* Use OOK */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx 106 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_106 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x08, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x2D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x51, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-A Tx 212 ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_212 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - , - ST25R3916_REG_AUX_MOD, - (ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am), - 0x88 /* Use Resistive AM */ - , - ST25R3916_REG_RES_AM_MOD, - ST25R3916_REG_RES_AM_MOD_md_res_mask, - 0x7F /* Set Resistive modulation */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx 212 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_212 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x02, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x14, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-A Tx 424 ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_424 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - , - ST25R3916_REG_AUX_MOD, - (ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am), - 0x88 /* Use Resistive AM */ - , - ST25R3916_REG_RES_AM_MOD, - ST25R3916_REG_RES_AM_MOD_md_res_mask, - 0x7F /* Set Resistive modulation */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx 424 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_424 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x42, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x54, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-A Tx 848 ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_848 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - , - ST25R3916_REG_TX_DRIVER, - ST25R3916_REG_TX_DRIVER_am_mod_mask, - ST25R3916_REG_TX_DRIVER_am_mod_40percent /* Set Modulation index */ - , - ST25R3916_REG_AUX_MOD, - (ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am), - 0x00 /* Use AM via regulator */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll NFC-A Rx 848 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | RFAL_ANALOG_CONFIG_BITRATE_848 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x42, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x44, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-A Anticolision setting ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_ANTICOL), - ST25R3916_REG_CORR_CONF1, - ST25R3916_REG_CORR_CONF1_corr_s6, - 0x00 /* Set collision detection level different from data */ - ) - -#ifdef RFAL_USE_COHE - /****** Default Analog Configuration for Poll NFC-B Rx Common ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_coherent /* Use Coherent Receiver */ - ) -#else - /****** Default Analog Configuration for Poll NFC-B Rx Common ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_correlator /* Use Correlator Receiver */ - ) -#endif /*RFAL_USE_COHE*/ - - /****** Default Analog Configuration for Poll NFC-B Rx 106 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | RFAL_ANALOG_CONFIG_BITRATE_106 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x04, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x1B, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-B Rx 212 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | RFAL_ANALOG_CONFIG_BITRATE_212 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x02, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x14, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-B Rx 424 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | RFAL_ANALOG_CONFIG_BITRATE_424 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x42, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x54, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) - - /****** Default Analog Configuration for Poll NFC-B Rx 848 ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | RFAL_ANALOG_CONFIG_BITRATE_848 | - RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x42, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x44, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) -#ifdef RFAL_USE_COHE - - /****** Default Analog Configuration for Poll NFC-F Rx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCF | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_coherent /* Use Pulse Receiver */ - , - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x54, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) -#else - /****** Default Analog Configuration for Poll NFC-F Rx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCF | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_correlator /* Use Correlator Receiver */ - , - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x3D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x54, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x00) -#endif /*RFAL_USE_COHE*/ - - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | RFAL_ANALOG_CONFIG_BITRATE_1OF4 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_ook /* Use OOK */ - ) - -#ifdef RFAL_USE_COHE - /****** Default Analog Configuration for Poll NFC-V Rx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_coherent /* Use Pulse Receiver */ - , - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x2D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x01) -#else - /****** Default Analog Configuration for Poll NFC-V Rx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_AUX, - ST25R3916_REG_AUX_dis_corr, - ST25R3916_REG_AUX_dis_corr_correlator /* Use Correlator Receiver */ - , - ST25R3916_REG_RX_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_RX_CONF2, - 0xFF, - 0x2D, - ST25R3916_REG_RX_CONF3, - 0xFF, - 0x00, - ST25R3916_REG_RX_CONF4, - 0xFF, - 0x00, - ST25R3916_REG_CORR_CONF1, - 0xFF, - 0x13, - ST25R3916_REG_CORR_CONF2, - 0xFF, - 0x01) -#endif /*RFAL_USE_COHE*/ - - /****** Default Analog Configuration for Poll AP2P Tx 106 ******/ - , - MODE_ENTRY_5_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | RFAL_ANALOG_CONFIG_BITRATE_106 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_ook /* Use OOK modulation */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Poll AP2P Tx 212 ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | RFAL_ANALOG_CONFIG_BITRATE_212 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - ) - - /****** Default Analog Configuration for Poll AP2P Tx 424 ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | RFAL_ANALOG_CONFIG_BITRATE_424 | - RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - ) - - /****** Default Analog Configuration for Chip-Specific Listen On ******/ - , - MODE_ENTRY_6_REG( - (RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_LISTEN_ON), - ST25R3916_REG_ANT_TUNE_A, - 0xFF, - 0x00 /* Set Antenna Tuning (Listener): ANTL */ - , - ST25R3916_REG_ANT_TUNE_B, - 0xFF, - 0xff /* Set Antenna Tuning (Listener): ANTL */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - ) - - /****** Default Analog Configuration for Listen AP2P Tx Common ******/ - , - MODE_ENTRY_7_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_ANT_TUNE_A, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_ANT_TUNE_B, - 0xFF, - 0x82 /* Set Antenna Tuning (Poller): ANTL */ - , - ST25R3916_REG_TX_DRIVER, - ST25R3916_REG_TX_DRIVER_am_mod_mask, - ST25R3916_REG_TX_DRIVER_am_mod_12percent /* Set Modulation index */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x00 /* Disable Undershoot Protection */ - ) - - /****** Default Analog Configuration for Listen AP2P Rx Common ******/ - , - MODE_ENTRY_3_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX), - ST25R3916_REG_RX_CONF1, - ST25R3916_REG_RX_CONF1_lp_mask, - ST25R3916_REG_RX_CONF1_lp_1200khz /* Set Rx filter configuration */ - , - ST25R3916_REG_RX_CONF1, - ST25R3916_REG_RX_CONF1_hz_mask, - ST25R3916_REG_RX_CONF1_hz_12_200khz /* Set Rx filter configuration */ - , - ST25R3916_REG_RX_CONF2, - ST25R3916_REG_RX_CONF2_amd_sel, - ST25R3916_REG_RX_CONF2_amd_sel_mixer /* AM demodulator: mixer */ - ) - - /****** Default Analog Configuration for Listen AP2P Tx 106 ******/ - , - MODE_ENTRY_5_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_106 | RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_ook /* Use OOK modulation */ - , - ST25R3916_REG_OVERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Overshoot Protection */ - , - ST25R3916_REG_OVERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Overshoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF1, - 0xFF, - 0x40 /* Set default Undershoot Protection */ - , - ST25R3916_REG_UNDERSHOOT_CONF2, - 0xFF, - 0x03 /* Set default Undershoot Protection */ - ) - - /****** Default Analog Configuration for Listen AP2P Tx 212 ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_212 | RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - ) - - /****** Default Analog Configuration for Listen AP2P Tx 424 ******/ - , - MODE_ENTRY_1_REG( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_424 | RFAL_ANALOG_CONFIG_TX), - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_tr_am, - ST25R3916_REG_MODE_tr_am_am /* Use AM modulation */ - ) - -}; - -#endif /* ST25R3916_ANALOGCONFIG_H */ diff --git a/lib/ST25RFAL002/source/st25r3916/rfal_dpoTbl.h b/lib/ST25RFAL002/source/st25r3916/rfal_dpoTbl.h deleted file mode 100644 index 3075776c5..000000000 --- a/lib/ST25RFAL002/source/st25r3916/rfal_dpoTbl.h +++ /dev/null @@ -1,68 +0,0 @@ - -/****************************************************************************** - * @attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * $Revision: $ - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Martin Zechleitner - * - * \brief RF Dynamic Power Table default values - */ - -#ifndef ST25R3916_DPO_H -#define ST25R3916_DPO_H - -/* - ****************************************************************************** - * INCLUDES - ****************************************************************************** - */ -#include "rfal_dpo.h" - -/* - ****************************************************************************** - * GLOBAL DATA TYPES - ****************************************************************************** - */ - -/*! Default DPO table */ -const uint8_t rfalDpoDefaultSettings[] = { - 0x00, - 255, - 200, - 0x01, - 210, - 150, - 0x02, - 160, - 100, - 0x03, - 110, - 50, -}; - -#endif /* ST25R3916_DPO_H */ diff --git a/lib/ST25RFAL002/source/st25r3916/rfal_features.h b/lib/ST25RFAL002/source/st25r3916/rfal_features.h deleted file mode 100644 index 92f26acf5..000000000 --- a/lib/ST25RFAL002/source/st25r3916/rfal_features.h +++ /dev/null @@ -1,109 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R391x firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Gustavo Patricio - * - * \brief RFAL Features/Capabilities Definition for ST25R3916 - */ - -#ifndef RFAL_FEATURES_H -#define RFAL_FEATURES_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "platform.h" - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ - -#define RFAL_SUPPORT_MODE_POLL_NFCA true /*!< RFAL Poll NFCA mode support switch */ -#define RFAL_SUPPORT_MODE_POLL_NFCB true /*!< RFAL Poll NFCB mode support switch */ -#define RFAL_SUPPORT_MODE_POLL_NFCF true /*!< RFAL Poll NFCF mode support switch */ -#define RFAL_SUPPORT_MODE_POLL_NFCV true /*!< RFAL Poll NFCV mode support switch */ -#define RFAL_SUPPORT_MODE_POLL_ACTIVE_P2P true /*!< RFAL Poll AP2P mode support switch */ -#define RFAL_SUPPORT_MODE_LISTEN_NFCA true /*!< RFAL Listen NFCA mode support switch */ -#define RFAL_SUPPORT_MODE_LISTEN_NFCB false /*!< RFAL Listen NFCB mode support switch */ -#define RFAL_SUPPORT_MODE_LISTEN_NFCF true /*!< RFAL Listen NFCF mode support switch */ -#define RFAL_SUPPORT_MODE_LISTEN_ACTIVE_P2P true /*!< RFAL Listen AP2P mode support switch */ - -/*******************************************************************************/ -/*! RFAL supported Card Emulation (CE) */ -#define RFAL_SUPPORT_CE \ - (RFAL_SUPPORT_MODE_LISTEN_NFCA || RFAL_SUPPORT_MODE_LISTEN_NFCB || \ - RFAL_SUPPORT_MODE_LISTEN_NFCF) - -/*! RFAL supported Reader/Writer (RW) */ -#define RFAL_SUPPORT_RW \ - (RFAL_SUPPORT_MODE_POLL_NFCA || RFAL_SUPPORT_MODE_POLL_NFCB || RFAL_SUPPORT_MODE_POLL_NFCF || \ - RFAL_SUPPORT_MODE_POLL_NFCV) - -/*! RFAL support for Active P2P (AP2P) */ -#define RFAL_SUPPORT_AP2P \ - (RFAL_SUPPORT_MODE_POLL_ACTIVE_P2P || RFAL_SUPPORT_MODE_LISTEN_ACTIVE_P2P) - -/*******************************************************************************/ -#define RFAL_SUPPORT_BR_RW_106 true /*!< RFAL RW 106 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_RW_212 true /*!< RFAL RW 212 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_RW_424 true /*!< RFAL RW 424 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_RW_848 true /*!< RFAL RW 848 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_RW_1695 false /*!< RFAL RW 1695 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_RW_3390 false /*!< RFAL RW 3390 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_RW_6780 false /*!< RFAL RW 6780 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_RW_13560 false /*!< RFAL RW 6780 Bit Rate support switch */ - -/*******************************************************************************/ -#define RFAL_SUPPORT_BR_AP2P_106 true /*!< RFAL AP2P 106 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_AP2P_212 true /*!< RFAL AP2P 212 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_AP2P_424 true /*!< RFAL AP2P 424 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_AP2P_848 false /*!< RFAL AP2P 848 Bit Rate support switch */ - -/*******************************************************************************/ -#define RFAL_SUPPORT_BR_CE_A_106 true /*!< RFAL CE A 106 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_CE_A_212 false /*!< RFAL CE A 212 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_CE_A_424 false /*!< RFAL CE A 424 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_CE_A_848 false /*!< RFAL CE A 848 Bit Rate support switch */ - -/*******************************************************************************/ -#define RFAL_SUPPORT_BR_CE_B_106 false /*!< RFAL CE B 106 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_CE_B_212 false /*!< RFAL CE B 212 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_CE_B_424 false /*!< RFAL CE B 424 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_CE_B_848 false /*!< RFAL CE B 848 Bit Rate support switch */ - -/*******************************************************************************/ -#define RFAL_SUPPORT_BR_CE_F_212 true /*!< RFAL CE F 212 Bit Rate support switch */ -#define RFAL_SUPPORT_BR_CE_F_424 true /*!< RFAL CE F 424 Bit Rate support switch */ - -#endif /* RFAL_FEATURES_H */ diff --git a/lib/ST25RFAL002/source/st25r3916/rfal_rfst25r3916.c b/lib/ST25RFAL002/source/st25r3916/rfal_rfst25r3916.c deleted file mode 100644 index 7b8c243b1..000000000 --- a/lib/ST25RFAL002/source/st25r3916/rfal_rfst25r3916.c +++ /dev/null @@ -1,4815 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Gustavo Patricio - * - * \brief RF Abstraction Layer (RFAL) - * - * RFAL implementation for ST25R3916 - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ - -#include "rfal_chip.h" -#include "utils.h" -#include "st25r3916.h" -#include "st25r3916_com.h" -#include "st25r3916_irq.h" -#include "rfal_analogConfig.h" -#include "rfal_iso15693_2.h" -#include "rfal_crc.h" - -/* - ****************************************************************************** - * ENABLE SWITCHES - ****************************************************************************** - */ - -#ifndef RFAL_FEATURE_LISTEN_MODE -#define RFAL_FEATURE_LISTEN_MODE false /* Listen Mode configuration missing. Disabled by default */ -#endif /* RFAL_FEATURE_LISTEN_MODE */ - -#ifndef RFAL_FEATURE_WAKEUP_MODE -#define RFAL_FEATURE_WAKEUP_MODE \ - false /* Wake-Up mode configuration missing. Disabled by default */ -#endif /* RFAL_FEATURE_WAKEUP_MODE */ - -#ifndef RFAL_FEATURE_LOWPOWER_MODE -#define RFAL_FEATURE_LOWPOWER_MODE \ - false /* Low Power mode configuration missing. Disabled by default */ -#endif /* RFAL_FEATURE_LOWPOWER_MODE */ - -/* -****************************************************************************** -* GLOBAL TYPES -****************************************************************************** -*/ - -/*! Struct that holds all involved on a Transceive including the context passed by the caller */ -typedef struct { - rfalTransceiveState state; /*!< Current transceive state */ - rfalTransceiveState lastState; /*!< Last transceive state (debug purposes) */ - ReturnCode status; /*!< Current status/error of the transceive */ - - rfalTransceiveContext ctx; /*!< The transceive context given by the caller */ -} rfalTxRx; - -/*! Struct that holds all context for the Listen Mode */ -typedef struct { - rfalLmState state; /*!< Current Listen Mode state */ - uint32_t mdMask; /*!< Listen Mode mask used */ - uint32_t mdReg; /*!< Listen Mode register value used */ - uint32_t mdIrqs; /*!< Listen Mode IRQs used */ - rfalBitRate brDetected; /*!< Last bit rate detected */ - - uint8_t* rxBuf; /*!< Location to store incoming data in Listen Mode */ - uint16_t rxBufLen; /*!< Length of rxBuf */ - uint16_t* rxLen; /*!< Pointer to write the data length placed into rxBuf */ - bool dataFlag; /*!< Listen Mode current Data Flag */ - bool iniFlag; /*!< Listen Mode initialized Flag (FeliCa slots) */ -} rfalLm; - -/*! Struct that holds all context for the Wake-Up Mode */ -typedef struct { - rfalWumState state; /*!< Current Wake-Up Mode state */ - rfalWakeUpConfig cfg; /*!< Current Wake-Up Mode context */ -} rfalWum; - -/*! Struct that holds all context for the Low Power Mode */ -typedef struct { - bool isRunning; -} rfalLpm; - -/*! Struct that holds the timings GT and FDTs */ -typedef struct { - uint32_t GT; /*!< GT in 1/fc */ - uint32_t FDTListen; /*!< FDTListen in 1/fc */ - uint32_t FDTPoll; /*!< FDTPoll in 1/fc */ - uint8_t nTRFW; /*!< n*TRFW used during RF CA */ -} rfalTimings; - -/*! Struct that holds the software timers */ -typedef struct { - uint32_t GT; /*!< RFAL's GT timer */ - uint32_t RXE; /*!< Timer between RXS and RXE */ - uint32_t txRx; /*!< Transceive sanity timer */ -} rfalTimers; - -/*! Struct that holds the RFAL's callbacks */ -typedef struct { - rfalPreTxRxCallback preTxRx; /*!< RFAL's Pre TxRx callback */ - rfalPostTxRxCallback postTxRx; /*!< RFAL's Post TxRx callback */ - RfalStateChangedCallback state_changed_cb; - void* ctx; -} rfalCallbacks; - -/*! Struct that holds counters to control the FIFO on Tx and Rx */ -typedef struct { - uint16_t - expWL; /*!< The amount of bytes expected to be Tx when a WL interrupt occurs */ - uint16_t - bytesTotal; /*!< Total bytes to be transmitted OR the total bytes received */ - uint16_t - bytesWritten; /*!< Amount of bytes already written on FIFO (Tx) OR read (RX) from FIFO and written on rxBuffer*/ - uint8_t status - [ST25R3916_FIFO_STATUS_LEN]; /*!< FIFO Status Registers */ -} rfalFIFO; - -/*! Struct that holds RFAL's configuration settings */ -typedef struct { - uint8_t obsvModeTx; /*!< RFAL's config of the ST25R3916's observation mode while Tx */ - uint8_t obsvModeRx; /*!< RFAL's config of the ST25R3916's observation mode while Rx */ - rfalEHandling eHandling; /*!< RFAL's error handling config/mode */ -} rfalConfigs; - -/*! Struct that holds NFC-F data - Used only inside rfalFelicaPoll() (static to avoid adding it into stack) */ -typedef struct { - rfalFeliCaPollRes - pollResponses[RFAL_FELICA_POLL_MAX_SLOTS]; /* FeliCa Poll response container for 16 slots */ -} rfalNfcfWorkingData; - -/*! Struct that holds NFC-V current context - * - * This buffer has to be big enough for coping with maximum response size (hamming coded) - * - inventory requests responses: 14*2+2 bytes - * - read single block responses: (32+4)*2+2 bytes - * - read multiple block could be very long... -> not supported - * - current implementation expects it be written in one bulk into FIFO - * - needs to be above FIFO water level of ST25R3916 (200) - * - the coding function needs to be able to - * put more than FIFO water level bytes into it (n*64+1)>200 */ -typedef struct { - uint8_t codingBuffer[( - (2 + 255 + 3) * 2)]; /*!< Coding buffer, length MUST be above 257: [257; ...] */ - uint16_t - nfcvOffset; /*!< Offset needed for ISO15693 coding function */ - rfalTransceiveContext - origCtx; /*!< context provided by user */ - uint16_t - ignoreBits; /*!< Number of bits at the beginning of a frame to be ignored when decoding */ -} rfalNfcvWorkingData; - -/*! RFAL instance */ -typedef struct { - rfalState state; /*!< RFAL's current state */ - rfalMode mode; /*!< RFAL's current mode */ - rfalBitRate txBR; /*!< RFAL's current Tx Bit Rate */ - rfalBitRate rxBR; /*!< RFAL's current Rx Bit Rate */ - bool field; /*!< Current field state (On / Off) */ - - rfalConfigs conf; /*!< RFAL's configuration settings */ - rfalTimings timings; /*!< RFAL's timing setting */ - rfalTxRx TxRx; /*!< RFAL's transceive management */ - rfalFIFO fifo; /*!< RFAL's FIFO management */ - rfalTimers tmr; /*!< RFAL's Software timers */ - rfalCallbacks callbacks; /*!< RFAL's callbacks */ - -#if RFAL_FEATURE_LISTEN_MODE - rfalLm Lm; /*!< RFAL's listen mode management */ -#endif /* RFAL_FEATURE_LISTEN_MODE */ - -#if RFAL_FEATURE_WAKEUP_MODE - rfalWum wum; /*!< RFAL's Wake-up mode management */ -#endif /* RFAL_FEATURE_WAKEUP_MODE */ - -#if RFAL_FEATURE_LOWPOWER_MODE - rfalLpm lpm; /*!< RFAL's Low power mode management */ -#endif /* RFAL_FEATURE_LOWPOWER_MODE */ - -#if RFAL_FEATURE_NFCF - rfalNfcfWorkingData nfcfData; /*!< RFAL's working data when supporting NFC-F */ -#endif /* RFAL_FEATURE_NFCF */ - -#if RFAL_FEATURE_NFCV - rfalNfcvWorkingData nfcvData; /*!< RFAL's working data when performing NFC-V */ -#endif /* RFAL_FEATURE_NFCV */ - -} rfal; - -/*! Felica's command set */ -typedef enum { - FELICA_CMD_POLLING = - 0x00, /*!< Felica Poll/REQC command (aka SENSF_REQ) to identify a card */ - FELICA_CMD_POLLING_RES = - 0x01, /*!< Felica Poll/REQC command (aka SENSF_RES) response */ - FELICA_CMD_REQUEST_SERVICE = - 0x02, /*!< verify the existence of Area and Service */ - FELICA_CMD_REQUEST_RESPONSE = - 0x04, /*!< verify the existence of a card */ - FELICA_CMD_READ_WITHOUT_ENCRYPTION = - 0x06, /*!< read Block Data from a Service that requires no authentication */ - FELICA_CMD_WRITE_WITHOUT_ENCRYPTION = - 0x08, /*!< write Block Data to a Service that requires no authentication */ - FELICA_CMD_REQUEST_SYSTEM_CODE = - 0x0C, /*!< acquire the System Code registered to a card */ - FELICA_CMD_AUTHENTICATION1 = - 0x10, /*!< authenticate a card */ - FELICA_CMD_AUTHENTICATION2 = - 0x12, /*!< allow a card to authenticate a Reader/Writer */ - FELICA_CMD_READ = 0x14, /*!< read Block Data from a Service that requires authentication */ - FELICA_CMD_WRITE = 0x16, /*!< write Block Data to a Service that requires authentication */ -} t_rfalFeliCaCmd; - -/*! Union representing all PTMem sections */ -typedef union { /* PRQA S 0750 # MISRA 19.2 - Both members are of the same type, just different names. Thus no problem can occur. */ - uint8_t PTMem_A - [ST25R3916_PTM_A_LEN]; /*!< PT_Memory area allocated for NFC-A configuration */ - uint8_t PTMem_F - [ST25R3916_PTM_F_LEN]; /*!< PT_Memory area allocated for NFC-F configuration */ - uint8_t - TSN[ST25R3916_PTM_TSN_LEN]; /*!< PT_Memory area allocated for TSN - Random numbers */ -} t_rfalPTMem; - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ - -#define RFAL_FIFO_IN_WL \ - 200U /*!< Number of bytes in the FIFO when WL interrupt occurs while Tx */ -#define RFAL_FIFO_OUT_WL \ - (ST25R3916_FIFO_DEPTH - \ - RFAL_FIFO_IN_WL) /*!< Number of bytes sent/out of the FIFO when WL interrupt occurs while Tx */ - -#define RFAL_FIFO_STATUS_REG1 \ - 0U /*!< Location of FIFO status register 1 in local copy */ -#define RFAL_FIFO_STATUS_REG2 \ - 1U /*!< Location of FIFO status register 2 in local copy */ -#define RFAL_FIFO_STATUS_INVALID \ - 0xFFU /*!< Value indicating that the local FIFO status in invalid|cleared */ - -#define RFAL_ST25R3916_GPT_MAX_1FC \ - rfalConv8fcTo1fc( \ - 0xFFFFU) /*!< Max GPT steps in 1fc (0xFFFF steps of 8/fc => 0xFFFF * 590ns = 38,7ms) */ -#define RFAL_ST25R3916_NRT_MAX_1FC \ - rfalConv4096fcTo1fc( \ - 0xFFFFU) /*!< Max NRT steps in 1fc (0xFFFF steps of 4096/fc => 0xFFFF * 302us = 19.8s ) */ -#define RFAL_ST25R3916_NRT_DISABLED \ - 0U /*!< NRT Disabled: All 0 No-response timer is not started, wait forever */ -#define RFAL_ST25R3916_MRT_MAX_1FC \ - rfalConv64fcTo1fc( \ - 0x00FFU) /*!< Max MRT steps in 1fc (0x00FF steps of 64/fc => 0x00FF * 4.72us = 1.2ms ) */ -#define RFAL_ST25R3916_MRT_MIN_1FC \ - rfalConv64fcTo1fc( \ - 0x0004U) /*!< Min MRT steps in 1fc ( 0<=mrt<=4 ; 4 (64/fc) => 0x0004 * 4.72us = 18.88us ) */ -#define RFAL_ST25R3916_GT_MAX_1FC \ - rfalConvMsTo1fc( \ - 6000U) /*!< Max GT value allowed in 1/fc (SFGI=14 => SFGT + dSFGT = 5.4s) */ -#define RFAL_ST25R3916_GT_MIN_1FC \ - rfalConvMsTo1fc( \ - RFAL_ST25R3916_SW_TMR_MIN_1MS) /*!< Min GT value allowed in 1/fc */ -#define RFAL_ST25R3916_SW_TMR_MIN_1MS \ - 1U /*!< Min value of a SW timer in ms */ - -#define RFAL_OBSMODE_DISABLE \ - 0x00U /*!< Observation Mode disabled */ - -#define RFAL_RX_INCOMPLETE_MAXLEN \ - (uint8_t)1U /*!< Threshold value where incoming rx may be considered as incomplete */ -#define RFAL_EMVCO_RX_MAXLEN \ - (uint8_t)4U /*!< Maximum value where EMVCo to apply special error handling */ - -#define RFAL_NORXE_TOUT \ - 50U /*!< Timeout to be used on a potential missing RXE - Silicon ST25R3916 Errata #TBD */ - -#define RFAL_ISO14443A_SDD_RES_LEN \ - 5U /*!< SDD_RES | Anticollision (UID CLn) length - rfalNfcaSddRes */ -#define RFAL_ISO14443A_CRC_INTVAL \ - 0x6363 /*!< ISO14443 CRC Initial Value|Register */ - -#define RFAL_FELICA_POLL_DELAY_TIME \ - 512U /*!< FeliCa Poll Processing time is 2.417 ms ~512*64/fc Digital 1.1 A4 */ -#define RFAL_FELICA_POLL_SLOT_TIME \ - 256U /*!< FeliCa Poll Time Slot duration is 1.208 ms ~256*64/fc Digital 1.1 A4 */ - -#define RFAL_LM_SENSF_RD0_POS \ - 17U /*!< FeliCa SENSF_RES Request Data RD0 position */ -#define RFAL_LM_SENSF_RD1_POS \ - 18U /*!< FeliCa SENSF_RES Request Data RD1 position */ - -#define RFAL_LM_NFCID_INCOMPLETE \ - 0x04U /*!< NFCA NFCID not complete bit in SEL_RES (SAK) */ - -#define RFAL_ISO15693_IGNORE_BITS \ - rfalConvBytesToBits( \ - 2U) /*!< Ignore collisions before the UID (RES_FLAG + DSFID) */ -#define RFAL_ISO15693_INV_RES_LEN \ - 12U /*!< ISO15693 Inventory response length with CRC (bytes) */ -#define RFAL_ISO15693_INV_RES_DUR \ - 4U /*!< ISO15693 Inventory response duration @ 26 kbps (ms) */ - -#define RFAL_WU_MIN_WEIGHT_VAL \ - 4U /*!< ST25R3916 minimum Wake-up weight value */ - -/*******************************************************************************/ - -#define RFAL_LM_GT \ - rfalConvUsTo1fc( \ - 100U) /*!< Listen Mode Guard Time enforced (GT - Passive; TIRFG - Active) */ -#define RFAL_FDT_POLL_ADJUSTMENT \ - rfalConvUsTo1fc( \ - 80U) /*!< FDT Poll adjustment: Time between the expiration of GPT to the actual Tx */ -#define RFAL_FDT_LISTEN_MRT_ADJUSTMENT \ - 64U /*!< MRT jitter adjustment: timeout will be between [ tout ; tout + 64 cycles ] */ -#define RFAL_AP2P_FIELDOFF_TRFW \ - rfalConv8fcTo1fc( \ - 64U) /*!< Time after TXE and Field Off in AP2P Trfw: 37.76us -> 64 (8/fc) */ - -#ifndef RFAL_ST25R3916_AAT_SETTLE -#define RFAL_ST25R3916_AAT_SETTLE \ - 5U /*!< Time in ms required for AAT pins and Osc to settle after en bit set */ -#endif /* RFAL_ST25R3916_AAT_SETTLE */ - -/*! FWT adjustment: - * 64 : NRT jitter between TXE and NRT start */ -#define RFAL_FWT_ADJUSTMENT 64U - -/*! FWT ISO14443A adjustment: - * 512 : 4bit length - * 64 : Half a bit duration due to ST25R3916 Coherent receiver (1/fc) */ -#define RFAL_FWT_A_ADJUSTMENT (512U + 64U) - -/*! FWT ISO14443B adjustment: - * SOF (14etu) + 1Byte (10etu) + 1etu (IRQ comes 1etu after first byte) - 3etu (ST25R3916 sends TXE 3etu after) */ -#define RFAL_FWT_B_ADJUSTMENT ((14U + 10U + 1U - 3U) * 128U) - -/*! FWT FeliCa 212 adjustment: - * 1024 : Length of the two Sync bytes at 212kbps */ -#define RFAL_FWT_F_212_ADJUSTMENT 1024U - -/*! FWT FeliCa 424 adjustment: - * 512 : Length of the two Sync bytes at 424kbps */ -#define RFAL_FWT_F_424_ADJUSTMENT 512U - -/*! Time between our field Off and other peer field On : Tadt + (n x Trfw) - * Ecma 340 11.1.2 - Tadt: [56.64 , 188.72] us ; n: [0 , 3] ; Trfw = 37.76 us - * Should be: 189 + (3*38) = 303us ; we'll use a more relaxed setting: 605 us */ -#define RFAL_AP2P_FIELDON_TADTTRFW rfalConvUsTo1fc(605U) - -/*! FDT Listen adjustment for ISO14443A EMVCo 2.6 4.8.1.3 ; Digital 1.1 6.10 - * - * 276: Time from the rising pulse of the pause of the logic '1' (i.e. the time point to measure the deaftime from), - * to the actual end of the EOF sequence (the point where the MRT starts). Please note that the ST25R391x uses the - * ISO14443-2 definition where the EOF consists of logic '0' followed by sequence Y. - * -64: Further adjustment for receiver to be ready just before first bit - */ -#define RFAL_FDT_LISTEN_A_ADJUSTMENT (276U - 64U) - -/*! FDT Listen adjustment for ISO14443B EMVCo 2.6 4.8.1.6 ; Digital 1.1 7.9 - * - * 340: Time from the rising edge of the EoS to the starting point of the MRT timer (sometime after the final high - * part of the EoS is completed) - */ -#define RFAL_FDT_LISTEN_B_ADJUSTMENT 340U - -/*! FDT Listen adjustment for ISO15693 - * ISO15693 2000 8.4 t1 MIN = 4192/fc - * ISO15693 2009 9.1 t1 MIN = 4320/fc - * Digital 2.1 B.5 FDTV,LISTEN,MIN = 4310/fc - * Set FDT Listen one step earlier than on the more recent spec versions for greater interoperability - */ -#define RFAL_FDT_LISTEN_V_ADJUSTMENT 64U - -/*! FDT Poll adjustment for ISO14443B Correlator - sst 5 etu */ -#define RFAL_FDT_LISTEN_B_ADJT_CORR 128U - -/*! FDT Poll adjustment for ISO14443B Correlator sst window - 5 etu */ -#define RFAL_FDT_LISTEN_B_ADJT_CORR_SST 20U - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ - -/*! Calculates Transceive Sanity Timer. It accounts for the slowest bit rate and the longest data format - * 1s for transmission and reception of a 4K message at 106kpbs (~425ms each direction) - * plus TxRx preparation and FIFO load over Serial Interface */ -#define rfalCalcSanityTmr(fwt) (uint16_t)(1000U + rfalConv1fcToMs((fwt))) - -#define rfalGennTRFW(n) \ - (((n) + 1U) & \ - ST25R3916_REG_AUX_nfc_n_mask) /*!< Generates the next n*TRRW used for RFCA */ - -#define rfalCalcNumBytes(nBits) \ - (((uint32_t)(nBits) + 7U) / \ - 8U) /*!< Returns the number of bytes required to fit given the number of bits */ - -#define rfalTimerStart(timer, time_ms) \ - do { \ - platformTimerDestroy(timer); \ - (timer) = platformTimerCreate((uint16_t)(time_ms)); \ - } while(0) /*!< Configures and starts timer */ -#define rfalTimerisExpired(timer) \ - platformTimerIsExpired( \ - timer) /*!< Checks if timer has expired */ -#define rfalTimerDestroy(timer) \ - platformTimerDestroy( \ - timer) /*!< Destroys timer */ - -#define rfalST25R3916ObsModeDisable() \ - st25r3916WriteTestRegister( \ - 0x01U, \ - (0x40U)) /*!< Disable ST25R3916 Observation mode */ -#define rfalST25R3916ObsModeTx() \ - st25r3916WriteTestRegister( \ - 0x01U, \ - (0x40U | \ - gRFAL.conf \ - .obsvModeTx)) /*!< Enable Tx Observation mode */ -#define rfalST25R3916ObsModeRx() \ - st25r3916WriteTestRegister( \ - 0x01U, \ - (0x40U | \ - gRFAL.conf \ - .obsvModeRx)) /*!< Enable Rx Observation mode */ - -#define rfalCheckDisableObsMode() \ - if(gRFAL.conf.obsvModeRx != 0U) { \ - rfalST25R3916ObsModeDisable(); \ - } /*!< Checks if the observation mode is enabled, and applies on ST25R3916 */ -#define rfalCheckEnableObsModeTx() \ - if(gRFAL.conf.obsvModeTx != 0U) { \ - rfalST25R3916ObsModeTx(); \ - } /*!< Checks if the observation mode is enabled, and applies on ST25R3916 */ -#define rfalCheckEnableObsModeRx() \ - if(gRFAL.conf.obsvModeRx != 0U) { \ - rfalST25R3916ObsModeRx(); \ - } /*!< Checks if the observation mode is enabled, and applies on ST25R3916 */ - -#define rfalGetIncmplBits(FIFOStatus2) \ - (((FIFOStatus2) >> 1) & \ - 0x07U) /*!< Returns the number of bits from fifo status */ -#define rfalIsIncompleteByteError(error) \ - (((error) >= ERR_INCOMPLETE_BYTE) && \ - ((error) <= \ - ERR_INCOMPLETE_BYTE_07)) /*!< Checks if given error is a Incomplete error */ - -#define rfalAdjACBR(b) \ - (((uint16_t)(b) >= (uint16_t)RFAL_BR_52p97) ? \ - (uint16_t)(b) : \ - ((uint16_t)(b) + \ - 1U)) /*!< Adjusts ST25R391x Bit rate to Analog Configuration */ -#define rfalConvBR2ACBR(b) \ - (((rfalAdjACBR((b))) << RFAL_ANALOG_CONFIG_BITRATE_SHIFT) & \ - RFAL_ANALOG_CONFIG_BITRATE_MASK) /*!< Converts ST25R391x Bit rate to Analog Configuration bit rate id */ - -#define rfalConvTDFormat(v) \ - ((uint16_t)(v) << 8U) /*!< Converts a uint8_t to the format used in SW Tag Detection */ - -/* - ****************************************************************************** - * LOCAL VARIABLES - ****************************************************************************** - */ - -static rfal gRFAL; /*!< RFAL module instance */ - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -static void rfalTransceiveTx(void); -static void rfalTransceiveRx(void); -static ReturnCode rfalTransceiveRunBlockingTx(void); -static void rfalPrepareTransceive(void); -static void rfalCleanupTransceive(void); -static void rfalErrorHandling(void); - -static ReturnCode rfalRunTransceiveWorker(void); -#if RFAL_FEATURE_LISTEN_MODE -static ReturnCode rfalRunListenModeWorker(void); -#endif /* RFAL_FEATURE_LISTEN_MODE */ -#if RFAL_FEATURE_WAKEUP_MODE -static void rfalRunWakeUpModeWorker(void); -static uint16_t rfalWakeUpModeFilter(uint16_t curRef, uint16_t curVal, uint8_t weight); -#endif /* RFAL_FEATURE_WAKEUP_MODE */ - -static void rfalFIFOStatusUpdate(void); -static void rfalFIFOStatusClear(void); -static bool rfalFIFOStatusIsMissingPar(void); -static bool rfalFIFOStatusIsIncompleteByte(void); -static uint16_t rfalFIFOStatusGetNumBytes(void); -static uint8_t rfalFIFOGetNumIncompleteBits(void); - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -ReturnCode rfalInitialize(void) { - ReturnCode err; - - EXIT_ON_ERR(err, st25r3916Initialize()); - - st25r3916ClearInterrupts(); - - /* Disable any previous observation mode */ - rfalST25R3916ObsModeDisable(); - - /*******************************************************************************/ - /* Apply RF Chip generic initialization */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_INIT)); - - // TODO: - // I don't want to mess with config table ("Default Analog Configuration for Chip-Specific Reset", rfal_analogConfigTbl.h) - // so with every rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_CHIP_INIT)) currently we need to clear pulldown bits - // luckily for us this is done only here - - // disable pulldowns - st25r3916ClrRegisterBits( - ST25R3916_REG_IO_CONF2, - (ST25R3916_REG_IO_CONF2_miso_pd1 | ST25R3916_REG_IO_CONF2_miso_pd2)); - - /*******************************************************************************/ - /* Enable External Field Detector as: Automatics */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_OP_CONTROL, - ST25R3916_REG_OP_CONTROL_en_fd_mask, - ST25R3916_REG_OP_CONTROL_en_fd_auto_efd); - - /* Clear FIFO status local copy */ - rfalFIFOStatusClear(); - - /*******************************************************************************/ - gRFAL.state = RFAL_STATE_INIT; - gRFAL.mode = RFAL_MODE_NONE; - gRFAL.field = false; - - /* Set RFAL default configs */ - gRFAL.conf.obsvModeRx = RFAL_OBSMODE_DISABLE; - gRFAL.conf.obsvModeTx = RFAL_OBSMODE_DISABLE; - gRFAL.conf.eHandling = RFAL_ERRORHANDLING_NONE; - - /* Transceive set to IDLE */ - gRFAL.TxRx.lastState = RFAL_TXRX_STATE_IDLE; - gRFAL.TxRx.state = RFAL_TXRX_STATE_IDLE; - - /* Disable all timings */ - gRFAL.timings.FDTListen = RFAL_TIMING_NONE; - gRFAL.timings.FDTPoll = RFAL_TIMING_NONE; - gRFAL.timings.GT = RFAL_TIMING_NONE; - gRFAL.timings.nTRFW = 0U; - - /* Destroy any previous pending timers */ - rfalTimerDestroy(gRFAL.tmr.GT); - rfalTimerDestroy(gRFAL.tmr.txRx); - rfalTimerDestroy(gRFAL.tmr.RXE); - gRFAL.tmr.GT = RFAL_TIMING_NONE; - gRFAL.tmr.txRx = RFAL_TIMING_NONE; - gRFAL.tmr.RXE = RFAL_TIMING_NONE; - - gRFAL.callbacks.preTxRx = NULL; - gRFAL.callbacks.postTxRx = NULL; - gRFAL.callbacks.state_changed_cb = NULL; - gRFAL.callbacks.ctx = NULL; - -#if RFAL_FEATURE_NFCV - /* Initialize NFC-V Data */ - gRFAL.nfcvData.ignoreBits = 0; -#endif /* RFAL_FEATURE_NFCV */ - -#if RFAL_FEATURE_LISTEN_MODE - /* Initialize Listen Mode */ - gRFAL.Lm.state = RFAL_LM_STATE_NOT_INIT; - gRFAL.Lm.brDetected = RFAL_BR_KEEP; - gRFAL.Lm.iniFlag = false; -#endif /* RFAL_FEATURE_LISTEN_MODE */ - -#if RFAL_FEATURE_WAKEUP_MODE - /* Initialize Wake-Up Mode */ - gRFAL.wum.state = RFAL_WUM_STATE_NOT_INIT; -#endif /* RFAL_FEATURE_WAKEUP_MODE */ - -#if RFAL_FEATURE_LOWPOWER_MODE - /* Initialize Low Power Mode */ - gRFAL.lpm.isRunning = false; -#endif /* RFAL_FEATURE_LOWPOWER_MODE */ - - /*******************************************************************************/ - /* Perform Automatic Calibration (if configured to do so). * - * Registers set by rfalSetAnalogConfig will tell rfalCalibrate what to perform*/ - rfalCalibrate(); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalCalibrate(void) { - uint16_t resValue; - - /* Check if RFAL is not initialized */ - if(gRFAL.state == RFAL_STATE_IDLE) { - return ERR_WRONG_STATE; - } - - /*******************************************************************************/ - /* Perform ST25R3916 regulators and antenna calibration */ - /*******************************************************************************/ - - /* Automatic regulator adjustment only performed if not set manually on Analog Configs */ - if(st25r3916CheckReg( - ST25R3916_REG_REGULATOR_CONTROL, ST25R3916_REG_REGULATOR_CONTROL_reg_s, 0x00)) { - /* Adjust the regulators so that Antenna Calibrate has better Regulator values */ - st25r3916AdjustRegulators(&resValue); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalAdjustRegulators(uint16_t* result) { - return st25r3916AdjustRegulators(result); -} - -/*******************************************************************************/ -void rfalSetUpperLayerCallback(rfalUpperLayerCallback pFunc) { - st25r3916IRQCallbackSet(pFunc); -} - -/*******************************************************************************/ -void rfalSetPreTxRxCallback(rfalPreTxRxCallback pFunc) { - gRFAL.callbacks.preTxRx = pFunc; -} - -/*******************************************************************************/ -void rfalSetPostTxRxCallback(rfalPostTxRxCallback pFunc) { - gRFAL.callbacks.postTxRx = pFunc; -} - -void rfal_set_state_changed_callback(RfalStateChangedCallback callback) { - gRFAL.callbacks.state_changed_cb = callback; -} - -void rfal_set_callback_context(void* context) { - gRFAL.callbacks.ctx = context; -} - -/*******************************************************************************/ -ReturnCode rfalDeinitialize(void) { - /* Deinitialize chip */ - st25r3916Deinitialize(); - - /* Set Analog configurations for deinitialization */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_DEINIT)); - - gRFAL.state = RFAL_STATE_IDLE; - return ERR_NONE; -} - -/*******************************************************************************/ -void rfalSetObsvMode(uint8_t txMode, uint8_t rxMode) { - gRFAL.conf.obsvModeTx = txMode; - gRFAL.conf.obsvModeRx = rxMode; -} - -/*******************************************************************************/ -void rfalGetObsvMode(uint8_t* txMode, uint8_t* rxMode) { - if(txMode != NULL) { - *txMode = gRFAL.conf.obsvModeTx; - } - - if(rxMode != NULL) { - *rxMode = gRFAL.conf.obsvModeRx; - } -} - -/*******************************************************************************/ -void rfalDisableObsvMode(void) { - gRFAL.conf.obsvModeTx = RFAL_OBSMODE_DISABLE; - gRFAL.conf.obsvModeRx = RFAL_OBSMODE_DISABLE; -} - -/*******************************************************************************/ -ReturnCode rfalSetMode(rfalMode mode, rfalBitRate txBR, rfalBitRate rxBR) { - /* Check if RFAL is not initialized */ - if(gRFAL.state == RFAL_STATE_IDLE) { - return ERR_WRONG_STATE; - } - - /* Check allowed bit rate value */ - if((txBR == RFAL_BR_KEEP) || (rxBR == RFAL_BR_KEEP)) { - return ERR_PARAM; - } - - switch(mode) { - /*******************************************************************************/ - case RFAL_MODE_POLL_NFCA: - - /* Disable wake up mode, if set */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - - /* Enable ISO14443A mode */ - st25r3916WriteRegister(ST25R3916_REG_MODE, ST25R3916_REG_MODE_om_iso14443a); - - /* Set Analog configurations for this mode and bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_POLL_NFCA_T1T: - /* Disable wake up mode, if set */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - - /* Enable Topaz mode */ - st25r3916WriteRegister(ST25R3916_REG_MODE, ST25R3916_REG_MODE_om_topaz); - - /* Set Analog configurations for this mode and bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_POLL_NFCB: - - /* Disable wake up mode, if set */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - - /* Enable ISO14443B mode */ - st25r3916WriteRegister(ST25R3916_REG_MODE, ST25R3916_REG_MODE_om_iso14443b); - - /* Set the EGT, SOF, EOF and EOF */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_ISO14443B_1, - (ST25R3916_REG_ISO14443B_1_egt_mask | ST25R3916_REG_ISO14443B_1_sof_mask | - ST25R3916_REG_ISO14443B_1_eof), - ((0U << ST25R3916_REG_ISO14443B_1_egt_shift) | ST25R3916_REG_ISO14443B_1_sof_0_10etu | - ST25R3916_REG_ISO14443B_1_sof_1_2etu | ST25R3916_REG_ISO14443B_1_eof_10etu)); - - /* Set the minimum TR1, SOF, EOF and EOF12 */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_ISO14443B_2, - (ST25R3916_REG_ISO14443B_2_tr1_mask | ST25R3916_REG_ISO14443B_2_no_sof | - ST25R3916_REG_ISO14443B_2_no_eof), - (ST25R3916_REG_ISO14443B_2_tr1_80fs80fs)); - - /* Set Analog configurations for this mode and bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_POLL_B_PRIME: - - /* Disable wake up mode, if set */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - - /* Enable ISO14443B mode */ - st25r3916WriteRegister(ST25R3916_REG_MODE, ST25R3916_REG_MODE_om_iso14443b); - - /* Set the EGT, SOF, EOF and EOF */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_ISO14443B_1, - (ST25R3916_REG_ISO14443B_1_egt_mask | ST25R3916_REG_ISO14443B_1_sof_mask | - ST25R3916_REG_ISO14443B_1_eof), - ((0U << ST25R3916_REG_ISO14443B_1_egt_shift) | ST25R3916_REG_ISO14443B_1_sof_0_10etu | - ST25R3916_REG_ISO14443B_1_sof_1_2etu | ST25R3916_REG_ISO14443B_1_eof_10etu)); - - /* Set the minimum TR1, EOF and EOF12 */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_ISO14443B_2, - (ST25R3916_REG_ISO14443B_2_tr1_mask | ST25R3916_REG_ISO14443B_2_no_sof | - ST25R3916_REG_ISO14443B_2_no_eof), - (ST25R3916_REG_ISO14443B_2_tr1_80fs80fs | ST25R3916_REG_ISO14443B_2_no_sof)); - - /* Set Analog configurations for this mode and bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_POLL_B_CTS: - - /* Disable wake up mode, if set */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - - /* Enable ISO14443B mode */ - st25r3916WriteRegister(ST25R3916_REG_MODE, ST25R3916_REG_MODE_om_iso14443b); - - /* Set the EGT, SOF, EOF and EOF */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_ISO14443B_1, - (ST25R3916_REG_ISO14443B_1_egt_mask | ST25R3916_REG_ISO14443B_1_sof_mask | - ST25R3916_REG_ISO14443B_1_eof), - ((0U << ST25R3916_REG_ISO14443B_1_egt_shift) | ST25R3916_REG_ISO14443B_1_sof_0_10etu | - ST25R3916_REG_ISO14443B_1_sof_1_2etu | ST25R3916_REG_ISO14443B_1_eof_10etu)); - - /* Set the minimum TR1, clear SOF, EOF and EOF12 */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_ISO14443B_2, - (ST25R3916_REG_ISO14443B_2_tr1_mask | ST25R3916_REG_ISO14443B_2_no_sof | - ST25R3916_REG_ISO14443B_2_no_eof), - (ST25R3916_REG_ISO14443B_2_tr1_80fs80fs | ST25R3916_REG_ISO14443B_2_no_sof | - ST25R3916_REG_ISO14443B_2_no_eof)); - - /* Set Analog configurations for this mode and bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_POLL_NFCF: - - /* Disable wake up mode, if set */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - - /* Enable FeliCa mode */ - st25r3916WriteRegister(ST25R3916_REG_MODE, ST25R3916_REG_MODE_om_felica); - - /* Set Analog configurations for this mode and bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCF | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCF | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_POLL_NFCV: - case RFAL_MODE_POLL_PICOPASS: - -#if !RFAL_FEATURE_NFCV - return ERR_DISABLED; -#else - - /* Disable wake up mode, if set */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - - /* Set Analog configurations for this mode and bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - -#endif /* RFAL_FEATURE_NFCV */ - - /*******************************************************************************/ - case RFAL_MODE_POLL_ACTIVE_P2P: - - /* Set NFCIP1 active communication Initiator mode and Automatic Response RF Collision Avoidance to always after EOF */ - st25r3916WriteRegister( - ST25R3916_REG_MODE, - (ST25R3916_REG_MODE_targ_init | ST25R3916_REG_MODE_om_nfc | - ST25R3916_REG_MODE_nfc_ar_eof)); - - /* External Field Detector enabled as Automatics on rfalInitialize() */ - - /* Set NRT to start at end of TX (own) field */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, - ST25R3916_REG_TIMER_EMV_CONTROL_nrt_nfc, - ST25R3916_REG_TIMER_EMV_CONTROL_nrt_nfc_off); - - /* Set GPT to start after end of TX, as GPT is used in active communication mode to timeout the field switching off */ - /* The field is turned off 37.76us after the end of the transmission Trfw */ - st25r3916SetStartGPTimer( - (uint16_t)rfalConv1fcTo8fc(RFAL_AP2P_FIELDOFF_TRFW), - ST25R3916_REG_TIMER_EMV_CONTROL_gptc_etx_nfc); - - /* Set PPon2 timer with the max time between our field Off and other peer field On : Tadt + (n x Trfw) */ - st25r3916WriteRegister( - ST25R3916_REG_PPON2, (uint8_t)rfalConv1fcTo64fc(RFAL_AP2P_FIELDON_TADTTRFW)); - - /* Set Analog configurations for this mode and bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_LISTEN_ACTIVE_P2P: - - /* Set NFCIP1 active communication Target mode and Automatic Response RF Collision Avoidance to always after EOF */ - st25r3916WriteRegister( - ST25R3916_REG_MODE, - (ST25R3916_REG_MODE_targ_targ | ST25R3916_REG_MODE_om_targ_nfcip | - ST25R3916_REG_MODE_nfc_ar_eof)); - - /* Set TARFG: 0 (75us+0ms=75us), as Target no Guard time needed */ - st25r3916WriteRegister(ST25R3916_REG_FIELD_ON_GT, 0U); - - /* External Field Detector enabled as Automatics on rfalInitialize() */ - - /* Set NRT to start at end of TX (own) field */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, - ST25R3916_REG_TIMER_EMV_CONTROL_nrt_nfc, - ST25R3916_REG_TIMER_EMV_CONTROL_nrt_nfc_off); - - /* Set GPT to start after end of TX, as GPT is used in active communication mode to timeout the field switching off */ - /* The field is turned off 37.76us after the end of the transmission Trfw */ - st25r3916SetStartGPTimer( - (uint16_t)rfalConv1fcTo8fc(RFAL_AP2P_FIELDOFF_TRFW), - ST25R3916_REG_TIMER_EMV_CONTROL_gptc_etx_nfc); - - /* Set PPon2 timer with the max time between our field Off and other peer field On : Tadt + (n x Trfw) */ - st25r3916WriteRegister( - ST25R3916_REG_PPON2, (uint8_t)rfalConv1fcTo64fc(RFAL_AP2P_FIELDON_TADTTRFW)); - - /* Set Analog configurations for this mode and bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_LISTEN_NFCA: - - /* Disable wake up mode, if set */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - - /* Enable Passive Target NFC-A mode, disable any Collision Avoidance */ - st25r3916WriteRegister( - ST25R3916_REG_MODE, - (ST25R3916_REG_MODE_targ | ST25R3916_REG_MODE_om_targ_nfca | - ST25R3916_REG_MODE_nfc_ar_off)); - - /* Set Analog configurations for this mode */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_LISTEN_NFCF: - - /* Disable wake up mode, if set */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - - /* Enable Passive Target NFC-F mode, disable any Collision Avoidance */ - st25r3916WriteRegister( - ST25R3916_REG_MODE, - (ST25R3916_REG_MODE_targ | ST25R3916_REG_MODE_om_targ_nfcf | - ST25R3916_REG_MODE_nfc_ar_off)); - - /* Set Analog configurations for this mode */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_NFCF | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_NFCF | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_RX)); - break; - - /*******************************************************************************/ - case RFAL_MODE_LISTEN_NFCB: - return ERR_NOTSUPP; - - /*******************************************************************************/ - default: - return ERR_NOT_IMPLEMENTED; - } - - /* Set state as STATE_MODE_SET only if not initialized yet (PSL) */ - gRFAL.state = ((gRFAL.state < RFAL_STATE_MODE_SET) ? RFAL_STATE_MODE_SET : gRFAL.state); - gRFAL.mode = mode; - - /* Apply the given bit rate */ - return rfalSetBitRate(txBR, rxBR); -} - -/*******************************************************************************/ -rfalMode rfalGetMode(void) { - return gRFAL.mode; -} - -/*******************************************************************************/ -ReturnCode rfalSetBitRate(rfalBitRate txBR, rfalBitRate rxBR) { - ReturnCode ret; - - /* Check if RFAL is not initialized */ - if(gRFAL.state == RFAL_STATE_IDLE) { - return ERR_WRONG_STATE; - } - - /* Store the new Bit Rates */ - gRFAL.txBR = ((txBR == RFAL_BR_KEEP) ? gRFAL.txBR : txBR); - gRFAL.rxBR = ((rxBR == RFAL_BR_KEEP) ? gRFAL.rxBR : rxBR); - - /* Update the bitrate reg if not in NFCV mode (streaming) */ - if((RFAL_MODE_POLL_NFCV != gRFAL.mode) && (RFAL_MODE_POLL_PICOPASS != gRFAL.mode)) { - /* Set bit rate register */ - EXIT_ON_ERR(ret, st25r3916SetBitrate((uint8_t)gRFAL.txBR, (uint8_t)gRFAL.rxBR)); - } - - switch(gRFAL.mode) { - /*******************************************************************************/ - case RFAL_MODE_POLL_NFCA: - case RFAL_MODE_POLL_NFCA_T1T: - - /* Set Analog configurations for this bit rate */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_POLL_COMMON)); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | rfalConvBR2ACBR(gRFAL.txBR) | RFAL_ANALOG_CONFIG_TX ) ); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | rfalConvBR2ACBR(gRFAL.rxBR) | RFAL_ANALOG_CONFIG_RX ) ); - break; - - /*******************************************************************************/ - case RFAL_MODE_POLL_NFCB: - case RFAL_MODE_POLL_B_PRIME: - case RFAL_MODE_POLL_B_CTS: - - /* Set Analog configurations for this bit rate */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_POLL_COMMON)); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | rfalConvBR2ACBR(gRFAL.txBR) | RFAL_ANALOG_CONFIG_TX ) ); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCB | rfalConvBR2ACBR(gRFAL.rxBR) | RFAL_ANALOG_CONFIG_RX ) ); - break; - - /*******************************************************************************/ - case RFAL_MODE_POLL_NFCF: - - /* Set Analog configurations for this bit rate */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_POLL_COMMON)); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCF | rfalConvBR2ACBR(gRFAL.txBR) | RFAL_ANALOG_CONFIG_TX ) ); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCF | rfalConvBR2ACBR(gRFAL.rxBR) | RFAL_ANALOG_CONFIG_RX ) ); - break; - - /*******************************************************************************/ - case RFAL_MODE_POLL_NFCV: - case RFAL_MODE_POLL_PICOPASS: - -#if !RFAL_FEATURE_NFCV - return ERR_DISABLED; -#else - - if(((gRFAL.rxBR != RFAL_BR_26p48) && (gRFAL.rxBR != RFAL_BR_52p97)) || - ((gRFAL.txBR != RFAL_BR_1p66) && (gRFAL.txBR != RFAL_BR_26p48))) { - return ERR_PARAM; - } - - { - const struct iso15693StreamConfig* isoStreamConfig; - struct st25r3916StreamConfig streamConf; - iso15693PhyConfig_t config; - - config.coding = - ((gRFAL.txBR == RFAL_BR_1p66) ? ISO15693_VCD_CODING_1_256 : - ISO15693_VCD_CODING_1_4); - switch(gRFAL.rxBR) { - case RFAL_BR_52p97: - config.speedMode = 1; - break; - default: - config.speedMode = 0; - break; - } - - iso15693PhyConfigure(&config, &isoStreamConfig); - - /* MISRA 11.3 - Cannot point directly into different object type, copy to local var */ - streamConf.din = isoStreamConfig->din; - streamConf.dout = isoStreamConfig->dout; - streamConf.report_period_length = isoStreamConfig->report_period_length; - streamConf.useBPSK = isoStreamConfig->useBPSK; - st25r3916StreamConfigure(&streamConf); - } - - /* Set Analog configurations for this bit rate */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_POLL_COMMON)); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | rfalConvBR2ACBR(gRFAL.txBR) | RFAL_ANALOG_CONFIG_TX ) ); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | rfalConvBR2ACBR(gRFAL.rxBR) | RFAL_ANALOG_CONFIG_RX ) ); - break; - -#endif /* RFAL_FEATURE_NFCV */ - - /*******************************************************************************/ - case RFAL_MODE_POLL_ACTIVE_P2P: - - /* Set Analog configurations for this bit rate */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_POLL_COMMON)); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | rfalConvBR2ACBR(gRFAL.txBR) | RFAL_ANALOG_CONFIG_TX ) ); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_AP2P | rfalConvBR2ACBR(gRFAL.rxBR) | RFAL_ANALOG_CONFIG_RX ) ); - break; - - /*******************************************************************************/ - case RFAL_MODE_LISTEN_ACTIVE_P2P: - - /* Set Analog configurations for this bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_LISTEN_COMMON)); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | rfalConvBR2ACBR(gRFAL.txBR) | RFAL_ANALOG_CONFIG_TX ) ); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_AP2P | rfalConvBR2ACBR(gRFAL.rxBR) | RFAL_ANALOG_CONFIG_RX ) ); - break; - - /*******************************************************************************/ - case RFAL_MODE_LISTEN_NFCA: - - /* Set Analog configurations for this bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_LISTEN_COMMON)); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_NFCA | rfalConvBR2ACBR(gRFAL.txBR) | RFAL_ANALOG_CONFIG_TX ) ); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_NFCA | rfalConvBR2ACBR(gRFAL.rxBR) | RFAL_ANALOG_CONFIG_RX ) ); - break; - - /*******************************************************************************/ - case RFAL_MODE_LISTEN_NFCF: - - /* Set Analog configurations for this bit rate */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_LISTEN_COMMON)); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_NFCF | rfalConvBR2ACBR(gRFAL.txBR) | RFAL_ANALOG_CONFIG_TX ) ); - rfalSetAnalogConfig( (rfalAnalogConfigId)(RFAL_ANALOG_CONFIG_LISTEN | RFAL_ANALOG_CONFIG_TECH_NFCF | rfalConvBR2ACBR(gRFAL.rxBR) | RFAL_ANALOG_CONFIG_RX ) ); - break; - - /*******************************************************************************/ - case RFAL_MODE_LISTEN_NFCB: - case RFAL_MODE_NONE: - return ERR_WRONG_STATE; - - /*******************************************************************************/ - default: - return ERR_NOT_IMPLEMENTED; - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalGetBitRate(rfalBitRate* txBR, rfalBitRate* rxBR) { - if((gRFAL.state == RFAL_STATE_IDLE) || (gRFAL.mode == RFAL_MODE_NONE)) { - return ERR_WRONG_STATE; - } - - if(txBR != NULL) { - *txBR = gRFAL.txBR; - } - - if(rxBR != NULL) { - *rxBR = gRFAL.rxBR; - } - - return ERR_NONE; -} - -/*******************************************************************************/ -void rfalSetErrorHandling(rfalEHandling eHandling) { - switch(eHandling) { - case RFAL_ERRORHANDLING_NFC: - case RFAL_ERRORHANDLING_NONE: - st25r3916ClrRegisterBits(ST25R3916_REG_EMD_SUP_CONF, ST25R3916_REG_EMD_SUP_CONF_emd_emv); - break; - - case RFAL_ERRORHANDLING_EMVCO: - /* MISRA 16.4: no empty default statement (in case RFAL_SW_EMD is defined) */ -#ifndef RFAL_SW_EMD - st25r3916ModifyRegister( - ST25R3916_REG_EMD_SUP_CONF, - (ST25R3916_REG_EMD_SUP_CONF_emd_emv | ST25R3916_REG_EMD_SUP_CONF_emd_thld_mask), - (ST25R3916_REG_EMD_SUP_CONF_emd_emv_on | RFAL_EMVCO_RX_MAXLEN)); -#endif /* RFAL_SW_EMD */ - break; - default: - /* MISRA 16.4: no empty default statement (a comment being enough) */ - break; - } - - gRFAL.conf.eHandling = eHandling; -} - -/*******************************************************************************/ -rfalEHandling rfalGetErrorHandling(void) { - return gRFAL.conf.eHandling; -} - -/*******************************************************************************/ -void rfalSetFDTPoll(uint32_t FDTPoll) { - gRFAL.timings.FDTPoll = MIN(FDTPoll, RFAL_ST25R3916_GPT_MAX_1FC); -} - -/*******************************************************************************/ -uint32_t rfalGetFDTPoll(void) { - return gRFAL.timings.FDTPoll; -} - -/*******************************************************************************/ -void rfalSetFDTListen(uint32_t FDTListen) { - gRFAL.timings.FDTListen = MIN(FDTListen, RFAL_ST25R3916_MRT_MAX_1FC); -} - -/*******************************************************************************/ -uint32_t rfalGetFDTListen(void) { - return gRFAL.timings.FDTListen; -} - -/*******************************************************************************/ -void rfalSetGT(uint32_t GT) { - gRFAL.timings.GT = MIN(GT, RFAL_ST25R3916_GT_MAX_1FC); -} - -/*******************************************************************************/ -uint32_t rfalGetGT(void) { - return gRFAL.timings.GT; -} - -/*******************************************************************************/ -bool rfalIsGTExpired(void) { - if(gRFAL.tmr.GT != RFAL_TIMING_NONE) { - if(!rfalTimerisExpired(gRFAL.tmr.GT)) { - return false; - } - } - return true; -} - -/*******************************************************************************/ -ReturnCode rfalFieldOnAndStartGT(void) { - ReturnCode ret; - - /* Check if RFAL has been initialized (Oscillator should be running) and also - * if a direct register access has been performed and left the Oscillator Off */ - if(!st25r3916IsOscOn() || (gRFAL.state < RFAL_STATE_INIT)) { - return ERR_WRONG_STATE; - } - - ret = ERR_NONE; - - /* Set Analog configurations for Field On event */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_FIELD_ON)); - - /*******************************************************************************/ - /* Perform collision avoidance and turn field On if not already On */ - if(!st25r3916IsTxEnabled() || !gRFAL.field) { - /* Set TARFG: 0 (75us+0ms=75us), GT is fulfilled using a SW timer */ - st25r3916WriteRegister(ST25R3916_REG_FIELD_ON_GT, 0U); - - /* Use Thresholds set by AnalogConfig */ - ret = st25r3916PerformCollisionAvoidance( - ST25R3916_CMD_INITIAL_RF_COLLISION, - ST25R3916_THRESHOLD_DO_NOT_SET, - ST25R3916_THRESHOLD_DO_NOT_SET, - gRFAL.timings.nTRFW); - - /* n * TRFW timing shall vary Activity 2.1 3.3.1.1 */ - gRFAL.timings.nTRFW = rfalGennTRFW(gRFAL.timings.nTRFW); - - gRFAL.field = st25r3916IsTxEnabled(); //(ret == ERR_NONE); - - /* Only turn on Receiver and Transmitter if field was successfully turned On */ - if(gRFAL.field) { - st25r3916TxRxOn(); /* Enable Tx and Rx (Tx is already On)*/ - } - } - - /*******************************************************************************/ - /* Start GT timer in case the GT value is set */ - if((gRFAL.timings.GT != RFAL_TIMING_NONE)) { - /* Ensure that a SW timer doesn't have a lower value then the minimum */ - rfalTimerStart( - gRFAL.tmr.GT, rfalConv1fcToMs(MAX((gRFAL.timings.GT), RFAL_ST25R3916_GT_MIN_1FC))); - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalFieldOff(void) { - /* Check whether a TxRx is not yet finished */ - if(gRFAL.TxRx.state != RFAL_TXRX_STATE_IDLE) { - rfalCleanupTransceive(); - } - - /* Disable Tx and Rx */ - st25r3916TxRxOff(); - - /* Set Analog configurations for Field Off event */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_FIELD_OFF)); - gRFAL.field = false; - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalStartTransceive(const rfalTransceiveContext* ctx) { - uint32_t FxTAdj; /* FWT or FDT adjustment calculation */ - - /* Check for valid parameters */ - if(ctx == NULL) { - return ERR_PARAM; - } - - /* Ensure that RFAL is already Initialized and the mode has been set */ - if((gRFAL.state >= RFAL_STATE_MODE_SET) /*&& (gRFAL.TxRx.state == RFAL_TXRX_STATE_INIT )*/) { - /*******************************************************************************/ - /* Check whether the field is already On, otherwise no TXE will be received */ - if(!st25r3916IsTxEnabled() && - (!rfalIsModePassiveListen(gRFAL.mode) && (ctx->txBuf != NULL))) { - return ERR_WRONG_STATE; - } - - gRFAL.TxRx.ctx = *ctx; - - /*******************************************************************************/ - if(gRFAL.timings.FDTListen != RFAL_TIMING_NONE) { - /* Calculate MRT adjustment accordingly to the current mode */ - FxTAdj = RFAL_FDT_LISTEN_MRT_ADJUSTMENT; - if(gRFAL.mode == RFAL_MODE_POLL_NFCA) { - FxTAdj += (uint32_t)RFAL_FDT_LISTEN_A_ADJUSTMENT; - } - if(gRFAL.mode == RFAL_MODE_POLL_NFCA_T1T) { - FxTAdj += (uint32_t)RFAL_FDT_LISTEN_A_ADJUSTMENT; - } - if(gRFAL.mode == RFAL_MODE_POLL_NFCB) { - FxTAdj += (uint32_t)RFAL_FDT_LISTEN_B_ADJUSTMENT; - } - if(gRFAL.mode == RFAL_MODE_POLL_NFCV) { - FxTAdj += (uint32_t)RFAL_FDT_LISTEN_V_ADJUSTMENT; - } - - /* Ensure that MRT is using 64/fc steps */ - st25r3916ClrRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, ST25R3916_REG_TIMER_EMV_CONTROL_mrt_step); - - /* If Correlator is being used further adjustment is required for NFCB */ - if((st25r3916CheckReg(ST25R3916_REG_AUX, ST25R3916_REG_AUX_dis_corr, 0x00U)) && - (gRFAL.mode == RFAL_MODE_POLL_NFCB)) { - FxTAdj += (uint32_t) - RFAL_FDT_LISTEN_B_ADJT_CORR; /* Reduce FDT(Listen) */ - st25r3916SetRegisterBits( - ST25R3916_REG_CORR_CONF1, - ST25R3916_REG_CORR_CONF1_corr_s3); /* Ensure BPSK start to 33 pilot pulses */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_SUBC_START_TIME, - ST25R3916_REG_SUBC_START_TIME_sst_mask, - RFAL_FDT_LISTEN_B_ADJT_CORR_SST); /* Set sst */ - } - - /* Set Minimum FDT(Listen) in which PICC is not allowed to send a response */ - st25r3916WriteRegister( - ST25R3916_REG_MASK_RX_TIMER, - (uint8_t)rfalConv1fcTo64fc( - (FxTAdj > gRFAL.timings.FDTListen) ? RFAL_ST25R3916_MRT_MIN_1FC : - (gRFAL.timings.FDTListen - FxTAdj))); - } - - /*******************************************************************************/ - /* FDT Poll will be loaded in rfalPrepareTransceive() once the previous was expired */ - - /*******************************************************************************/ - if((gRFAL.TxRx.ctx.fwt != RFAL_FWT_NONE) && (gRFAL.TxRx.ctx.fwt != 0U)) { - /* Ensure proper timing configuration */ - if(gRFAL.timings.FDTListen >= gRFAL.TxRx.ctx.fwt) { - return ERR_PARAM; - } - - FxTAdj = RFAL_FWT_ADJUSTMENT; - if(gRFAL.mode == RFAL_MODE_POLL_NFCA) { - FxTAdj += (uint32_t)RFAL_FWT_A_ADJUSTMENT; - } - if(gRFAL.mode == RFAL_MODE_POLL_NFCA_T1T) { - FxTAdj += (uint32_t)RFAL_FWT_A_ADJUSTMENT; - } - if(gRFAL.mode == RFAL_MODE_POLL_NFCB) { - FxTAdj += (uint32_t)RFAL_FWT_B_ADJUSTMENT; - } - if((gRFAL.mode == RFAL_MODE_POLL_NFCF) || (gRFAL.mode == RFAL_MODE_POLL_ACTIVE_P2P)) { - FxTAdj += - (uint32_t)((gRFAL.txBR == RFAL_BR_212) ? RFAL_FWT_F_212_ADJUSTMENT : RFAL_FWT_F_424_ADJUSTMENT); - } - - /* Ensure that the given FWT doesn't exceed NRT maximum */ - gRFAL.TxRx.ctx.fwt = MIN((gRFAL.TxRx.ctx.fwt + FxTAdj), RFAL_ST25R3916_NRT_MAX_1FC); - - /* Set FWT in the NRT */ - st25r3916SetNoResponseTime(rfalConv1fcTo64fc(gRFAL.TxRx.ctx.fwt)); - } else { - /* Disable NRT, no NRE will be triggered, therefore wait endlessly for Rx */ - st25r3916SetNoResponseTime(RFAL_ST25R3916_NRT_DISABLED); - } - - gRFAL.state = RFAL_STATE_TXRX; - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_IDLE; - gRFAL.TxRx.status = ERR_BUSY; - -#if RFAL_FEATURE_NFCV - /*******************************************************************************/ - if((RFAL_MODE_POLL_NFCV == gRFAL.mode) || - (RFAL_MODE_POLL_PICOPASS == - gRFAL.mode)) { /* Exchange receive buffer with internal buffer */ - gRFAL.nfcvData.origCtx = gRFAL.TxRx.ctx; - - gRFAL.TxRx.ctx.rxBuf = - ((gRFAL.nfcvData.origCtx.rxBuf != NULL) ? gRFAL.nfcvData.codingBuffer : NULL); - gRFAL.TxRx.ctx.rxBufLen = - (uint16_t)rfalConvBytesToBits(sizeof(gRFAL.nfcvData.codingBuffer)); - gRFAL.TxRx.ctx.flags = - (uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP | - (uint32_t)RFAL_TXRX_FLAGS_NFCIP1_OFF | - (uint32_t)(gRFAL.nfcvData.origCtx.flags & (uint32_t)RFAL_TXRX_FLAGS_AGC_OFF) | - (uint32_t)RFAL_TXRX_FLAGS_PAR_RX_KEEP | (uint32_t)RFAL_TXRX_FLAGS_PAR_TX_NONE; - - /* In NFCV a TxRx with a valid txBuf and txBufSize==0 indicates to send an EOF */ - /* Skip logic below that would go directly into receive */ - if(gRFAL.TxRx.ctx.txBuf != NULL) { - return ERR_NONE; - } - } -#endif /* RFAL_FEATURE_NFCV */ - - /*******************************************************************************/ - /* Check if the Transceive start performing Tx or goes directly to Rx */ - if((gRFAL.TxRx.ctx.txBuf == NULL) || (gRFAL.TxRx.ctx.txBufLen == 0U)) { - /* Clear FIFO, Clear and Enable the Interrupts */ - rfalPrepareTransceive(); - - /* In AP2P check the field status */ - if(rfalIsModeActiveComm(gRFAL.mode)) { - /* Disable our field upon a Rx reEnable, and start PPON2 manually */ - st25r3916TxOff(); - st25r3916ExecuteCommand(ST25R3916_CMD_START_PPON2_TIMER); - } - - /* No Tx done, enable the Receiver */ - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - - /* Start NRT manually, if FWT = 0 (wait endlessly for Rx) chip will ignore anyhow */ - st25r3916ExecuteCommand(ST25R3916_CMD_START_NO_RESPONSE_TIMER); - - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_IDLE; - } - - return ERR_NONE; - } - - return ERR_WRONG_STATE; -} - -/*******************************************************************************/ -bool rfalIsTransceiveInTx(void) { - return ( - (gRFAL.TxRx.state >= RFAL_TXRX_STATE_TX_IDLE) && - (gRFAL.TxRx.state < RFAL_TXRX_STATE_RX_IDLE)); -} - -/*******************************************************************************/ -bool rfalIsTransceiveInRx(void) { - return (gRFAL.TxRx.state >= RFAL_TXRX_STATE_RX_IDLE); -} - -/*******************************************************************************/ -ReturnCode rfalTransceiveBlockingTx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt) { - ReturnCode ret; - rfalTransceiveContext ctx; - - rfalCreateByteFlagsTxRxContext(ctx, txBuf, txBufLen, rxBuf, rxBufLen, actLen, flags, fwt); - EXIT_ON_ERR(ret, rfalStartTransceive(&ctx)); - - return rfalTransceiveRunBlockingTx(); -} - -ReturnCode rfalTransceiveBitsBlockingTx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt) { - ReturnCode ret; - rfalTransceiveContext ctx = { - .rxBuf = rxBuf, - .rxBufLen = rxBufLen, - .rxRcvdLen = actLen, - .txBuf = txBuf, - .txBufLen = txBufLen, - .flags = flags, - .fwt = fwt, - }; - - EXIT_ON_ERR(ret, rfalStartTransceive(&ctx)); - - return rfalTransceiveRunBlockingTx(); -} - -/*******************************************************************************/ -static ReturnCode rfalTransceiveRunBlockingTx(void) { - ReturnCode ret; - - do { - rfalWorker(); - ret = rfalGetTransceiveStatus(); - } while(rfalIsTransceiveInTx() && (ret == ERR_BUSY)); - - if(rfalIsTransceiveInRx()) { - return ERR_NONE; - } - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalTransceiveBlockingRx(void) { - ReturnCode ret; - - do { - rfalWorker(); - ret = rfalGetTransceiveStatus(); - } while(rfalIsTransceiveInRx() && (ret == ERR_BUSY)); - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalTransceiveBlockingTxRx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt) { - ReturnCode ret; - - EXIT_ON_ERR( - ret, rfalTransceiveBlockingTx(txBuf, txBufLen, rxBuf, rxBufLen, actLen, flags, fwt)); - ret = rfalTransceiveBlockingRx(); - - /* Convert received bits to bytes */ - if(actLen != NULL) { - *actLen = rfalConvBitsToBytes(*actLen); - } - - return ret; -} - -ReturnCode rfalTransceiveBitsBlockingTxRx( - uint8_t* txBuf, - uint16_t txBufLen, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* actLen, - uint32_t flags, - uint32_t fwt) { - ReturnCode ret; - - EXIT_ON_ERR( - ret, rfalTransceiveBitsBlockingTx(txBuf, txBufLen, rxBuf, rxBufLen, actLen, flags, fwt)); - ret = rfalTransceiveBlockingRx(); - - return ret; -} - -/*******************************************************************************/ -static ReturnCode rfalRunTransceiveWorker(void) { - if(gRFAL.state == RFAL_STATE_TXRX) { - /*******************************************************************************/ - /* Check Transceive Sanity Timer has expired */ - if(gRFAL.tmr.txRx != RFAL_TIMING_NONE) { - if(rfalTimerisExpired(gRFAL.tmr.txRx)) { - /* If sanity timer has expired abort ongoing transceive and signal error */ - gRFAL.TxRx.status = ERR_IO; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - } - } - - /*******************************************************************************/ - /* Run Tx or Rx state machines */ - if(rfalIsTransceiveInTx()) { - rfalTransceiveTx(); - return rfalGetTransceiveStatus(); - } - if(rfalIsTransceiveInRx()) { - rfalTransceiveRx(); - return rfalGetTransceiveStatus(); - } - } - return ERR_WRONG_STATE; -} - -/*******************************************************************************/ -rfalTransceiveState rfalGetTransceiveState(void) { - return gRFAL.TxRx.state; -} - -/*******************************************************************************/ -ReturnCode rfalGetTransceiveStatus(void) { - return ((gRFAL.TxRx.state == RFAL_TXRX_STATE_IDLE) ? gRFAL.TxRx.status : ERR_BUSY); -} - -/*******************************************************************************/ -ReturnCode rfalGetTransceiveRSSI(uint16_t* rssi) { - uint16_t amRSSI; - uint16_t pmRSSI; - bool isSumMode; - - if(rssi == NULL) { - return ERR_PARAM; - } - - st25r3916GetRSSI(&amRSSI, &pmRSSI); - - /* Check if Correlator Summation mode is being used */ - isSumMode = - (st25r3916CheckReg( - ST25R3916_REG_CORR_CONF1, - ST25R3916_REG_CORR_CONF1_corr_s4, - ST25R3916_REG_CORR_CONF1_corr_s4) ? - st25r3916CheckReg(ST25R3916_REG_AUX, ST25R3916_REG_AUX_dis_corr, 0x00) : - false); - if(isSumMode) { - /*******************************************************************************/ - /* Using SQRT from math.h and float. If due to compiler, resources or performance - * issue this cannot be used, other approaches can be foreseen with less accuracy: - * Use a simpler sqrt algorithm - * *rssi = MAX( amRSSI, pmRSSI ); - * *rssi = ( (amRSSI + pmRSSI) / 2); - */ - *rssi = (uint16_t)sqrt( - ((double)amRSSI * (double)amRSSI) + - ((double)pmRSSI * - (double) - pmRSSI)); /* PRQA S 5209 # MISRA 4.9 - External function (sqrt()) requires double */ - } else { - /* Check which channel was used */ - *rssi = - (st25r3916CheckReg( - ST25R3916_REG_AUX_DISPLAY, - ST25R3916_REG_AUX_DISPLAY_a_cha, - ST25R3916_REG_AUX_DISPLAY_a_cha) ? - pmRSSI : - amRSSI); - } - return ERR_NONE; -} - -/*******************************************************************************/ -void rfalWorker(void) { - platformProtectWorker(); /* Protect RFAL Worker/Task/Process */ - - switch(gRFAL.state) { - case RFAL_STATE_TXRX: - rfalRunTransceiveWorker(); - break; - -#if RFAL_FEATURE_LISTEN_MODE - case RFAL_STATE_LM: - rfalRunListenModeWorker(); - break; -#endif /* RFAL_FEATURE_LISTEN_MODE */ - -#if RFAL_FEATURE_WAKEUP_MODE - case RFAL_STATE_WUM: - rfalRunWakeUpModeWorker(); - break; -#endif /* RFAL_FEATURE_WAKEUP_MODE */ - - /* Nothing to be done */ - default: - /* MISRA 16.4: no empty default statement (a comment being enough) */ - break; - } - - platformUnprotectWorker(); /* Unprotect RFAL Worker/Task/Process */ -} - -/*******************************************************************************/ -static void rfalErrorHandling(void) { - uint16_t fifoBytesToRead; - - fifoBytesToRead = rfalFIFOStatusGetNumBytes(); - -#ifdef RFAL_SW_EMD - /*******************************************************************************/ - /* EMVCo */ - /*******************************************************************************/ - if(gRFAL.conf.eHandling == RFAL_ERRORHANDLING_EMVCO) { - bool rxHasIncParError; - - /*******************************************************************************/ - /* EMD Handling - NFC Forum Digital 1.1 4.1.1.1 ; EMVCo v2.5 4.9.2 */ - /* ReEnable the receiver on frames with a length < 4 bytes, upon: */ - /* - Collision or Framing error detected */ - /* - Residual bits are detected (hard framing error) */ - /* - Parity error */ - /* - CRC error */ - /*******************************************************************************/ - - /* Check if reception has incomplete bytes or parity error */ - rxHasIncParError = - (rfalFIFOStatusIsIncompleteByte() ? true : - rfalFIFOStatusIsMissingPar()); /* MISRA 13.5 */ - - /* In case there are residual bits decrement FIFO bytes */ - /* Ensure FIFO contains some byte as the FIFO might be empty upon Framing errors */ - if((fifoBytesToRead > 0U) && rxHasIncParError) { - fifoBytesToRead--; - } - - if(((gRFAL.fifo.bytesTotal + fifoBytesToRead) < RFAL_EMVCO_RX_MAXLEN) && - ((gRFAL.TxRx.status == ERR_RF_COLLISION) || (gRFAL.TxRx.status == ERR_FRAMING) || - (gRFAL.TxRx.status == ERR_PAR) || (gRFAL.TxRx.status == ERR_CRC) || - rxHasIncParError)) { - /* Ignore this reception, ReEnable receiver which also clears the FIFO */ - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - - /* Ensure that the NRT has not expired meanwhile */ - if(st25r3916CheckReg( - ST25R3916_REG_NFCIP1_BIT_RATE, ST25R3916_REG_NFCIP1_BIT_RATE_nrt_on, 0x00)) { - if(st25r3916CheckReg( - ST25R3916_REG_AUX_DISPLAY, ST25R3916_REG_AUX_DISPLAY_rx_act, 0x00)) { - /* Abort reception */ - st25r3916ExecuteCommand(ST25R3916_CMD_MASK_RECEIVE_DATA); - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - return; - } - } - - rfalFIFOStatusClear(); - gRFAL.fifo.bytesTotal = 0; - gRFAL.TxRx.status = ERR_BUSY; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_WAIT_RXS; - } - return; - } -#endif - - /*******************************************************************************/ - /* ISO14443A Mode */ - /*******************************************************************************/ - if(gRFAL.mode == RFAL_MODE_POLL_NFCA) { - /*******************************************************************************/ - /* If we received a frame with a incomplete byte we`ll raise a specific error * - * ( support for T2T 4 bit ACK / NAK, MIFARE and Kovio ) */ - /*******************************************************************************/ - if((gRFAL.TxRx.status == ERR_PAR) || (gRFAL.TxRx.status == ERR_CRC)) { - if(rfalFIFOStatusIsIncompleteByte()) { - st25r3916ReadFifo((uint8_t*)(gRFAL.TxRx.ctx.rxBuf), fifoBytesToRead); - if((gRFAL.TxRx.ctx.rxRcvdLen) != NULL) { - *gRFAL.TxRx.ctx.rxRcvdLen = rfalFIFOGetNumIncompleteBits(); - } - - gRFAL.TxRx.status = ERR_INCOMPLETE_BYTE; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - } - } - } -} - -/*******************************************************************************/ -static void rfalCleanupTransceive(void) { - /*******************************************************************************/ - /* Transceive flags */ - /*******************************************************************************/ - - /* Restore default settings on NFCIP1 mode, Receiving parity + CRC bits and manual Tx Parity*/ - st25r3916ClrRegisterBits( - ST25R3916_REG_ISO14443A_NFC, - (ST25R3916_REG_ISO14443A_NFC_no_tx_par | ST25R3916_REG_ISO14443A_NFC_no_rx_par | - ST25R3916_REG_ISO14443A_NFC_nfc_f0)); - - /* Restore AGC enabled */ - st25r3916SetRegisterBits(ST25R3916_REG_RX_CONF2, ST25R3916_REG_RX_CONF2_agc_en); - - /*******************************************************************************/ - - /*******************************************************************************/ - /* Transceive timers */ - /*******************************************************************************/ - rfalTimerDestroy(gRFAL.tmr.txRx); - rfalTimerDestroy(gRFAL.tmr.RXE); - gRFAL.tmr.txRx = RFAL_TIMING_NONE; - gRFAL.tmr.RXE = RFAL_TIMING_NONE; - /*******************************************************************************/ - - /*******************************************************************************/ - /* Execute Post Transceive Callback */ - /*******************************************************************************/ - if(gRFAL.callbacks.postTxRx != NULL) { - gRFAL.callbacks.postTxRx(gRFAL.callbacks.ctx); - } - /*******************************************************************************/ -} - -/*******************************************************************************/ -static void rfalPrepareTransceive(void) { - uint32_t maskInterrupts; - uint8_t reg; - - /* If we are in RW or AP2P mode */ - if(!rfalIsModePassiveListen(gRFAL.mode)) { - /* Reset receive logic with STOP command */ - st25r3916ExecuteCommand(ST25R3916_CMD_STOP); - - /* Reset Rx Gain */ - st25r3916ExecuteCommand(ST25R3916_CMD_RESET_RXGAIN); - } else { - /* In Passive Listen Mode do not use STOP as it stops FDT timer */ - st25r3916ExecuteCommand(ST25R3916_CMD_CLEAR_FIFO); - } - - /*******************************************************************************/ - /* FDT Poll */ - /*******************************************************************************/ - if(rfalIsModePassiveComm(gRFAL.mode)) /* Passive Comms */ - { - /* In Passive communications General Purpose Timer is used to measure FDT Poll */ - if(gRFAL.timings.FDTPoll != RFAL_TIMING_NONE) { - /* Configure GPT to start at RX end */ - st25r3916SetStartGPTimer( - (uint16_t)rfalConv1fcTo8fc(MIN( - gRFAL.timings.FDTPoll, (gRFAL.timings.FDTPoll - RFAL_FDT_POLL_ADJUSTMENT))), - ST25R3916_REG_TIMER_EMV_CONTROL_gptc_erx); - } - } - - /*******************************************************************************/ - /* Execute Pre Transceive Callback */ - /*******************************************************************************/ - if(gRFAL.callbacks.preTxRx != NULL) { - gRFAL.callbacks.preTxRx(gRFAL.callbacks.ctx); - } - /*******************************************************************************/ - - maskInterrupts = - (ST25R3916_IRQ_MASK_FWL | ST25R3916_IRQ_MASK_TXE | ST25R3916_IRQ_MASK_RXS | - ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_CRC | - ST25R3916_IRQ_MASK_ERR1 | ST25R3916_IRQ_MASK_ERR2 | ST25R3916_IRQ_MASK_NRE); - - /*******************************************************************************/ - /* Transceive flags */ - /*******************************************************************************/ - - reg = - (ST25R3916_REG_ISO14443A_NFC_no_tx_par_off | ST25R3916_REG_ISO14443A_NFC_no_rx_par_off | - ST25R3916_REG_ISO14443A_NFC_nfc_f0_off); - - /* Check if NFCIP1 mode is to be enabled */ - if((gRFAL.TxRx.ctx.flags & (uint8_t)RFAL_TXRX_FLAGS_NFCIP1_ON) != 0U) { - reg |= ST25R3916_REG_ISO14443A_NFC_nfc_f0; - } - - /* Check if Parity check is to be skipped and to keep the parity + CRC bits in FIFO */ - if((gRFAL.TxRx.ctx.flags & (uint8_t)RFAL_TXRX_FLAGS_PAR_RX_KEEP) != 0U) { - reg |= ST25R3916_REG_ISO14443A_NFC_no_rx_par; - } - - /* Check if automatic Parity bits is to be disabled */ - if((gRFAL.TxRx.ctx.flags & (uint8_t)RFAL_TXRX_FLAGS_PAR_TX_NONE) != 0U) { - reg |= ST25R3916_REG_ISO14443A_NFC_no_tx_par; - } - - /* Apply current TxRx flags on ISO14443A and NFC 106kb/s Settings Register */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_ISO14443A_NFC, - (ST25R3916_REG_ISO14443A_NFC_no_tx_par | ST25R3916_REG_ISO14443A_NFC_no_rx_par | - ST25R3916_REG_ISO14443A_NFC_nfc_f0), - reg); - - /* Check if AGC is to be disabled */ - if((gRFAL.TxRx.ctx.flags & (uint8_t)RFAL_TXRX_FLAGS_AGC_OFF) != 0U) { - st25r3916ClrRegisterBits(ST25R3916_REG_RX_CONF2, ST25R3916_REG_RX_CONF2_agc_en); - } else { - st25r3916SetRegisterBits(ST25R3916_REG_RX_CONF2, ST25R3916_REG_RX_CONF2_agc_en); - } - /*******************************************************************************/ - - /*******************************************************************************/ - /* EMVCo NRT mode */ - /*******************************************************************************/ - if(gRFAL.conf.eHandling == RFAL_ERRORHANDLING_EMVCO) { - st25r3916SetRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, ST25R3916_REG_TIMER_EMV_CONTROL_nrt_emv); - maskInterrupts |= ST25R3916_IRQ_MASK_RX_REST; - } else { - st25r3916ClrRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, ST25R3916_REG_TIMER_EMV_CONTROL_nrt_emv); - } - /*******************************************************************************/ - - /* In Passive Listen mode additionally enable External Field interrupts */ - if(rfalIsModePassiveListen(gRFAL.mode)) { - maskInterrupts |= - (ST25R3916_IRQ_MASK_EOF | - ST25R3916_IRQ_MASK_WU_F); /* Enable external Field interrupts to detect Link Loss and SENF_REQ auto responses */ - } - - /* In Active comms enable also External Field interrupts and set RF Collision Avoindance */ - if(rfalIsModeActiveComm(gRFAL.mode)) { - maskInterrupts |= - (ST25R3916_IRQ_MASK_EOF | ST25R3916_IRQ_MASK_EON | ST25R3916_IRQ_MASK_PPON2 | - ST25R3916_IRQ_MASK_CAT | ST25R3916_IRQ_MASK_CAC); - - /* Set n=0 for subsequent RF Collision Avoidance */ - st25r3916ChangeRegisterBits(ST25R3916_REG_AUX, ST25R3916_REG_AUX_nfc_n_mask, 0); - } - - /*******************************************************************************/ - /* Start transceive Sanity Timer if a FWT is used */ - if((gRFAL.TxRx.ctx.fwt != RFAL_FWT_NONE) && (gRFAL.TxRx.ctx.fwt != 0U)) { - rfalTimerStart(gRFAL.tmr.txRx, rfalCalcSanityTmr(gRFAL.TxRx.ctx.fwt)); - } - /*******************************************************************************/ - - /*******************************************************************************/ - /* Clear and enable these interrupts */ - st25r3916GetInterrupt(maskInterrupts); - st25r3916EnableInterrupts(maskInterrupts); - - /* Clear FIFO status local copy */ - rfalFIFOStatusClear(); -} - -/*******************************************************************************/ -static void rfalTransceiveTx(void) { - volatile uint32_t irqs; - uint16_t tmp; - ReturnCode ret; - - /* Suppress warning in case NFC-V feature is disabled */ - ret = ERR_NONE; - NO_WARNING(ret); - - irqs = ST25R3916_IRQ_MASK_NONE; - - if(gRFAL.TxRx.state != gRFAL.TxRx.lastState) { - /* rfalLogD( "RFAL: lastSt: %d curSt: %d \r\n", gRFAL.TxRx.lastState, gRFAL.TxRx.state ); */ - gRFAL.TxRx.lastState = gRFAL.TxRx.state; - } - - switch(gRFAL.TxRx.state) { - /*******************************************************************************/ - case RFAL_TXRX_STATE_TX_IDLE: - - /* Nothing to do */ - - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_WAIT_GT; - /* fall through */ - - /*******************************************************************************/ - case RFAL_TXRX_STATE_TX_WAIT_GT: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - if(!rfalIsGTExpired()) { - break; - } - - rfalTimerDestroy(gRFAL.tmr.GT); - gRFAL.tmr.GT = RFAL_TIMING_NONE; - - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_WAIT_FDT; - /* fall through */ - - /*******************************************************************************/ - case RFAL_TXRX_STATE_TX_WAIT_FDT: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - /* Only in Passive communications GPT is used to measure FDT Poll */ - if(rfalIsModePassiveComm(gRFAL.mode)) { - if(st25r3916IsGPTRunning()) { - break; - } - } - - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_TRANSMIT; - /* fall through */ - - /*******************************************************************************/ - case RFAL_TXRX_STATE_TX_TRANSMIT: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - /* Clear FIFO, Clear and Enable the Interrupts */ - rfalPrepareTransceive(); - - /* ST25R3916 has a fixed FIFO water level */ - gRFAL.fifo.expWL = RFAL_FIFO_OUT_WL; - -#if RFAL_FEATURE_NFCV - /*******************************************************************************/ - /* In NFC-V streaming mode, the FIFO needs to be loaded with the coded bits */ - if((RFAL_MODE_POLL_NFCV == gRFAL.mode) || (RFAL_MODE_POLL_PICOPASS == gRFAL.mode)) { -#if 0 - /* Debugging code: output the payload bits by writing into the FIFO and subsequent clearing */ - st25r3916WriteFifo(gRFAL.TxRx.ctx.txBuf, rfalConvBitsToBytes(gRFAL.TxRx.ctx.txBufLen)); - st25r3916ExecuteCommand( ST25R3916_CMD_CLEAR_FIFO ); -#endif - /* Calculate the bytes needed to be Written into FIFO (a incomplete byte will be added as 1byte) */ - gRFAL.nfcvData.nfcvOffset = 0; - ret = iso15693VCDCode( - gRFAL.TxRx.ctx.txBuf, - rfalConvBitsToBytes(gRFAL.TxRx.ctx.txBufLen), - (((gRFAL.nfcvData.origCtx.flags & (uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL) != 0U) ? - false : - true), - (((gRFAL.nfcvData.origCtx.flags & (uint32_t)RFAL_TXRX_FLAGS_NFCV_FLAG_MANUAL) != - 0U) ? - false : - true), - (RFAL_MODE_POLL_PICOPASS == gRFAL.mode), - &gRFAL.fifo.bytesTotal, - &gRFAL.nfcvData.nfcvOffset, - gRFAL.nfcvData.codingBuffer, - MIN((uint16_t)ST25R3916_FIFO_DEPTH, (uint16_t)sizeof(gRFAL.nfcvData.codingBuffer)), - &gRFAL.fifo.bytesWritten); - - if((ret != ERR_NONE) && (ret != ERR_AGAIN)) { - gRFAL.TxRx.status = ret; - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_FAIL; - break; - } - /* Set the number of full bytes and bits to be transmitted */ - st25r3916SetNumTxBits((uint16_t)rfalConvBytesToBits(gRFAL.fifo.bytesTotal)); - - /* Load FIFO with coded bytes */ - st25r3916WriteFifo(gRFAL.nfcvData.codingBuffer, gRFAL.fifo.bytesWritten); - - } - /*******************************************************************************/ - else -#endif /* RFAL_FEATURE_NFCV */ - { - /* Calculate the bytes needed to be Written into FIFO (a incomplete byte will be added as 1byte) */ - gRFAL.fifo.bytesTotal = (uint16_t)rfalCalcNumBytes(gRFAL.TxRx.ctx.txBufLen); - - /* Set the number of full bytes and bits to be transmitted */ - st25r3916SetNumTxBits(gRFAL.TxRx.ctx.txBufLen); - - /* Load FIFO with total length or FIFO's maximum */ - gRFAL.fifo.bytesWritten = MIN(gRFAL.fifo.bytesTotal, ST25R3916_FIFO_DEPTH); - st25r3916WriteFifo(gRFAL.TxRx.ctx.txBuf, gRFAL.fifo.bytesWritten); - } - - /*Check if Observation Mode is enabled and set it on ST25R391x */ - rfalCheckEnableObsModeTx(); - - /*******************************************************************************/ - /* If we're in Passive Listen mode ensure that the external field is still On */ - if(rfalIsModePassiveListen(gRFAL.mode)) { - if(!rfalIsExtFieldOn()) { - gRFAL.TxRx.status = ERR_LINK_LOSS; - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_FAIL; - break; - } - } - - /*******************************************************************************/ - /* Trigger/Start transmission */ - if((gRFAL.TxRx.ctx.flags & (uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL) != 0U) { - st25r3916ExecuteCommand(ST25R3916_CMD_TRANSMIT_WITHOUT_CRC); - } else { - st25r3916ExecuteCommand(ST25R3916_CMD_TRANSMIT_WITH_CRC); - } - - /* Check if a WL level is expected or TXE should come */ - gRFAL.TxRx.state = - ((gRFAL.fifo.bytesWritten < gRFAL.fifo.bytesTotal) ? RFAL_TXRX_STATE_TX_WAIT_WL : - RFAL_TXRX_STATE_TX_WAIT_TXE); - break; - - /*******************************************************************************/ - case RFAL_TXRX_STATE_TX_WAIT_WL: - - irqs = st25r3916GetInterrupt((ST25R3916_IRQ_MASK_FWL | ST25R3916_IRQ_MASK_TXE)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if(((irqs & ST25R3916_IRQ_MASK_FWL) != 0U) && ((irqs & ST25R3916_IRQ_MASK_TXE) == 0U)) { - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_RELOAD_FIFO; - } else { - gRFAL.TxRx.status = ERR_IO; - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_FAIL; - break; - } - - /* fall through */ - - /*******************************************************************************/ - case RFAL_TXRX_STATE_TX_RELOAD_FIFO: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - -#if RFAL_FEATURE_NFCV - /*******************************************************************************/ - /* In NFC-V streaming mode, the FIFO needs to be loaded with the coded bits */ - if((RFAL_MODE_POLL_NFCV == gRFAL.mode) || (RFAL_MODE_POLL_PICOPASS == gRFAL.mode)) { - uint16_t maxLen; - - /* Load FIFO with the remaining length or maximum available (which fit on the coding buffer) */ - maxLen = - (uint16_t)MIN((gRFAL.fifo.bytesTotal - gRFAL.fifo.bytesWritten), gRFAL.fifo.expWL); - maxLen = (uint16_t)MIN(maxLen, sizeof(gRFAL.nfcvData.codingBuffer)); - tmp = 0; - - /* Calculate the bytes needed to be Written into FIFO (a incomplete byte will be added as 1byte) */ - ret = iso15693VCDCode( - gRFAL.TxRx.ctx.txBuf, - rfalConvBitsToBytes(gRFAL.TxRx.ctx.txBufLen), - (((gRFAL.nfcvData.origCtx.flags & (uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL) != 0U) ? - false : - true), - (((gRFAL.nfcvData.origCtx.flags & (uint32_t)RFAL_TXRX_FLAGS_NFCV_FLAG_MANUAL) != - 0U) ? - false : - true), - (RFAL_MODE_POLL_PICOPASS == gRFAL.mode), - &gRFAL.fifo.bytesTotal, - &gRFAL.nfcvData.nfcvOffset, - gRFAL.nfcvData.codingBuffer, - maxLen, - &tmp); - - if((ret != ERR_NONE) && (ret != ERR_AGAIN)) { - gRFAL.TxRx.status = ret; - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_FAIL; - break; - } - - /* Load FIFO with coded bytes */ - st25r3916WriteFifo(gRFAL.nfcvData.codingBuffer, tmp); - } - /*******************************************************************************/ - else -#endif /* RFAL_FEATURE_NFCV */ - { - /* Load FIFO with the remaining length or maximum available */ - tmp = MIN( - (gRFAL.fifo.bytesTotal - gRFAL.fifo.bytesWritten), - gRFAL.fifo.expWL); /* tmp holds the number of bytes written on this iteration */ - st25r3916WriteFifo(&gRFAL.TxRx.ctx.txBuf[gRFAL.fifo.bytesWritten], tmp); - } - - /* Update total written bytes to FIFO */ - gRFAL.fifo.bytesWritten += tmp; - - /* Check if a WL level is expected or TXE should come */ - gRFAL.TxRx.state = - ((gRFAL.fifo.bytesWritten < gRFAL.fifo.bytesTotal) ? RFAL_TXRX_STATE_TX_WAIT_WL : - RFAL_TXRX_STATE_TX_WAIT_TXE); - break; - - /*******************************************************************************/ - case RFAL_TXRX_STATE_TX_WAIT_TXE: - - irqs = st25r3916GetInterrupt((ST25R3916_IRQ_MASK_FWL | ST25R3916_IRQ_MASK_TXE)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_TXE) != 0U) { - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_DONE; - } else if((irqs & ST25R3916_IRQ_MASK_FWL) != 0U) { - break; /* Ignore ST25R3916 FIFO WL if total TxLen is already on the FIFO */ - } else { - gRFAL.TxRx.status = ERR_IO; - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_FAIL; - break; - } - - /* fall through */ - - /*******************************************************************************/ - case RFAL_TXRX_STATE_TX_DONE: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - /* If no rxBuf is provided do not wait/expect Rx */ - if(gRFAL.TxRx.ctx.rxBuf == NULL) { - /*Check if Observation Mode was enabled and disable it on ST25R391x */ - rfalCheckDisableObsMode(); - - /* Clean up Transceive */ - rfalCleanupTransceive(); - - gRFAL.TxRx.status = ERR_NONE; - gRFAL.TxRx.state = RFAL_TXRX_STATE_IDLE; - break; - } - - rfalCheckEnableObsModeRx(); - - /* Goto Rx */ - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_IDLE; - break; - - /*******************************************************************************/ - case RFAL_TXRX_STATE_TX_FAIL: - - /* Error should be assigned by previous state */ - if(gRFAL.TxRx.status == ERR_BUSY) { - gRFAL.TxRx.status = ERR_SYSTEM; - } - - /*Check if Observation Mode was enabled and disable it on ST25R391x */ - rfalCheckDisableObsMode(); - - /* Clean up Transceive */ - rfalCleanupTransceive(); - - gRFAL.TxRx.state = RFAL_TXRX_STATE_IDLE; - break; - - /*******************************************************************************/ - default: - gRFAL.TxRx.status = ERR_SYSTEM; - gRFAL.TxRx.state = RFAL_TXRX_STATE_TX_FAIL; - break; - } -} - -/*******************************************************************************/ -static void rfalTransceiveRx(void) { - volatile uint32_t irqs; - uint16_t tmp; - uint16_t aux; - - irqs = ST25R3916_IRQ_MASK_NONE; - - if(gRFAL.TxRx.state != gRFAL.TxRx.lastState) { - /* rfalLogD( "RFAL: lastSt: %d curSt: %d \r\n", gRFAL.TxRx.lastState, gRFAL.TxRx.state ); */ - gRFAL.TxRx.lastState = gRFAL.TxRx.state; - } - - switch(gRFAL.TxRx.state) { - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_IDLE: - - /* Clear rx counters */ - gRFAL.fifo.bytesWritten = 0; /* Total bytes written on RxBuffer */ - gRFAL.fifo.bytesTotal = 0; /* Total bytes in FIFO will now be from Rx */ - if(gRFAL.TxRx.ctx.rxRcvdLen != NULL) { - *gRFAL.TxRx.ctx.rxRcvdLen = 0; - } - - gRFAL.TxRx.state = - (rfalIsModeActiveComm(gRFAL.mode) ? RFAL_TXRX_STATE_RX_WAIT_EON : - RFAL_TXRX_STATE_RX_WAIT_RXS); - break; - - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_WAIT_RXS: - - /*******************************************************************************/ - irqs = st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_RXS | ST25R3916_IRQ_MASK_NRE | ST25R3916_IRQ_MASK_EOF)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - /* Only raise Timeout if NRE is detected with no Rx Start (NRT EMV mode) */ - if(((irqs & ST25R3916_IRQ_MASK_NRE) != 0U) && ((irqs & ST25R3916_IRQ_MASK_RXS) == 0U)) { - gRFAL.TxRx.status = ERR_TIMEOUT; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - break; - } - - /* Only raise Link Loss if EOF is detected with no Rx Start */ - if(((irqs & ST25R3916_IRQ_MASK_EOF) != 0U) && ((irqs & ST25R3916_IRQ_MASK_RXS) == 0U)) { - /* In AP2P a Field On has already occurred - treat this as timeout | mute */ - gRFAL.TxRx.status = (rfalIsModeActiveComm(gRFAL.mode) ? ERR_TIMEOUT : ERR_LINK_LOSS); - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - break; - } - - if((irqs & ST25R3916_IRQ_MASK_RXS) != 0U) { - /*******************************************************************************/ - /* REMARK: Silicon workaround ST25R3916 Errata #TBD */ - /* Rarely on corrupted frames I_rxs gets signaled but I_rxe is not signaled */ - /* Use a SW timer to handle an eventual missing RXE */ - rfalTimerStart(gRFAL.tmr.RXE, RFAL_NORXE_TOUT); - /*******************************************************************************/ - - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_WAIT_RXE; - } else { - gRFAL.TxRx.status = ERR_IO; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - break; - } - - /* remove NRE that might appear together (NRT EMV mode), and remove RXS, but keep EOF if present for next state */ - irqs &= ~(ST25R3916_IRQ_MASK_RXS | ST25R3916_IRQ_MASK_NRE); - - /* fall through */ - - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_WAIT_RXE: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - /*******************************************************************************/ - /* REMARK: Silicon workaround ST25R3916 Errata #TBD */ - /* ST25R396 may indicate RXS without RXE afterwards, this happens rarely on */ - /* corrupted frames. */ - /* SW timer is used to timeout upon a missing RXE */ - if(rfalTimerisExpired(gRFAL.tmr.RXE)) { - gRFAL.TxRx.status = ERR_FRAMING; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - } - /*******************************************************************************/ - - irqs |= st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_FWL | ST25R3916_IRQ_MASK_EOF | - ST25R3916_IRQ_MASK_RX_REST | ST25R3916_IRQ_MASK_WU_F)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_RX_REST) != 0U) { - /* RX_REST indicates that Receiver has been reset due to EMD, therefore a RXS + RXE should * - * follow if a good reception is followed within the valid initial timeout */ - - /* Check whether NRT has expired already, if so signal a timeout */ - if(st25r3916GetInterrupt(ST25R3916_IRQ_MASK_NRE) != 0U) { - gRFAL.TxRx.status = ERR_TIMEOUT; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - break; - } - if(st25r3916CheckReg( - ST25R3916_REG_NFCIP1_BIT_RATE, - ST25R3916_REG_NFCIP1_BIT_RATE_nrt_on, - 0)) /* MISRA 13.5 */ - { - gRFAL.TxRx.status = ERR_TIMEOUT; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - break; - } - - /* Discard any previous RXS */ - st25r3916GetInterrupt(ST25R3916_IRQ_MASK_RXS); - - /* Check whether a following reception has already started */ - if(st25r3916CheckReg( - ST25R3916_REG_AUX_DISPLAY, - ST25R3916_REG_AUX_DISPLAY_rx_act, - ST25R3916_REG_AUX_DISPLAY_rx_act)) { - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_WAIT_RXE; - break; - } - - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_WAIT_RXS; - break; - } - - if(((irqs & ST25R3916_IRQ_MASK_FWL) != 0U) && ((irqs & ST25R3916_IRQ_MASK_RXE) == 0U)) { - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_READ_FIFO; - break; - } - - /* Automatic responses allowed during TxRx only for the SENSF_REQ */ - if((irqs & ST25R3916_IRQ_MASK_WU_F) != 0U) { - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_WAIT_RXS; - break; - } - - /* After RXE retrieve and check for any error irqs */ - irqs |= st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_CRC | ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_ERR1 | - ST25R3916_IRQ_MASK_ERR2 | ST25R3916_IRQ_MASK_COL)); - - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_ERR_CHECK; - /* fall through */ - - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_ERR_CHECK: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - if((irqs & ST25R3916_IRQ_MASK_ERR1) != 0U) { - gRFAL.TxRx.status = ERR_FRAMING; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_READ_DATA; - - /* Check if there's a specific error handling for this */ - rfalErrorHandling(); - break; - } - /* Discard Soft Framing errors in AP2P and CE */ - else if(rfalIsModePassivePoll(gRFAL.mode) && ((irqs & ST25R3916_IRQ_MASK_ERR2) != 0U)) { - gRFAL.TxRx.status = ERR_FRAMING; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_READ_DATA; - - /* Check if there's a specific error handling for this */ - rfalErrorHandling(); - break; - } else if((irqs & ST25R3916_IRQ_MASK_PAR) != 0U) { - gRFAL.TxRx.status = ERR_PAR; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_READ_DATA; - - /* Check if there's a specific error handling for this */ - rfalErrorHandling(); - break; - } else if((irqs & ST25R3916_IRQ_MASK_CRC) != 0U) { - gRFAL.TxRx.status = ERR_CRC; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_READ_DATA; - - /* Check if there's a specific error handling for this */ - rfalErrorHandling(); - break; - } else if((irqs & ST25R3916_IRQ_MASK_COL) != 0U) { - gRFAL.TxRx.status = ERR_RF_COLLISION; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_READ_DATA; - - /* Check if there's a specific error handling for this */ - rfalErrorHandling(); - break; - } else if(rfalIsModePassiveListen(gRFAL.mode) && ((irqs & ST25R3916_IRQ_MASK_EOF) != 0U)) { - gRFAL.TxRx.status = ERR_LINK_LOSS; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - break; - } else if((irqs & ST25R3916_IRQ_MASK_RXE) != 0U) { - /* Reception ended without any error indication, * - * check FIFO status for malformed or incomplete frames */ - - /* Check if the reception ends with an incomplete byte (residual bits) */ - if(rfalFIFOStatusIsIncompleteByte()) { - gRFAL.TxRx.status = ERR_INCOMPLETE_BYTE; - } - /* Check if the reception ends missing parity bit */ - else if(rfalFIFOStatusIsMissingPar()) { - gRFAL.TxRx.status = ERR_FRAMING; - } else { - /* MISRA 15.7 - Empty else */ - } - - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_READ_DATA; - } else { - gRFAL.TxRx.status = ERR_IO; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - break; - } - - /* fall through */ - - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_READ_DATA: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - tmp = rfalFIFOStatusGetNumBytes(); - - /*******************************************************************************/ - /* Check if CRC should not be placed in rxBuf */ - if(((gRFAL.TxRx.ctx.flags & (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP) == 0U)) { - /* if received frame was bigger than CRC */ - if((uint16_t)(gRFAL.fifo.bytesTotal + tmp) > 0U) { - /* By default CRC will not be placed into the rxBuffer */ - if((tmp > RFAL_CRC_LEN)) { - tmp -= RFAL_CRC_LEN; - } - /* If the CRC was already placed into rxBuffer (due to WL interrupt where CRC was already in FIFO Read) - * cannot remove it from rxBuf. Can only remove it from rxBufLen not indicate the presence of CRC */ - else if(gRFAL.fifo.bytesTotal > RFAL_CRC_LEN) { - gRFAL.fifo.bytesTotal -= RFAL_CRC_LEN; - } else { - /* MISRA 15.7 - Empty else */ - } - } - } - - gRFAL.fifo.bytesTotal += tmp; /* add to total bytes counter */ - - /*******************************************************************************/ - /* Check if remaining bytes fit on the rxBuf available */ - if(gRFAL.fifo.bytesTotal > rfalConvBitsToBytes(gRFAL.TxRx.ctx.rxBufLen)) { - tmp = - (uint16_t)(rfalConvBitsToBytes(gRFAL.TxRx.ctx.rxBufLen) - gRFAL.fifo.bytesWritten); - - /* Transmission errors have precedence over buffer error */ - if(gRFAL.TxRx.status == ERR_BUSY) { - gRFAL.TxRx.status = ERR_NOMEM; - } - } - - /*******************************************************************************/ - /* Retrieve remaining bytes from FIFO to rxBuf, and assign total length rcvd */ - st25r3916ReadFifo(&gRFAL.TxRx.ctx.rxBuf[gRFAL.fifo.bytesWritten], tmp); - if(gRFAL.TxRx.ctx.rxRcvdLen != NULL) { - (*gRFAL.TxRx.ctx.rxRcvdLen) = (uint16_t)rfalConvBytesToBits(gRFAL.fifo.bytesTotal); - if(rfalFIFOStatusIsIncompleteByte()) { - (*gRFAL.TxRx.ctx.rxRcvdLen) -= - (RFAL_BITS_IN_BYTE - rfalFIFOGetNumIncompleteBits()); - } - } - -#if RFAL_FEATURE_NFCV - /*******************************************************************************/ - /* Decode sub bit stream into payload bits for NFCV, if no error found so far */ - if(((RFAL_MODE_POLL_NFCV == gRFAL.mode) || (RFAL_MODE_POLL_PICOPASS == gRFAL.mode)) && - (gRFAL.TxRx.status == ERR_BUSY)) { - ReturnCode ret; - uint16_t offset = 0; /* REMARK offset not currently used */ - - ret = iso15693VICCDecode( - gRFAL.TxRx.ctx.rxBuf, - gRFAL.fifo.bytesTotal, - gRFAL.nfcvData.origCtx.rxBuf, - rfalConvBitsToBytes(gRFAL.nfcvData.origCtx.rxBufLen), - &offset, - gRFAL.nfcvData.origCtx.rxRcvdLen, - gRFAL.nfcvData.ignoreBits, - (RFAL_MODE_POLL_PICOPASS == gRFAL.mode)); - - if(((ERR_NONE == ret) || (ERR_CRC == ret)) && - (((uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP & gRFAL.nfcvData.origCtx.flags) == 0U) && - ((*gRFAL.nfcvData.origCtx.rxRcvdLen % RFAL_BITS_IN_BYTE) == 0U) && - (*gRFAL.nfcvData.origCtx.rxRcvdLen >= rfalConvBytesToBits(RFAL_CRC_LEN))) { - *gRFAL.nfcvData.origCtx.rxRcvdLen -= - (uint16_t)rfalConvBytesToBits(RFAL_CRC_LEN); /* Remove CRC */ - } -#if 0 - /* Debugging code: output the payload bits by writing into the FIFO and subsequent clearing */ - st25r3916WriteFifo(gRFAL.nfcvData.origCtx.rxBuf, rfalConvBitsToBytes( *gRFAL.nfcvData.origCtx.rxRcvdLen)); - st25r3916ExecuteCommand( ST25R3916_CMD_CLEAR_FIFO ); -#endif - - /* Restore original ctx */ - gRFAL.TxRx.ctx = gRFAL.nfcvData.origCtx; - gRFAL.TxRx.status = ((ret != ERR_NONE) ? ret : ERR_BUSY); - } -#endif /* RFAL_FEATURE_NFCV */ - - /*******************************************************************************/ - /* If an error as been marked/detected don't fall into to RX_DONE */ - if(gRFAL.TxRx.status != ERR_BUSY) { - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - break; - } - - if(rfalIsModeActiveComm(gRFAL.mode)) { - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_WAIT_EOF; - break; - } - - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_DONE; - /* fall through */ - - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_DONE: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - /*Check if Observation Mode was enabled and disable it on ST25R391x */ - rfalCheckDisableObsMode(); - - /* Clean up Transceive */ - rfalCleanupTransceive(); - - gRFAL.TxRx.status = ERR_NONE; - gRFAL.TxRx.state = RFAL_TXRX_STATE_IDLE; - break; - - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_READ_FIFO: - - /*******************************************************************************/ - /* REMARK: Silicon workaround ST25R3916 Errata #TBD */ - /* Rarely on corrupted frames I_rxs gets signaled but I_rxe is not signaled */ - /* Use a SW timer to handle an eventual missing RXE */ - rfalTimerStart(gRFAL.tmr.RXE, RFAL_NORXE_TOUT); - /*******************************************************************************/ - - tmp = rfalFIFOStatusGetNumBytes(); - gRFAL.fifo.bytesTotal += tmp; - - /*******************************************************************************/ - /* Calculate the amount of bytes that still fits in rxBuf */ - aux = - ((gRFAL.fifo.bytesTotal > rfalConvBitsToBytes(gRFAL.TxRx.ctx.rxBufLen)) ? - (rfalConvBitsToBytes(gRFAL.TxRx.ctx.rxBufLen) - gRFAL.fifo.bytesWritten) : - tmp); - - /*******************************************************************************/ - /* Retrieve incoming bytes from FIFO to rxBuf, and store already read amount */ - st25r3916ReadFifo(&gRFAL.TxRx.ctx.rxBuf[gRFAL.fifo.bytesWritten], aux); - gRFAL.fifo.bytesWritten += aux; - - /*******************************************************************************/ - /* If the bytes already read were not the full FIFO WL, dump the remaining * - * FIFO so that ST25R391x can continue with reception */ - if(aux < tmp) { - st25r3916ReadFifo(NULL, (tmp - aux)); - } - - rfalFIFOStatusClear(); - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_WAIT_RXE; - break; - - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_FAIL: - - /*Check if Observation Mode was enabled and disable it on ST25R391x */ - rfalCheckDisableObsMode(); - - /* Clean up Transceive */ - rfalCleanupTransceive(); - - /* Error should be assigned by previous state */ - if(gRFAL.TxRx.status == ERR_BUSY) { - gRFAL.TxRx.status = ERR_SYSTEM; - } - - /*rfalLogD( "RFAL: curSt: %d Error: %d \r\n", gRFAL.TxRx.state, gRFAL.TxRx.status );*/ - gRFAL.TxRx.state = RFAL_TXRX_STATE_IDLE; - break; - - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_WAIT_EON: - - irqs = st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_EON | ST25R3916_IRQ_MASK_NRE | ST25R3916_IRQ_MASK_PPON2)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_EON) != 0U) { - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_WAIT_RXS; - } - - if((irqs & ST25R3916_IRQ_MASK_NRE) != 0U) { - gRFAL.TxRx.status = ERR_TIMEOUT; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - } - if((irqs & ST25R3916_IRQ_MASK_PPON2) != 0U) { - gRFAL.TxRx.status = ERR_LINK_LOSS; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - } - break; - - /*******************************************************************************/ - case RFAL_TXRX_STATE_RX_WAIT_EOF: - - irqs = st25r3916GetInterrupt((ST25R3916_IRQ_MASK_CAT | ST25R3916_IRQ_MASK_CAC)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_CAT) != 0U) { - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_DONE; - } else if((irqs & ST25R3916_IRQ_MASK_CAC) != 0U) { - gRFAL.TxRx.status = ERR_RF_COLLISION; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - } else { - gRFAL.TxRx.status = ERR_IO; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - } - break; - - /*******************************************************************************/ - default: - gRFAL.TxRx.status = ERR_SYSTEM; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_FAIL; - break; - } -} - -/*******************************************************************************/ -static void rfalFIFOStatusUpdate(void) { - if(gRFAL.fifo.status[RFAL_FIFO_STATUS_REG2] == RFAL_FIFO_STATUS_INVALID) { - st25r3916ReadMultipleRegisters( - ST25R3916_REG_FIFO_STATUS1, gRFAL.fifo.status, ST25R3916_FIFO_STATUS_LEN); - } -} - -/*******************************************************************************/ -static void rfalFIFOStatusClear(void) { - gRFAL.fifo.status[RFAL_FIFO_STATUS_REG2] = RFAL_FIFO_STATUS_INVALID; -} - -/*******************************************************************************/ -static uint16_t rfalFIFOStatusGetNumBytes(void) { - uint16_t result; - - rfalFIFOStatusUpdate(); - - result = - ((((uint16_t)gRFAL.fifo.status[RFAL_FIFO_STATUS_REG2] & - ST25R3916_REG_FIFO_STATUS2_fifo_b_mask) >> - ST25R3916_REG_FIFO_STATUS2_fifo_b_shift) - << RFAL_BITS_IN_BYTE); - result |= (((uint16_t)gRFAL.fifo.status[RFAL_FIFO_STATUS_REG1]) & 0x00FFU); - return result; -} - -/*******************************************************************************/ -static bool rfalFIFOStatusIsIncompleteByte(void) { - rfalFIFOStatusUpdate(); - return ( - (gRFAL.fifo.status[RFAL_FIFO_STATUS_REG2] & ST25R3916_REG_FIFO_STATUS2_fifo_lb_mask) != - 0U); -} - -/*******************************************************************************/ -static bool rfalFIFOStatusIsMissingPar(void) { - rfalFIFOStatusUpdate(); - return ((gRFAL.fifo.status[RFAL_FIFO_STATUS_REG2] & ST25R3916_REG_FIFO_STATUS2_np_lb) != 0U); -} - -/*******************************************************************************/ -static uint8_t rfalFIFOGetNumIncompleteBits(void) { - rfalFIFOStatusUpdate(); - return ( - (gRFAL.fifo.status[RFAL_FIFO_STATUS_REG2] & ST25R3916_REG_FIFO_STATUS2_fifo_lb_mask) >> - ST25R3916_REG_FIFO_STATUS2_fifo_lb_shift); -} - -#if RFAL_FEATURE_NFCA - -/*******************************************************************************/ -ReturnCode rfalISO14443ATransceiveShortFrame( - rfal14443AShortFrameCmd txCmd, - uint8_t* rxBuf, - uint8_t rxBufLen, - uint16_t* rxRcvdLen, - uint32_t fwt) { - ReturnCode ret; - uint8_t directCmd; - - /* Check if RFAL is properly initialized */ - if(!st25r3916IsTxEnabled() || (gRFAL.state < RFAL_STATE_MODE_SET) || - ((gRFAL.mode != RFAL_MODE_POLL_NFCA) && (gRFAL.mode != RFAL_MODE_POLL_NFCA_T1T))) { - return ERR_WRONG_STATE; - } - - /* Check for valid parameters */ - if((rxBuf == NULL) || (rxRcvdLen == NULL) || (fwt == RFAL_FWT_NONE)) { - return ERR_PARAM; - } - - /*******************************************************************************/ - /* Select the Direct Command to be performed */ - switch(txCmd) { - case RFAL_14443A_SHORTFRAME_CMD_WUPA: - directCmd = ST25R3916_CMD_TRANSMIT_WUPA; - break; - - case RFAL_14443A_SHORTFRAME_CMD_REQA: - directCmd = ST25R3916_CMD_TRANSMIT_REQA; - break; - - default: - return ERR_PARAM; - } - - /* Disable CRC while receiving since ATQA has no CRC included */ - st25r3916SetRegisterBits(ST25R3916_REG_AUX, ST25R3916_REG_AUX_no_crc_rx); - - /*******************************************************************************/ - /* Wait for GT and FDT */ - while(!rfalIsGTExpired()) { /* MISRA 15.6: mandatory brackets */ - }; - while(st25r3916IsGPTRunning()) { /* MISRA 15.6: mandatory brackets */ - }; - - rfalTimerDestroy(gRFAL.tmr.GT); - gRFAL.tmr.GT = RFAL_TIMING_NONE; - - /*******************************************************************************/ - /* Prepare for Transceive, Receive only (bypass Tx states) */ - gRFAL.TxRx.ctx.flags = - ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP); - gRFAL.TxRx.ctx.rxBuf = rxBuf; - gRFAL.TxRx.ctx.rxBufLen = rxBufLen; - gRFAL.TxRx.ctx.rxRcvdLen = rxRcvdLen; - gRFAL.TxRx.ctx.fwt = fwt; - - /*******************************************************************************/ - /* Load NRT with FWT */ - st25r3916SetNoResponseTime(rfalConv1fcTo64fc( - MIN((fwt + RFAL_FWT_ADJUSTMENT + RFAL_FWT_A_ADJUSTMENT), RFAL_ST25R3916_NRT_MAX_1FC))); - - if(gRFAL.timings.FDTListen != RFAL_TIMING_NONE) { - /* Ensure that MRT is using 64/fc steps */ - st25r3916ClrRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, ST25R3916_REG_TIMER_EMV_CONTROL_mrt_step); - - /* Set Minimum FDT(Listen) in which PICC is not allowed to send a response */ - st25r3916WriteRegister( - ST25R3916_REG_MASK_RX_TIMER, - (uint8_t)rfalConv1fcTo64fc( - ((RFAL_FDT_LISTEN_MRT_ADJUSTMENT + RFAL_FDT_LISTEN_A_ADJUSTMENT) > - gRFAL.timings.FDTListen) ? - RFAL_ST25R3916_MRT_MIN_1FC : - (gRFAL.timings.FDTListen - - (RFAL_FDT_LISTEN_MRT_ADJUSTMENT + RFAL_FDT_LISTEN_A_ADJUSTMENT)))); - } - - /* In Passive communications General Purpose Timer is used to measure FDT Poll */ - if(gRFAL.timings.FDTPoll != RFAL_TIMING_NONE) { - /* Configure GPT to start at RX end */ - st25r3916SetStartGPTimer( - (uint16_t)rfalConv1fcTo8fc( - MIN(gRFAL.timings.FDTPoll, (gRFAL.timings.FDTPoll - RFAL_FDT_POLL_ADJUSTMENT))), - ST25R3916_REG_TIMER_EMV_CONTROL_gptc_erx); - } - - /*******************************************************************************/ - rfalPrepareTransceive(); - - /* Also enable bit collision interrupt */ - st25r3916GetInterrupt(ST25R3916_IRQ_MASK_COL); - st25r3916EnableInterrupts(ST25R3916_IRQ_MASK_COL); - - /*Check if Observation Mode is enabled and set it on ST25R391x */ - rfalCheckEnableObsModeTx(); - - /*******************************************************************************/ - /* Clear nbtx bits before sending WUPA/REQA - otherwise ST25R3916 will report parity error, Note2 of the register */ - st25r3916WriteRegister(ST25R3916_REG_NUM_TX_BYTES2, 0); - - /* Send either WUPA or REQA. All affected tags will backscatter ATQA and change to READY state */ - st25r3916ExecuteCommand(directCmd); - - /* Wait for TXE */ - if(st25r3916WaitForInterruptsTimed( - ST25R3916_IRQ_MASK_TXE, - (uint16_t)MAX(rfalConv1fcToMs(fwt), RFAL_ST25R3916_SW_TMR_MIN_1MS)) == 0U) { - ret = ERR_IO; - } else { - /*Check if Observation Mode is enabled and set it on ST25R391x */ - rfalCheckEnableObsModeRx(); - - /* Jump into a transceive Rx state for reception (bypass Tx states) */ - gRFAL.state = RFAL_STATE_TXRX; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_IDLE; - gRFAL.TxRx.status = ERR_BUSY; - - /* Execute Transceive Rx blocking */ - ret = rfalTransceiveBlockingRx(); - } - - /* Disable Collision interrupt */ - st25r3916DisableInterrupts((ST25R3916_IRQ_MASK_COL)); - - /* ReEnable CRC on Rx */ - st25r3916ClrRegisterBits(ST25R3916_REG_AUX, ST25R3916_REG_AUX_no_crc_rx); - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalISO14443ATransceiveAnticollisionFrame( - uint8_t* buf, - uint8_t* bytesToSend, - uint8_t* bitsToSend, - uint16_t* rxLength, - uint32_t fwt) { - ReturnCode ret; - rfalTransceiveContext ctx; - uint8_t collByte; - uint8_t collData; - - /* Check if RFAL is properly initialized */ - if((gRFAL.state < RFAL_STATE_MODE_SET) || (gRFAL.mode != RFAL_MODE_POLL_NFCA)) { - return ERR_WRONG_STATE; - } - - /* Check for valid parameters */ - if((buf == NULL) || (bytesToSend == NULL) || (bitsToSend == NULL) || (rxLength == NULL)) { - return ERR_PARAM; - } - - /*******************************************************************************/ - /* Set specific Analog Config for Anticolission if needed */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_ANTICOL)); - - /*******************************************************************************/ - /* Enable anti collision to recognise collision in first byte of SENS_REQ */ - st25r3916SetRegisterBits(ST25R3916_REG_ISO14443A_NFC, ST25R3916_REG_ISO14443A_NFC_antcl); - - /* Disable CRC while receiving */ - st25r3916SetRegisterBits(ST25R3916_REG_AUX, ST25R3916_REG_AUX_no_crc_rx); - - /*******************************************************************************/ - /* Prepare for Transceive */ - ctx.flags = ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP); - ctx.txBuf = buf; - ctx.txBufLen = (uint16_t)(rfalConvBytesToBits(*bytesToSend) + *bitsToSend); - ctx.rxBuf = &buf[*bytesToSend]; - ctx.rxBufLen = (uint16_t)rfalConvBytesToBits(RFAL_ISO14443A_SDD_RES_LEN); - ctx.rxRcvdLen = rxLength; - ctx.fwt = fwt; - - /* Disable Automatic Gain Control (AGC) for better detection of collisions if using Coherent Receiver */ - ctx.flags |= - (st25r3916CheckReg( - ST25R3916_REG_AUX, ST25R3916_REG_AUX_dis_corr, ST25R3916_REG_AUX_dis_corr) ? - (uint32_t)RFAL_TXRX_FLAGS_AGC_OFF : - 0x00U); - - rfalStartTransceive(&ctx); - - /* Additionally enable bit collision interrupt */ - st25r3916GetInterrupt(ST25R3916_IRQ_MASK_COL); - st25r3916EnableInterrupts(ST25R3916_IRQ_MASK_COL); - - /*******************************************************************************/ - collByte = 0; - - /* save the collision byte */ - if((*bitsToSend) > 0U) { - buf[(*bytesToSend)] <<= (RFAL_BITS_IN_BYTE - (*bitsToSend)); - buf[(*bytesToSend)] >>= (RFAL_BITS_IN_BYTE - (*bitsToSend)); - collByte = buf[(*bytesToSend)]; - } - - /*******************************************************************************/ - /* Run Transceive blocking */ - ret = rfalTransceiveRunBlockingTx(); - if(ret == ERR_NONE) { - ret = rfalTransceiveBlockingRx(); - - /*******************************************************************************/ - if((*bitsToSend) > 0U) { - buf[(*bytesToSend)] >>= (*bitsToSend); - buf[(*bytesToSend)] <<= (*bitsToSend); - buf[(*bytesToSend)] |= collByte; - } - - if((ERR_RF_COLLISION == ret)) { - /* read out collision register */ - st25r3916ReadRegister(ST25R3916_REG_COLLISION_STATUS, &collData); - - (*bytesToSend) = - ((collData >> ST25R3916_REG_COLLISION_STATUS_c_byte_shift) & - 0x0FU); // 4-bits Byte information - (*bitsToSend) = - ((collData >> ST25R3916_REG_COLLISION_STATUS_c_bit_shift) & - 0x07U); // 3-bits bit information - } - } - - /*******************************************************************************/ - /* Disable Collision interrupt */ - st25r3916DisableInterrupts((ST25R3916_IRQ_MASK_COL)); - - /* Disable anti collision again */ - st25r3916ClrRegisterBits(ST25R3916_REG_ISO14443A_NFC, ST25R3916_REG_ISO14443A_NFC_antcl); - - /* ReEnable CRC on Rx */ - st25r3916ClrRegisterBits(ST25R3916_REG_AUX, ST25R3916_REG_AUX_no_crc_rx); - /*******************************************************************************/ - - /* Restore common Analog configurations for this mode */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | rfalConvBR2ACBR(gRFAL.txBR) | - RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCA | rfalConvBR2ACBR(gRFAL.rxBR) | - RFAL_ANALOG_CONFIG_RX)); - - return ret; -} - -#endif /* RFAL_FEATURE_NFCA */ - -#if RFAL_FEATURE_NFCV - -/*******************************************************************************/ -ReturnCode rfalISO15693TransceiveAnticollisionFrame( - uint8_t* txBuf, - uint8_t txBufLen, - uint8_t* rxBuf, - uint8_t rxBufLen, - uint16_t* actLen) { - ReturnCode ret; - rfalTransceiveContext ctx; - - /* Check if RFAL is properly initialized */ - if((gRFAL.state < RFAL_STATE_MODE_SET) || (gRFAL.mode != RFAL_MODE_POLL_NFCV)) { - return ERR_WRONG_STATE; - } - - /*******************************************************************************/ - /* Set specific Analog Config for Anticolission if needed */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | - RFAL_ANALOG_CONFIG_BITRATE_COMMON | RFAL_ANALOG_CONFIG_ANTICOL)); - - /* Ignoring collisions before the UID (RES_FLAG + DSFID) */ - gRFAL.nfcvData.ignoreBits = (uint16_t)RFAL_ISO15693_IGNORE_BITS; - - /*******************************************************************************/ - /* Prepare for Transceive */ - ctx.flags = - ((txBufLen == 0U) ? (uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL : - (uint32_t)RFAL_TXRX_FLAGS_CRC_TX_AUTO) | - (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP | (uint32_t)RFAL_TXRX_FLAGS_AGC_OFF | - ((txBufLen == 0U) ? - (uint32_t)RFAL_TXRX_FLAGS_NFCV_FLAG_MANUAL : - (uint32_t) - RFAL_TXRX_FLAGS_NFCV_FLAG_AUTO); /* Disable Automatic Gain Control (AGC) for better detection of collision */ - ctx.txBuf = txBuf; - ctx.txBufLen = (uint16_t)rfalConvBytesToBits(txBufLen); - ctx.rxBuf = rxBuf; - ctx.rxBufLen = (uint16_t)rfalConvBytesToBits(rxBufLen); - ctx.rxRcvdLen = actLen; - ctx.fwt = rfalConv64fcTo1fc(ISO15693_FWT); - - rfalStartTransceive(&ctx); - - /*******************************************************************************/ - /* Run Transceive blocking */ - ret = rfalTransceiveRunBlockingTx(); - if(ret == ERR_NONE) { - ret = rfalTransceiveBlockingRx(); - } - - /* Check if a Transmission error and received data is less then expected */ - if(((ret == ERR_RF_COLLISION) || (ret == ERR_CRC) || (ret == ERR_FRAMING)) && - (rfalConvBitsToBytes(*ctx.rxRcvdLen) < RFAL_ISO15693_INV_RES_LEN)) { - /* If INVENTORY_RES is shorter than expected, tag is still modulating * - * Ensure that response is complete before next frame */ - platformDelay(( - uint8_t)((RFAL_ISO15693_INV_RES_LEN - rfalConvBitsToBytes(*ctx.rxRcvdLen)) / ((RFAL_ISO15693_INV_RES_LEN / RFAL_ISO15693_INV_RES_DUR) + 1U))); - } - - /* Restore common Analog configurations for this mode */ - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | rfalConvBR2ACBR(gRFAL.txBR) | - RFAL_ANALOG_CONFIG_TX)); - rfalSetAnalogConfig( - (RFAL_ANALOG_CONFIG_POLL | RFAL_ANALOG_CONFIG_TECH_NFCV | rfalConvBR2ACBR(gRFAL.rxBR) | - RFAL_ANALOG_CONFIG_RX)); - - gRFAL.nfcvData.ignoreBits = 0; - return ret; -} - -/*******************************************************************************/ -ReturnCode - rfalISO15693TransceiveEOFAnticollision(uint8_t* rxBuf, uint8_t rxBufLen, uint16_t* actLen) { - uint8_t dummy; - - return rfalISO15693TransceiveAnticollisionFrame(&dummy, 0, rxBuf, rxBufLen, actLen); -} - -/*******************************************************************************/ -ReturnCode rfalISO15693TransceiveEOF(uint8_t* rxBuf, uint8_t rxBufLen, uint16_t* actLen) { - ReturnCode ret; - uint8_t dummy; - - /* Check if RFAL is properly initialized */ - if((gRFAL.state < RFAL_STATE_MODE_SET) || (gRFAL.mode != RFAL_MODE_POLL_NFCV)) { - return ERR_WRONG_STATE; - } - - /*******************************************************************************/ - /* Run Transceive blocking */ - ret = rfalTransceiveBlockingTxRx( - &dummy, - 0, - rxBuf, - rxBufLen, - actLen, - ((uint32_t)RFAL_TXRX_FLAGS_CRC_TX_MANUAL | (uint32_t)RFAL_TXRX_FLAGS_CRC_RX_KEEP | - (uint32_t)RFAL_TXRX_FLAGS_AGC_ON), - rfalConv64fcTo1fc(ISO15693_FWT)); - return ret; -} - -#endif /* RFAL_FEATURE_NFCV */ - -#if RFAL_FEATURE_NFCF - -/*******************************************************************************/ -ReturnCode rfalFeliCaPoll( - rfalFeliCaPollSlots slots, - uint16_t sysCode, - uint8_t reqCode, - rfalFeliCaPollRes* pollResList, - uint8_t pollResListSize, - uint8_t* devicesDetected, - uint8_t* collisionsDetected) { - ReturnCode ret; - uint8_t frame - [RFAL_FELICA_POLL_REQ_LEN - RFAL_FELICA_LEN_LEN]; // LEN is added by ST25R391x automatically - uint16_t actLen; - uint8_t frameIdx; - uint8_t devDetected; - uint8_t colDetected; - rfalEHandling curHandling; - uint8_t nbSlots; - - /* Check if RFAL is properly initialized */ - if((gRFAL.state < RFAL_STATE_MODE_SET) || (gRFAL.mode != RFAL_MODE_POLL_NFCF)) { - return ERR_WRONG_STATE; - } - - frameIdx = 0; - colDetected = 0; - devDetected = 0; - nbSlots = (uint8_t)slots; - - /*******************************************************************************/ - /* Compute SENSF_REQ frame */ - frame[frameIdx++] = (uint8_t)FELICA_CMD_POLLING; /* CMD: SENF_REQ */ - frame[frameIdx++] = (uint8_t)(sysCode >> 8); /* System Code (SC) */ - frame[frameIdx++] = (uint8_t)(sysCode & 0xFFU); /* System Code (SC) */ - frame[frameIdx++] = reqCode; /* Communication Parameter Request (RC)*/ - frame[frameIdx++] = nbSlots; /* TimeSlot (TSN) */ - - /*******************************************************************************/ - /* NRT should not stop on reception - Use EMVCo mode to run NRT in nrt_emv * - * ERRORHANDLING_EMVCO has no special handling for NFC-F mode */ - curHandling = gRFAL.conf.eHandling; - rfalSetErrorHandling(RFAL_ERRORHANDLING_EMVCO); - - /*******************************************************************************/ - /* Run transceive blocking, - * Calculate Total Response Time in(64/fc): - * 512 PICC process time + (n * 256 Time Slot duration) */ - ret = rfalTransceiveBlockingTx( - frame, - (uint16_t)frameIdx, - (uint8_t*)gRFAL.nfcfData.pollResponses, - RFAL_FELICA_POLL_RES_LEN, - &actLen, - (RFAL_TXRX_FLAGS_DEFAULT), - rfalConv64fcTo1fc( - RFAL_FELICA_POLL_DELAY_TIME + - (RFAL_FELICA_POLL_SLOT_TIME * ((uint32_t)nbSlots + 1U)))); - - /*******************************************************************************/ - /* If Tx OK, Wait for all responses, store them as soon as they appear */ - if(ret == ERR_NONE) { - bool timeout; - - do { - ret = rfalTransceiveBlockingRx(); - if(ret == ERR_TIMEOUT) { - /* Upon timeout the full Poll Delay + (Slot time)*(nbSlots) has expired */ - timeout = true; - } else { - /* Reception done, reEnabled Rx for following Slot */ - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - st25r3916ExecuteCommand(ST25R3916_CMD_RESET_RXGAIN); - - /* If the reception was OK, new device found */ - if(ret == ERR_NONE) { - devDetected++; - - /* Overwrite the Transceive context for the next reception */ - gRFAL.TxRx.ctx.rxBuf = (uint8_t*)gRFAL.nfcfData.pollResponses[devDetected]; - } - /* If the reception was not OK, mark as collision */ - else { - colDetected++; - } - - /* Check whether NRT has expired meanwhile */ - timeout = st25r3916CheckReg( - ST25R3916_REG_NFCIP1_BIT_RATE, ST25R3916_REG_NFCIP1_BIT_RATE_nrt_on, 0x00); - if(!timeout) { - /* Jump again into transceive Rx state for the following reception */ - gRFAL.TxRx.status = ERR_BUSY; - gRFAL.state = RFAL_STATE_TXRX; - gRFAL.TxRx.state = RFAL_TXRX_STATE_RX_IDLE; - } - } - } while(((nbSlots--) != 0U) && !timeout); - } - - /*******************************************************************************/ - /* Restore NRT to normal mode - back to previous error handling */ - rfalSetErrorHandling(curHandling); - - /*******************************************************************************/ - /* Assign output parameters if requested */ - - if((pollResList != NULL) && (pollResListSize > 0U) && (devDetected > 0U)) { - ST_MEMCPY( - pollResList, - gRFAL.nfcfData.pollResponses, - (RFAL_FELICA_POLL_RES_LEN * (uint32_t)MIN(pollResListSize, devDetected))); - } - - if(devicesDetected != NULL) { - *devicesDetected = devDetected; - } - - if(collisionsDetected != NULL) { - *collisionsDetected = colDetected; - } - - return (((colDetected != 0U) || (devDetected != 0U)) ? ERR_NONE : ret); -} - -#endif /* RFAL_FEATURE_NFCF */ - -/***************************************************************************** - * Listen Mode * - *****************************************************************************/ - -/*******************************************************************************/ -bool rfalIsExtFieldOn(void) { - return st25r3916IsExtFieldOn(); -} - -#if RFAL_FEATURE_LISTEN_MODE - -/*******************************************************************************/ -ReturnCode rfalListenStart( - uint32_t lmMask, - const rfalLmConfPA* confA, - const rfalLmConfPB* confB, - const rfalLmConfPF* confF, - uint8_t* rxBuf, - uint16_t rxBufLen, - uint16_t* rxLen) { - t_rfalPTMem - PTMem; /* PRQA S 0759 # MISRA 19.2 - Allocating Union where members are of the same type, just different names. Thus no problem can occur. */ - uint8_t* pPTMem; - uint8_t autoResp; - - /* Check if RFAL is initialized */ - if(gRFAL.state < RFAL_STATE_INIT) { - return ERR_WRONG_STATE; - } - - gRFAL.Lm.state = RFAL_LM_STATE_NOT_INIT; - gRFAL.Lm.mdIrqs = ST25R3916_IRQ_MASK_NONE; - gRFAL.Lm.mdReg = - (ST25R3916_REG_MODE_targ_init | ST25R3916_REG_MODE_om_nfc | ST25R3916_REG_MODE_nfc_ar_off); - - /* By default disable all automatic responses */ - autoResp = - (ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a | ST25R3916_REG_PASSIVE_TARGET_rfu | - ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r | ST25R3916_REG_PASSIVE_TARGET_d_ac_ap2p); - - /*******************************************************************************/ - if((lmMask & RFAL_LM_MASK_NFCA) != 0U) { - /* Check if the conf has been provided */ - if(confA == NULL) { - return ERR_PARAM; - } - - pPTMem = (uint8_t*)PTMem.PTMem_A; - - /*******************************************************************************/ - /* Check and set supported NFCID Length */ - switch(confA->nfcidLen) { - case RFAL_LM_NFCID_LEN_04: - st25r3916ChangeRegisterBits( - ST25R3916_REG_AUX, ST25R3916_REG_AUX_nfc_id_mask, ST25R3916_REG_AUX_nfc_id_4bytes); - break; - - case RFAL_LM_NFCID_LEN_07: - st25r3916ChangeRegisterBits( - ST25R3916_REG_AUX, ST25R3916_REG_AUX_nfc_id_mask, ST25R3916_REG_AUX_nfc_id_7bytes); - break; - - default: - return ERR_PARAM; - } - - /*******************************************************************************/ - /* Set NFCID */ - ST_MEMCPY(pPTMem, confA->nfcid, RFAL_NFCID1_TRIPLE_LEN); - pPTMem = &pPTMem[RFAL_NFCID1_TRIPLE_LEN]; /* MISRA 18.4 */ - - /* Set SENS_RES */ - ST_MEMCPY(pPTMem, confA->SENS_RES, RFAL_LM_SENS_RES_LEN); - pPTMem = &pPTMem[RFAL_LM_SENS_RES_LEN]; /* MISRA 18.4 */ - - /* Set SEL_RES */ - *pPTMem++ = - ((confA->nfcidLen == RFAL_LM_NFCID_LEN_04) ? - (confA->SEL_RES & ~RFAL_LM_NFCID_INCOMPLETE) : - (confA->SEL_RES | RFAL_LM_NFCID_INCOMPLETE)); - *pPTMem++ = (confA->SEL_RES & ~RFAL_LM_NFCID_INCOMPLETE); - *pPTMem++ = (confA->SEL_RES & ~RFAL_LM_NFCID_INCOMPLETE); - - /* Write into PTMem-A */ - st25r3916WritePTMem(PTMem.PTMem_A, ST25R3916_PTM_A_LEN); - - /*******************************************************************************/ - /* Enable automatic responses for A */ - autoResp &= ~ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a; - - /* Set Target mode, Bit Rate detection and Listen Mode for NFC-F */ - gRFAL.Lm.mdReg |= - (ST25R3916_REG_MODE_targ_targ | ST25R3916_REG_MODE_om3 | ST25R3916_REG_MODE_om0 | - ST25R3916_REG_MODE_nfc_ar_off); - - gRFAL.Lm.mdIrqs |= - (ST25R3916_IRQ_MASK_WU_A | ST25R3916_IRQ_MASK_WU_A_X | ST25R3916_IRQ_MASK_RXE_PTA); - } - - /*******************************************************************************/ - if((lmMask & RFAL_LM_MASK_NFCB) != 0U) { - /* Check if the conf has been provided */ - if(confB == NULL) { - return ERR_PARAM; - } - - return ERR_NOTSUPP; - } - - /*******************************************************************************/ - if((lmMask & RFAL_LM_MASK_NFCF) != 0U) { - pPTMem = (uint8_t*)PTMem.PTMem_F; - - /* Check if the conf has been provided */ - if(confF == NULL) { - return ERR_PARAM; - } - - /*******************************************************************************/ - /* Set System Code */ - ST_MEMCPY(pPTMem, confF->SC, RFAL_LM_SENSF_SC_LEN); - pPTMem = &pPTMem[RFAL_LM_SENSF_SC_LEN]; /* MISRA 18.4 */ - - /* Set SENSF_RES */ - ST_MEMCPY(pPTMem, confF->SENSF_RES, RFAL_LM_SENSF_RES_LEN); - - /* Set RD bytes to 0x00 as ST25R3916 cannot support advances features */ - pPTMem[RFAL_LM_SENSF_RD0_POS] = - 0x00; /* NFC Forum Digital 1.1 Table 46: 0x00 */ - pPTMem[RFAL_LM_SENSF_RD1_POS] = - 0x00; /* NFC Forum Digital 1.1 Table 47: No automatic bit rates */ - - pPTMem = &pPTMem[RFAL_LM_SENS_RES_LEN]; /* MISRA 18.4 */ - - /* Write into PTMem-F */ - st25r3916WritePTMemF(PTMem.PTMem_F, ST25R3916_PTM_F_LEN); - - /*******************************************************************************/ - /* Write 24 TSN "Random" Numbers at first initialization and let it rollover */ - if(!gRFAL.Lm.iniFlag) { - pPTMem = (uint8_t*)PTMem.TSN; - - *pPTMem++ = 0x12; - *pPTMem++ = 0x34; - *pPTMem++ = 0x56; - *pPTMem++ = 0x78; - *pPTMem++ = 0x9A; - *pPTMem++ = 0xBC; - *pPTMem++ = 0xDF; - *pPTMem++ = 0x21; - *pPTMem++ = 0x43; - *pPTMem++ = 0x65; - *pPTMem++ = 0x87; - *pPTMem++ = 0xA9; - - /* Write into PTMem-TSN */ - st25r3916WritePTMemTSN(PTMem.TSN, ST25R3916_PTM_TSN_LEN); - } - - /*******************************************************************************/ - /* Enable automatic responses for F */ - autoResp &= ~(ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r); - - /* Set Target mode, Bit Rate detection and Listen Mode for NFC-F */ - gRFAL.Lm.mdReg |= - (ST25R3916_REG_MODE_targ_targ | ST25R3916_REG_MODE_om3 | ST25R3916_REG_MODE_om2 | - ST25R3916_REG_MODE_nfc_ar_off); - - /* In CE NFC-F any data without error will be passed to FIFO, to support CUP */ - gRFAL.Lm.mdIrqs |= - (ST25R3916_IRQ_MASK_WU_F | ST25R3916_IRQ_MASK_RXE_PTA | ST25R3916_IRQ_MASK_RXE); - } - - /*******************************************************************************/ - if((lmMask & RFAL_LM_MASK_ACTIVE_P2P) != 0U) { - /* Enable Reception of P2P frames */ - autoResp &= ~(ST25R3916_REG_PASSIVE_TARGET_d_ac_ap2p); - - /* Set Target mode, Bit Rate detection and Automatic Response RF Collision Avoidance */ - gRFAL.Lm.mdReg |= - (ST25R3916_REG_MODE_targ_targ | ST25R3916_REG_MODE_om3 | ST25R3916_REG_MODE_om2 | - ST25R3916_REG_MODE_om0 | ST25R3916_REG_MODE_nfc_ar_auto_rx); - - /* n * TRFW timing shall vary Activity 2.1 3.4.1.1 */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_AUX, ST25R3916_REG_AUX_nfc_n_mask, gRFAL.timings.nTRFW); - gRFAL.timings.nTRFW = rfalGennTRFW(gRFAL.timings.nTRFW); - - gRFAL.Lm.mdIrqs |= (ST25R3916_IRQ_MASK_RXE); - } - - /* Check if one of the modes were selected */ - if((gRFAL.Lm.mdReg & ST25R3916_REG_MODE_targ) == ST25R3916_REG_MODE_targ_targ) { - gRFAL.state = RFAL_STATE_LM; - gRFAL.Lm.mdMask = lmMask; - - gRFAL.Lm.rxBuf = rxBuf; - gRFAL.Lm.rxBufLen = rxBufLen; - gRFAL.Lm.rxLen = rxLen; - *gRFAL.Lm.rxLen = 0; - gRFAL.Lm.dataFlag = false; - gRFAL.Lm.iniFlag = true; - - /* Apply the Automatic Responses configuration */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, - (ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a | ST25R3916_REG_PASSIVE_TARGET_rfu | - ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r | ST25R3916_REG_PASSIVE_TARGET_d_ac_ap2p), - autoResp); - - /* Disable GPT trigger source */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, - ST25R3916_REG_TIMER_EMV_CONTROL_gptc_mask, - ST25R3916_REG_TIMER_EMV_CONTROL_gptc_no_trigger); - - /* On Bit Rate Detection Mode ST25R391x will filter incoming frames during MRT time starting on External Field On event, use 512/fc steps */ - st25r3916SetRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, ST25R3916_REG_TIMER_EMV_CONTROL_mrt_step_512); - st25r3916WriteRegister( - ST25R3916_REG_MASK_RX_TIMER, (uint8_t)rfalConv1fcTo512fc(RFAL_LM_GT)); - - /* Restore default settings on NFCIP1 mode, Receiving parity + CRC bits and manual Tx Parity*/ - st25r3916ClrRegisterBits( - ST25R3916_REG_ISO14443A_NFC, - (ST25R3916_REG_ISO14443A_NFC_no_tx_par | ST25R3916_REG_ISO14443A_NFC_no_rx_par | - ST25R3916_REG_ISO14443A_NFC_nfc_f0)); - - /* External Field Detector enabled as Automatics on rfalInitialize() */ - - /* Set Analog configurations for generic Listen mode */ - /* Not on SetState(POWER OFF) as otherwise would be applied on every Field Event */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_LISTEN_ON)); - - /* Initialize as POWER_OFF and set proper mode in RF Chip */ - rfalListenSetState(RFAL_LM_STATE_POWER_OFF); - } else { - return ERR_REQUEST; /* Listen Start called but no mode was enabled */ - } - - return ERR_NONE; -} - -/*******************************************************************************/ -static ReturnCode rfalRunListenModeWorker(void) { - volatile uint32_t irqs; - uint8_t tmp; - - if(gRFAL.state != RFAL_STATE_LM) { - return ERR_WRONG_STATE; - } - - switch(gRFAL.Lm.state) { - /*******************************************************************************/ - case RFAL_LM_STATE_POWER_OFF: - - irqs = st25r3916GetInterrupt((ST25R3916_IRQ_MASK_EON)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_EON) != 0U) { - rfalListenSetState(RFAL_LM_STATE_IDLE); - } else { - break; - } - /* fall through */ - - /*******************************************************************************/ - case RFAL_LM_STATE_IDLE: /* PRQA S 2003 # MISRA 16.3 - Intentional fall through */ - - irqs = st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_NFCT | ST25R3916_IRQ_MASK_WU_F | ST25R3916_IRQ_MASK_RXE | - ST25R3916_IRQ_MASK_EOF | ST25R3916_IRQ_MASK_RXE_PTA)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_NFCT) != 0U) { - /* Retrieve detected bitrate */ - uint8_t newBr; - st25r3916ReadRegister(ST25R3916_REG_NFCIP1_BIT_RATE, &newBr); - newBr >>= ST25R3916_REG_NFCIP1_BIT_RATE_nfc_rate_shift; - - if(newBr > ST25R3916_REG_BIT_RATE_rxrate_424) { - newBr = ST25R3916_REG_BIT_RATE_rxrate_424; - } - - gRFAL.Lm.brDetected = - (rfalBitRate)(newBr); /* PRQA S 4342 # MISRA 10.5 - Guaranteed that no invalid enum values may be created. See also equalityGuard_RFAL_BR_106 ff.*/ - } - - if(((irqs & ST25R3916_IRQ_MASK_WU_F) != 0U) && (gRFAL.Lm.brDetected != RFAL_BR_KEEP)) { - rfalListenSetState(RFAL_LM_STATE_READY_F); - } else if(((irqs & ST25R3916_IRQ_MASK_RXE) != 0U) && (gRFAL.Lm.brDetected != RFAL_BR_KEEP)) { - irqs = st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_WU_F | ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_EOF | - ST25R3916_IRQ_MASK_CRC | ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_ERR2 | - ST25R3916_IRQ_MASK_ERR1)); - - if(((irqs & ST25R3916_IRQ_MASK_CRC) != 0U) || - ((irqs & ST25R3916_IRQ_MASK_PAR) != 0U) || - ((irqs & ST25R3916_IRQ_MASK_ERR1) != 0U)) { - st25r3916ExecuteCommand(ST25R3916_CMD_CLEAR_FIFO); - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - st25r3916TxOff(); - break; /* A bad reception occurred, remain in same state */ - } - - /* Retrieve received data */ - *gRFAL.Lm.rxLen = st25r3916GetNumFIFOBytes(); - st25r3916ReadFifo( - gRFAL.Lm.rxBuf, MIN(*gRFAL.Lm.rxLen, rfalConvBitsToBytes(gRFAL.Lm.rxBufLen))); - - /*******************************************************************************/ - /* REMARK: Silicon workaround ST25R3916 Errata #TBD */ - /* In bitrate detection mode CRC is now checked for NFC-A frames */ - if((*gRFAL.Lm.rxLen > RFAL_CRC_LEN) && (gRFAL.Lm.brDetected == RFAL_BR_106)) { - if(rfalCrcCalculateCcitt( - RFAL_ISO14443A_CRC_INTVAL, gRFAL.Lm.rxBuf, *gRFAL.Lm.rxLen) != 0U) { - st25r3916ExecuteCommand(ST25R3916_CMD_CLEAR_FIFO); - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - st25r3916TxOff(); - break; /* A bad reception occurred, remain in same state */ - } - } - /*******************************************************************************/ - - /* Check if the data we got has at least the CRC and remove it, otherwise leave at 0 */ - *gRFAL.Lm.rxLen -= ((*gRFAL.Lm.rxLen > RFAL_CRC_LEN) ? RFAL_CRC_LEN : *gRFAL.Lm.rxLen); - *gRFAL.Lm.rxLen = (uint16_t)rfalConvBytesToBits(*gRFAL.Lm.rxLen); - gRFAL.Lm.dataFlag = true; - - /*Check if Observation Mode was enabled and disable it on ST25R391x */ - rfalCheckDisableObsMode(); - } else if( - ((irqs & ST25R3916_IRQ_MASK_RXE_PTA) != 0U) && (gRFAL.Lm.brDetected != RFAL_BR_KEEP)) { - if(((gRFAL.Lm.mdMask & RFAL_LM_MASK_NFCA) != 0U) && - (gRFAL.Lm.brDetected == RFAL_BR_106)) { - st25r3916ReadRegister(ST25R3916_REG_PASSIVE_TARGET_STATUS, &tmp); - if(tmp > ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_idle) { - rfalListenSetState(RFAL_LM_STATE_READY_A); - } - } - } else if(((irqs & ST25R3916_IRQ_MASK_EOF) != 0U) && (!gRFAL.Lm.dataFlag)) { - rfalListenSetState(RFAL_LM_STATE_POWER_OFF); - } else { - /* MISRA 15.7 - Empty else */ - } - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_READY_F: - - irqs = st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_WU_F | ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_EOF)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_WU_F) != 0U) { - break; - } else if((irqs & ST25R3916_IRQ_MASK_RXE) != 0U) { - /* Retrieve the error flags/irqs */ - irqs |= st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_CRC | ST25R3916_IRQ_MASK_ERR2 | ST25R3916_IRQ_MASK_ERR1)); - - if(((irqs & ST25R3916_IRQ_MASK_CRC) != 0U) || - ((irqs & ST25R3916_IRQ_MASK_ERR1) != 0U)) { - st25r3916ExecuteCommand(ST25R3916_CMD_CLEAR_FIFO); - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - break; /* A bad reception occurred, remain in same state */ - } - - /* Retrieve received data */ - *gRFAL.Lm.rxLen = st25r3916GetNumFIFOBytes(); - st25r3916ReadFifo( - gRFAL.Lm.rxBuf, MIN(*gRFAL.Lm.rxLen, rfalConvBitsToBytes(gRFAL.Lm.rxBufLen))); - - /* Check if the data we got has at least the CRC and remove it, otherwise leave at 0 */ - *gRFAL.Lm.rxLen -= ((*gRFAL.Lm.rxLen > RFAL_CRC_LEN) ? RFAL_CRC_LEN : *gRFAL.Lm.rxLen); - *gRFAL.Lm.rxLen = (uint16_t)rfalConvBytesToBits(*gRFAL.Lm.rxLen); - gRFAL.Lm.dataFlag = true; - } else if((irqs & ST25R3916_IRQ_MASK_EOF) != 0U) { - rfalListenSetState(RFAL_LM_STATE_POWER_OFF); - } else { - /* MISRA 15.7 - Empty else */ - } - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_READY_A: - - irqs = st25r3916GetInterrupt((ST25R3916_IRQ_MASK_EOF | ST25R3916_IRQ_MASK_WU_A)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_WU_A) != 0U) { - rfalListenSetState(RFAL_LM_STATE_ACTIVE_A); - } else if((irqs & ST25R3916_IRQ_MASK_EOF) != 0U) { - rfalListenSetState(RFAL_LM_STATE_POWER_OFF); - } else { - /* MISRA 15.7 - Empty else */ - } - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_ACTIVE_A: - case RFAL_LM_STATE_ACTIVE_Ax: - - irqs = st25r3916GetInterrupt((ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_EOF)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_RXE) != 0U) { - /* Retrieve the error flags/irqs */ - irqs |= st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_CRC | ST25R3916_IRQ_MASK_ERR2 | - ST25R3916_IRQ_MASK_ERR1)); - *gRFAL.Lm.rxLen = st25r3916GetNumFIFOBytes(); - - if(((irqs & ST25R3916_IRQ_MASK_CRC) != 0U) || - ((irqs & ST25R3916_IRQ_MASK_ERR1) != 0U) || - ((irqs & ST25R3916_IRQ_MASK_PAR) != 0U) || (*gRFAL.Lm.rxLen <= RFAL_CRC_LEN)) { - /* Clear rx context and FIFO */ - *gRFAL.Lm.rxLen = 0; - st25r3916ExecuteCommand(ST25R3916_CMD_CLEAR_FIFO); - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - - /* Check if we should go to IDLE or Sleep */ - if(gRFAL.Lm.state == RFAL_LM_STATE_ACTIVE_Ax) { - rfalListenSleepStart( - RFAL_LM_STATE_SLEEP_A, gRFAL.Lm.rxBuf, gRFAL.Lm.rxBufLen, gRFAL.Lm.rxLen); - } else { - rfalListenSetState(RFAL_LM_STATE_IDLE); - } - - st25r3916DisableInterrupts(ST25R3916_IRQ_MASK_RXE); - break; - } - - /* Remove CRC from length */ - *gRFAL.Lm.rxLen -= RFAL_CRC_LEN; - - /* Retrieve received data */ - st25r3916ReadFifo( - gRFAL.Lm.rxBuf, MIN(*gRFAL.Lm.rxLen, rfalConvBitsToBytes(gRFAL.Lm.rxBufLen))); - *gRFAL.Lm.rxLen = (uint16_t)rfalConvBytesToBits(*gRFAL.Lm.rxLen); - gRFAL.Lm.dataFlag = true; - } else if((irqs & ST25R3916_IRQ_MASK_EOF) != 0U) { - rfalListenSetState(RFAL_LM_STATE_POWER_OFF); - } else { - /* MISRA 15.7 - Empty else */ - } - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_SLEEP_A: - case RFAL_LM_STATE_SLEEP_B: - case RFAL_LM_STATE_SLEEP_AF: - - irqs = st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_NFCT | ST25R3916_IRQ_MASK_WU_F | ST25R3916_IRQ_MASK_RXE | - ST25R3916_IRQ_MASK_EOF | ST25R3916_IRQ_MASK_RXE_PTA)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_NFCT) != 0U) { - uint8_t newBr; - /* Retrieve detected bitrate */ - st25r3916ReadRegister(ST25R3916_REG_NFCIP1_BIT_RATE, &newBr); - newBr >>= ST25R3916_REG_NFCIP1_BIT_RATE_nfc_rate_shift; - - if(newBr > ST25R3916_REG_BIT_RATE_rxrate_424) { - newBr = ST25R3916_REG_BIT_RATE_rxrate_424; - } - - gRFAL.Lm.brDetected = - (rfalBitRate)(newBr); /* PRQA S 4342 # MISRA 10.5 - Guaranteed that no invalid enum values may be created. See also equalityGuard_RFAL_BR_106 ff.*/ - } - - if(((irqs & ST25R3916_IRQ_MASK_WU_F) != 0U) && (gRFAL.Lm.brDetected != RFAL_BR_KEEP)) { - rfalListenSetState(RFAL_LM_STATE_READY_F); - } else if(((irqs & ST25R3916_IRQ_MASK_RXE) != 0U) && (gRFAL.Lm.brDetected != RFAL_BR_KEEP)) { - /* Clear rx context and FIFO */ - *gRFAL.Lm.rxLen = 0; - st25r3916ExecuteCommand(ST25R3916_CMD_CLEAR_FIFO); - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - - /* REMARK: In order to support CUP or proprietary frames, handling could be added here */ - } else if( - ((irqs & ST25R3916_IRQ_MASK_RXE_PTA) != 0U) && (gRFAL.Lm.brDetected != RFAL_BR_KEEP)) { - if(((gRFAL.Lm.mdMask & RFAL_LM_MASK_NFCA) != 0U) && - (gRFAL.Lm.brDetected == RFAL_BR_106)) { - st25r3916ReadRegister(ST25R3916_REG_PASSIVE_TARGET_STATUS, &tmp); - if(tmp > ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_halt) { - rfalListenSetState(RFAL_LM_STATE_READY_Ax); - } - } - } else if((irqs & ST25R3916_IRQ_MASK_EOF) != 0U) { - rfalListenSetState(RFAL_LM_STATE_POWER_OFF); - } else { - /* MISRA 15.7 - Empty else */ - } - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_READY_Ax: - - irqs = st25r3916GetInterrupt((ST25R3916_IRQ_MASK_EOF | ST25R3916_IRQ_MASK_WU_A_X)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - if((irqs & ST25R3916_IRQ_MASK_WU_A_X) != 0U) { - rfalListenSetState(RFAL_LM_STATE_ACTIVE_Ax); - } else if((irqs & ST25R3916_IRQ_MASK_EOF) != 0U) { - rfalListenSetState(RFAL_LM_STATE_POWER_OFF); - } else { - /* MISRA 15.7 - Empty else */ - } - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_CARDEMU_4A: - case RFAL_LM_STATE_CARDEMU_4B: - case RFAL_LM_STATE_CARDEMU_3: - case RFAL_LM_STATE_TARGET_F: - case RFAL_LM_STATE_TARGET_A: - break; - - /*******************************************************************************/ - default: - return ERR_WRONG_STATE; - } - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalListenStop(void) { - /* Check if RFAL is initialized */ - if(gRFAL.state < RFAL_STATE_INIT) { - return ERR_WRONG_STATE; - } - - gRFAL.Lm.state = RFAL_LM_STATE_NOT_INIT; - - /*Check if Observation Mode was enabled and disable it on ST25R391x */ - rfalCheckDisableObsMode(); - - /* Re-Enable the Oscillator if not running */ - st25r3916OscOn(); - - /* Disable Receiver and Transmitter */ - rfalFieldOff(); - - /* Disable all automatic responses */ - st25r3916SetRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, - (ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r | ST25R3916_REG_PASSIVE_TARGET_rfu | - ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a | ST25R3916_REG_PASSIVE_TARGET_d_ac_ap2p)); - - /* As there's no Off mode, set default value: ISO14443A with automatic RF Collision Avoidance Off */ - st25r3916WriteRegister( - ST25R3916_REG_MODE, - (ST25R3916_REG_MODE_om_iso14443a | ST25R3916_REG_MODE_tr_am_ook | - ST25R3916_REG_MODE_nfc_ar_off)); - - st25r3916DisableInterrupts( - (ST25R3916_IRQ_MASK_RXE_PTA | ST25R3916_IRQ_MASK_WU_F | ST25R3916_IRQ_MASK_WU_A | - ST25R3916_IRQ_MASK_WU_A_X | ST25R3916_IRQ_MASK_RFU2 | ST25R3916_IRQ_MASK_OSC)); - st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_RXE_PTA | ST25R3916_IRQ_MASK_WU_F | ST25R3916_IRQ_MASK_WU_A | - ST25R3916_IRQ_MASK_WU_A_X | ST25R3916_IRQ_MASK_RFU2)); - - /* Set Analog configurations for Listen Off event */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_LISTEN_OFF)); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode - rfalListenSleepStart(rfalLmState sleepSt, uint8_t* rxBuf, uint16_t rxBufLen, uint16_t* rxLen) { - /* Check if RFAL is not initialized */ - if(gRFAL.state < RFAL_STATE_INIT) { - return ERR_WRONG_STATE; - } - - switch(sleepSt) { - /*******************************************************************************/ - case RFAL_LM_STATE_SLEEP_A: - - /* Enable automatic responses for A */ - st25r3916ClrRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, (ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a)); - - /* Reset NFCA target */ - st25r3916ExecuteCommand(ST25R3916_CMD_GOTO_SLEEP); - - /* Set Target mode, Bit Rate detection and Listen Mode for NFC-A */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_MODE, - (ST25R3916_REG_MODE_targ | ST25R3916_REG_MODE_om_mask | - ST25R3916_REG_MODE_nfc_ar_mask), - (ST25R3916_REG_MODE_targ_targ | ST25R3916_REG_MODE_om3 | ST25R3916_REG_MODE_om0 | - ST25R3916_REG_MODE_nfc_ar_off)); - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_SLEEP_AF: - - /* Enable automatic responses for A + F */ - st25r3916ClrRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, - (ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r | ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a)); - - /* Reset NFCA target state */ - st25r3916ExecuteCommand(ST25R3916_CMD_GOTO_SLEEP); - - /* Set Target mode, Bit Rate detection, Listen Mode for NFC-A and NFC-F */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_MODE, - (ST25R3916_REG_MODE_targ | ST25R3916_REG_MODE_om_mask | - ST25R3916_REG_MODE_nfc_ar_mask), - (ST25R3916_REG_MODE_targ_targ | ST25R3916_REG_MODE_om3 | ST25R3916_REG_MODE_om2 | - ST25R3916_REG_MODE_om0 | ST25R3916_REG_MODE_nfc_ar_off)); - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_SLEEP_B: - /* REMARK: Support for CE-B would be added here */ - return ERR_NOT_IMPLEMENTED; - - /*******************************************************************************/ - default: - return ERR_PARAM; - } - - /* Ensure that the NFCIP1 mode is disabled */ - st25r3916ClrRegisterBits(ST25R3916_REG_ISO14443A_NFC, ST25R3916_REG_ISO14443A_NFC_nfc_f0); - - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - - /* Clear and enable required IRQs */ - st25r3916ClearAndEnableInterrupts( - (ST25R3916_IRQ_MASK_NFCT | ST25R3916_IRQ_MASK_RXS | ST25R3916_IRQ_MASK_CRC | - ST25R3916_IRQ_MASK_ERR1 | ST25R3916_IRQ_MASK_ERR2 | ST25R3916_IRQ_MASK_PAR | - ST25R3916_IRQ_MASK_EON | ST25R3916_IRQ_MASK_EOF | gRFAL.Lm.mdIrqs)); - - /* Check whether the field was turn off right after the Sleep request */ - if(!rfalIsExtFieldOn()) { - /*rfalLogD( "RFAL: curState: %02X newState: %02X \r\n", gRFAL.Lm.state, RFAL_LM_STATE_NOT_INIT );*/ - - rfalListenStop(); - return ERR_LINK_LOSS; - } - - /*rfalLogD( "RFAL: curState: %02X newState: %02X \r\n", gRFAL.Lm.state, sleepSt );*/ - - /* Set the new Sleep State*/ - gRFAL.Lm.state = sleepSt; - gRFAL.state = RFAL_STATE_LM; - - gRFAL.Lm.rxBuf = rxBuf; - gRFAL.Lm.rxBufLen = rxBufLen; - gRFAL.Lm.rxLen = rxLen; - *gRFAL.Lm.rxLen = 0; - gRFAL.Lm.dataFlag = false; - - return ERR_NONE; -} - -/*******************************************************************************/ -rfalLmState rfalListenGetState(bool* dataFlag, rfalBitRate* lastBR) { - /* Allow state retrieval even if gRFAL.state != RFAL_STATE_LM so * - * that this Lm state can be used by caller after activation */ - - if(lastBR != NULL) { - *lastBR = gRFAL.Lm.brDetected; - } - - if(dataFlag != NULL) { - *dataFlag = gRFAL.Lm.dataFlag; - } - - return gRFAL.Lm.state; -} - -/*******************************************************************************/ -ReturnCode rfalListenSetState(rfalLmState newSt) { - ReturnCode ret; - rfalLmState newState; - bool reSetState; - - /* Check if RFAL is initialized */ - if(gRFAL.state < RFAL_STATE_INIT) { - return ERR_WRONG_STATE; - } - - /* SetState clears the Data flag */ - gRFAL.Lm.dataFlag = false; - newState = newSt; - ret = ERR_NONE; - - do { - reSetState = false; - - /*******************************************************************************/ - switch(newState) { - /*******************************************************************************/ - case RFAL_LM_STATE_POWER_OFF: - - /* Enable the receiver and reset logic */ - st25r3916SetRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_rx_en); - st25r3916ExecuteCommand(ST25R3916_CMD_STOP); - - if((gRFAL.Lm.mdMask & RFAL_LM_MASK_NFCA) != 0U) { - /* Enable automatic responses for A */ - st25r3916ClrRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a); - - /* Prepares the NFCIP-1 Passive target logic to wait in the Sense/Idle state */ - st25r3916ExecuteCommand(ST25R3916_CMD_GOTO_SENSE); - } - - if((gRFAL.Lm.mdMask & RFAL_LM_MASK_NFCF) != 0U) { - /* Enable automatic responses for F */ - st25r3916ClrRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, (ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r)); - } - - if((gRFAL.Lm.mdMask & RFAL_LM_MASK_ACTIVE_P2P) != 0U) { - /* Ensure automatic response RF Collision Avoidance is back to only after Rx */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_nfc_ar_mask, - ST25R3916_REG_MODE_nfc_ar_auto_rx); - - /* Ensure that our field is Off, as automatic response RF Collision Avoidance may have been triggered */ - st25r3916TxOff(); - } - - /*******************************************************************************/ - /* Ensure that the NFCIP1 mode is disabled */ - st25r3916ClrRegisterBits( - ST25R3916_REG_ISO14443A_NFC, ST25R3916_REG_ISO14443A_NFC_nfc_f0); - - /*******************************************************************************/ - /* Clear and enable required IRQs */ - st25r3916DisableInterrupts(ST25R3916_IRQ_MASK_ALL); - - st25r3916ClearAndEnableInterrupts( - (ST25R3916_IRQ_MASK_NFCT | ST25R3916_IRQ_MASK_RXS | ST25R3916_IRQ_MASK_CRC | - ST25R3916_IRQ_MASK_ERR1 | ST25R3916_IRQ_MASK_OSC | ST25R3916_IRQ_MASK_ERR2 | - ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_EON | ST25R3916_IRQ_MASK_EOF | - gRFAL.Lm.mdIrqs)); - - /*******************************************************************************/ - /* Clear the bitRate previously detected */ - gRFAL.Lm.brDetected = RFAL_BR_KEEP; - - /*******************************************************************************/ - /* Apply the initial mode */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_MODE, - (ST25R3916_REG_MODE_targ | ST25R3916_REG_MODE_om_mask | - ST25R3916_REG_MODE_nfc_ar_mask), - (uint8_t)gRFAL.Lm.mdReg); - - /*******************************************************************************/ - /* Check if external Field is already On */ - if(rfalIsExtFieldOn()) { - reSetState = true; - newState = RFAL_LM_STATE_IDLE; /* Set IDLE state */ - } -#if 1 /* Perform bit rate detection in Low power mode */ - else { - st25r3916ClrRegisterBits( - ST25R3916_REG_OP_CONTROL, - (ST25R3916_REG_OP_CONTROL_tx_en | ST25R3916_REG_OP_CONTROL_rx_en | - ST25R3916_REG_OP_CONTROL_en)); - } -#endif - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_IDLE: - - /*******************************************************************************/ - /* Check if device is coming from Low Power bit rate detection */ - if(!st25r3916CheckReg( - ST25R3916_REG_OP_CONTROL, - ST25R3916_REG_OP_CONTROL_en, - ST25R3916_REG_OP_CONTROL_en)) { - /* Exit Low Power mode and confirm the temporarily enable */ - st25r3916SetRegisterBits( - ST25R3916_REG_OP_CONTROL, - (ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_rx_en)); - - if(!st25r3916CheckReg( - ST25R3916_REG_AUX_DISPLAY, - ST25R3916_REG_AUX_DISPLAY_osc_ok, - ST25R3916_REG_AUX_DISPLAY_osc_ok)) { - /* Wait for Oscillator ready */ - if(st25r3916WaitForInterruptsTimed( - ST25R3916_IRQ_MASK_OSC, ST25R3916_TOUT_OSC_STABLE) == 0U) { - ret = ERR_IO; - break; - } - } - } else { - st25r3916GetInterrupt(ST25R3916_IRQ_MASK_OSC); - } - - /*******************************************************************************/ - /* In Active P2P the Initiator may: Turn its field On; LM goes into IDLE state; - * Initiator sends an unexpected frame raising a Protocol error; Initiator - * turns its field Off and ST25R3916 performs the automatic RF Collision - * Avoidance keeping our field On; upon a Protocol error upper layer sets - * again the state to IDLE to clear dataFlag and wait for next data. - * - * Ensure that when upper layer calls SetState(IDLE), it restores initial - * configuration and that check whether an external Field is still present */ - if((gRFAL.Lm.mdMask & RFAL_LM_MASK_ACTIVE_P2P) != 0U) { - /* Ensure nfc_ar is reset and back to only after Rx */ - st25r3916ExecuteCommand(ST25R3916_CMD_STOP); - st25r3916ChangeRegisterBits( - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_nfc_ar_mask, - ST25R3916_REG_MODE_nfc_ar_auto_rx); - - /* Ensure that our field is Off, as automatic response RF Collision Avoidance may have been triggered */ - st25r3916TxOff(); - - /* If external Field is no longer detected go back to POWER_OFF */ - if(!st25r3916IsExtFieldOn()) { - reSetState = true; - newState = RFAL_LM_STATE_POWER_OFF; /* Set POWER_OFF state */ - } - } - /*******************************************************************************/ - - /* If we are in ACTIVE_A, reEnable Listen for A before going to IDLE, otherwise do nothing */ - if(gRFAL.Lm.state == RFAL_LM_STATE_ACTIVE_A) { - /* Enable automatic responses for A and Reset NFCA target state */ - st25r3916ClrRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, (ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a)); - st25r3916ExecuteCommand(ST25R3916_CMD_GOTO_SENSE); - } - - /* ReEnable the receiver */ - st25r3916ExecuteCommand(ST25R3916_CMD_CLEAR_FIFO); - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - - /*******************************************************************************/ - /*Check if Observation Mode is enabled and set it on ST25R391x */ - rfalCheckEnableObsModeRx(); - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_READY_F: - - /*******************************************************************************/ - /* If we're coming from BitRate detection mode, the Bit Rate Definition reg - * still has the last bit rate used. - * If a frame is received between setting the mode to Listen NFCA and - * setting Bit Rate Definition reg, it will raise a framing error. - * Set the bitrate immediately, and then the normal SetMode procedure */ - st25r3916SetBitrate((uint8_t)gRFAL.Lm.brDetected, (uint8_t)gRFAL.Lm.brDetected); - /*******************************************************************************/ - - /* Disable automatic responses for NFC-A */ - st25r3916SetRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, (ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a)); - - /* Set Mode NFC-F only */ - ret = rfalSetMode(RFAL_MODE_LISTEN_NFCF, gRFAL.Lm.brDetected, gRFAL.Lm.brDetected); - gRFAL.state = RFAL_STATE_LM; /* Keep in Listen Mode */ - - /* ReEnable the receiver */ - st25r3916ExecuteCommand(ST25R3916_CMD_CLEAR_FIFO); - st25r3916ExecuteCommand(ST25R3916_CMD_UNMASK_RECEIVE_DATA); - - /* Clear any previous transmission errors (if Reader polled for other/unsupported technologies) */ - st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_CRC | ST25R3916_IRQ_MASK_ERR2 | - ST25R3916_IRQ_MASK_ERR1)); - - st25r3916EnableInterrupts( - ST25R3916_IRQ_MASK_RXE); /* Start looking for any incoming data */ - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_CARDEMU_3: - - /* Set Listen NFCF mode */ - ret = rfalSetMode(RFAL_MODE_LISTEN_NFCF, gRFAL.Lm.brDetected, gRFAL.Lm.brDetected); - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_READY_Ax: - case RFAL_LM_STATE_READY_A: - - /*******************************************************************************/ - /* If we're coming from BitRate detection mode, the Bit Rate Definition reg - * still has the last bit rate used. - * If a frame is received between setting the mode to Listen NFCA and - * setting Bit Rate Definition reg, it will raise a framing error. - * Set the bitrate immediately, and then the normal SetMode procedure */ - st25r3916SetBitrate((uint8_t)gRFAL.Lm.brDetected, (uint8_t)gRFAL.Lm.brDetected); - /*******************************************************************************/ - - /* Disable automatic responses for NFC-F */ - st25r3916SetRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, (ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r)); - - /* Set Mode NFC-A only */ - ret = rfalSetMode(RFAL_MODE_LISTEN_NFCA, gRFAL.Lm.brDetected, gRFAL.Lm.brDetected); - - gRFAL.state = RFAL_STATE_LM; /* Keep in Listen Mode */ - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_ACTIVE_Ax: - case RFAL_LM_STATE_ACTIVE_A: - - /* Disable automatic responses for A */ - st25r3916SetRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, (ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a)); - - /* Clear any previous transmission errors (if Reader polled for other/unsupported technologies) */ - st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_CRC | ST25R3916_IRQ_MASK_ERR2 | - ST25R3916_IRQ_MASK_ERR1)); - - st25r3916EnableInterrupts( - ST25R3916_IRQ_MASK_RXE); /* Start looking for any incoming data */ - break; - - case RFAL_LM_STATE_TARGET_F: - /* Disable Automatic response SENSF_REQ */ - st25r3916SetRegisterBits( - ST25R3916_REG_PASSIVE_TARGET, (ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r)); - break; - - /*******************************************************************************/ - case RFAL_LM_STATE_SLEEP_A: - case RFAL_LM_STATE_SLEEP_B: - case RFAL_LM_STATE_SLEEP_AF: - /* These sleep states have to be set by the rfalListenSleepStart() method */ - return ERR_REQUEST; - - /*******************************************************************************/ - case RFAL_LM_STATE_CARDEMU_4A: - case RFAL_LM_STATE_CARDEMU_4B: - case RFAL_LM_STATE_TARGET_A: - /* States not handled by the LM, just keep state context */ - break; - - /*******************************************************************************/ - default: - return ERR_WRONG_STATE; - } - } while(reSetState); - - gRFAL.Lm.state = newState; - - // Call callback on state change - if(gRFAL.callbacks.state_changed_cb) { - gRFAL.callbacks.state_changed_cb(gRFAL.callbacks.ctx); - } - - return ret; -} - -#endif /* RFAL_FEATURE_LISTEN_MODE */ - -/******************************************************************************* - * Wake-Up Mode * - *******************************************************************************/ - -#if RFAL_FEATURE_WAKEUP_MODE - -/*******************************************************************************/ -ReturnCode rfalWakeUpModeStart(const rfalWakeUpConfig* config) { - uint8_t aux; - uint8_t reg; - uint32_t irqs; - - /* Check if RFAL is not initialized */ - if(gRFAL.state < RFAL_STATE_INIT) { - return ERR_WRONG_STATE; - } - - /* The Wake-Up procedure is explained in detail in Application Note: AN4985 */ - - if(config == NULL) { - gRFAL.wum.cfg.period = RFAL_WUM_PERIOD_200MS; - gRFAL.wum.cfg.irqTout = false; - gRFAL.wum.cfg.indAmp.enabled = true; - gRFAL.wum.cfg.indPha.enabled = false; - gRFAL.wum.cfg.cap.enabled = false; - gRFAL.wum.cfg.indAmp.delta = 2U; - gRFAL.wum.cfg.indAmp.reference = RFAL_WUM_REFERENCE_AUTO; - gRFAL.wum.cfg.indAmp.autoAvg = false; - - /*******************************************************************************/ - /* Check if AAT is enabled and if so make use of the SW Tag Detection */ - if(st25r3916CheckReg( - ST25R3916_REG_IO_CONF2, - ST25R3916_REG_IO_CONF2_aat_en, - ST25R3916_REG_IO_CONF2_aat_en)) { - gRFAL.wum.cfg.swTagDetect = true; - gRFAL.wum.cfg.indAmp.autoAvg = true; - gRFAL.wum.cfg.indAmp.aaWeight = RFAL_WUM_AA_WEIGHT_16; - } - } else { - gRFAL.wum.cfg = *config; - } - - /* Check for valid configuration */ - if((!gRFAL.wum.cfg.cap.enabled && !gRFAL.wum.cfg.indAmp.enabled && - !gRFAL.wum.cfg.indPha.enabled) || - (gRFAL.wum.cfg.cap.enabled && - (gRFAL.wum.cfg.indAmp.enabled || gRFAL.wum.cfg.indPha.enabled)) || - (gRFAL.wum.cfg.cap.enabled && gRFAL.wum.cfg.swTagDetect) || - ((gRFAL.wum.cfg.indAmp.reference > RFAL_WUM_REFERENCE_AUTO) || - (gRFAL.wum.cfg.indPha.reference > RFAL_WUM_REFERENCE_AUTO) || - (gRFAL.wum.cfg.cap.reference > RFAL_WUM_REFERENCE_AUTO))) { - return ERR_PARAM; - } - - irqs = ST25R3916_IRQ_MASK_NONE; - - /* Disable Tx, Rx, External Field Detector and set default ISO14443A mode */ - st25r3916TxRxOff(); - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_en_fd_mask); - st25r3916ChangeRegisterBits( - ST25R3916_REG_MODE, - (ST25R3916_REG_MODE_targ | ST25R3916_REG_MODE_om_mask), - (ST25R3916_REG_MODE_targ_init | ST25R3916_REG_MODE_om_iso14443a)); - - /* Set Analog configurations for Wake-up On event */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_WAKEUP_ON)); - - /*******************************************************************************/ - /* Prepare Wake-Up Timer Control Register */ - reg = - (uint8_t)(((uint8_t)gRFAL.wum.cfg.period & 0x0FU) << ST25R3916_REG_WUP_TIMER_CONTROL_wut_shift); - reg |= - (uint8_t)(((uint8_t)gRFAL.wum.cfg.period < (uint8_t)RFAL_WUM_PERIOD_100MS) ? ST25R3916_REG_WUP_TIMER_CONTROL_wur : 0x00U); - - if(gRFAL.wum.cfg.irqTout || gRFAL.wum.cfg.swTagDetect) { - reg |= ST25R3916_REG_WUP_TIMER_CONTROL_wto; - irqs |= ST25R3916_IRQ_MASK_WT; - } - - /* Check if HW Wake-up is to be used or SW Tag detection */ - if(gRFAL.wum.cfg.swTagDetect) { - gRFAL.wum.cfg.indAmp.reference = 0U; - gRFAL.wum.cfg.indPha.reference = 0U; - gRFAL.wum.cfg.cap.reference = 0U; - } else { - /*******************************************************************************/ - /* Check if Inductive Amplitude is to be performed */ - if(gRFAL.wum.cfg.indAmp.enabled) { - aux = - (uint8_t)((gRFAL.wum.cfg.indAmp.delta) << ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_d_shift); - aux |= - (uint8_t)(gRFAL.wum.cfg.indAmp.aaInclMeas ? ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_aam : 0x00U); - aux |= - (uint8_t)(((uint8_t)gRFAL.wum.cfg.indAmp.aaWeight << ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_aew_shift) & ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_aew_mask); - aux |= - (uint8_t)(gRFAL.wum.cfg.indAmp.autoAvg ? ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_ae : 0x00U); - - st25r3916WriteRegister(ST25R3916_REG_AMPLITUDE_MEASURE_CONF, aux); - - /* Only need to set the reference if not using Auto Average */ - if(!gRFAL.wum.cfg.indAmp.autoAvg) { - if(gRFAL.wum.cfg.indAmp.reference == RFAL_WUM_REFERENCE_AUTO) { - st25r3916MeasureAmplitude(&aux); - gRFAL.wum.cfg.indAmp.reference = aux; - } - st25r3916WriteRegister( - ST25R3916_REG_AMPLITUDE_MEASURE_REF, (uint8_t)gRFAL.wum.cfg.indAmp.reference); - } - - reg |= ST25R3916_REG_WUP_TIMER_CONTROL_wam; - irqs |= ST25R3916_IRQ_MASK_WAM; - } - - /*******************************************************************************/ - /* Check if Inductive Phase is to be performed */ - if(gRFAL.wum.cfg.indPha.enabled) { - aux = - (uint8_t)((gRFAL.wum.cfg.indPha.delta) << ST25R3916_REG_PHASE_MEASURE_CONF_pm_d_shift); - aux |= - (uint8_t)(gRFAL.wum.cfg.indPha.aaInclMeas ? ST25R3916_REG_PHASE_MEASURE_CONF_pm_aam : 0x00U); - aux |= - (uint8_t)(((uint8_t)gRFAL.wum.cfg.indPha.aaWeight << ST25R3916_REG_PHASE_MEASURE_CONF_pm_aew_shift) & ST25R3916_REG_PHASE_MEASURE_CONF_pm_aew_mask); - aux |= - (uint8_t)(gRFAL.wum.cfg.indPha.autoAvg ? ST25R3916_REG_PHASE_MEASURE_CONF_pm_ae : 0x00U); - - st25r3916WriteRegister(ST25R3916_REG_PHASE_MEASURE_CONF, aux); - - /* Only need to set the reference if not using Auto Average */ - if(!gRFAL.wum.cfg.indPha.autoAvg) { - if(gRFAL.wum.cfg.indPha.reference == RFAL_WUM_REFERENCE_AUTO) { - st25r3916MeasurePhase(&aux); - gRFAL.wum.cfg.indPha.reference = aux; - } - st25r3916WriteRegister( - ST25R3916_REG_PHASE_MEASURE_REF, (uint8_t)gRFAL.wum.cfg.indPha.reference); - } - - reg |= ST25R3916_REG_WUP_TIMER_CONTROL_wph; - irqs |= ST25R3916_IRQ_MASK_WPH; - } - - /*******************************************************************************/ - /* Check if Capacitive is to be performed */ - if(gRFAL.wum.cfg.cap.enabled) { - /*******************************************************************************/ - /* Perform Capacitive sensor calibration */ - - /* Disable Oscillator and Field */ - st25r3916ClrRegisterBits( - ST25R3916_REG_OP_CONTROL, - (ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_tx_en)); - - /* Sensor gain should be configured on Analog Config: RFAL_ANALOG_CONFIG_CHIP_WAKEUP_ON */ - - /* Perform calibration procedure */ - st25r3916CalibrateCapacitiveSensor(NULL); - - /*******************************************************************************/ - aux = - (uint8_t)((gRFAL.wum.cfg.cap.delta) << ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_d_shift); - aux |= - (uint8_t)(gRFAL.wum.cfg.cap.aaInclMeas ? ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_aam : 0x00U); - aux |= - (uint8_t)(((uint8_t)gRFAL.wum.cfg.cap.aaWeight << ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_aew_shift) & ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_aew_mask); - aux |= - (uint8_t)(gRFAL.wum.cfg.cap.autoAvg ? ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_ae : 0x00U); - - st25r3916WriteRegister(ST25R3916_REG_CAPACITANCE_MEASURE_CONF, aux); - - /* Only need to set the reference if not using Auto Average */ - if(!gRFAL.wum.cfg.cap.autoAvg || gRFAL.wum.cfg.swTagDetect) { - if(gRFAL.wum.cfg.indPha.reference == RFAL_WUM_REFERENCE_AUTO) { - st25r3916MeasureCapacitance(&aux); - gRFAL.wum.cfg.cap.reference = aux; - } - st25r3916WriteRegister( - ST25R3916_REG_CAPACITANCE_MEASURE_REF, (uint8_t)gRFAL.wum.cfg.cap.reference); - } - - reg |= ST25R3916_REG_WUP_TIMER_CONTROL_wcap; - irqs |= ST25R3916_IRQ_MASK_WCAP; - } - } - - /* Disable and clear all interrupts except Wake-Up IRQs */ - st25r3916DisableInterrupts(ST25R3916_IRQ_MASK_ALL); - st25r3916GetInterrupt(irqs); - st25r3916EnableInterrupts(irqs); - - /* Enable Low Power Wake-Up Mode (Disable: Oscilattor, Tx, Rx and External Field Detector) */ - st25r3916WriteRegister(ST25R3916_REG_WUP_TIMER_CONTROL, reg); - st25r3916ChangeRegisterBits( - ST25R3916_REG_OP_CONTROL, - (ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_rx_en | - ST25R3916_REG_OP_CONTROL_tx_en | ST25R3916_REG_OP_CONTROL_en_fd_mask | - ST25R3916_REG_OP_CONTROL_wu), - ST25R3916_REG_OP_CONTROL_wu); - - gRFAL.wum.state = RFAL_WUM_STATE_ENABLED; - gRFAL.state = RFAL_STATE_WUM; - - return ERR_NONE; -} - -/*******************************************************************************/ -bool rfalWakeUpModeHasWoke(void) { - return (gRFAL.wum.state >= RFAL_WUM_STATE_ENABLED_WOKE); -} - -/*******************************************************************************/ -static uint16_t rfalWakeUpModeFilter(uint16_t curRef, uint16_t curVal, uint8_t weight) { - uint16_t newRef; - - /* Perform the averaging|filter as describded in ST25R3916 DS */ - - /* Avoid signed arithmetics by splitting in two cases */ - if(curVal > curRef) { - newRef = curRef + ((curVal - curRef) / weight); - - /* In order for the reference to converge to final value * - * increment once the diff is smaller that the weight */ - if((curVal != curRef) && (curRef == newRef)) { - newRef &= 0xFF00U; - newRef += 0x0100U; - } - } else { - newRef = curRef - ((curRef - curVal) / weight); - - /* In order for the reference to converge to final value * - * decrement once the diff is smaller that the weight */ - if((curVal != curRef) && (curRef == newRef)) { - newRef &= 0xFF00U; - } - } - - return newRef; -} - -/*******************************************************************************/ -static void rfalRunWakeUpModeWorker(void) { - uint32_t irqs; - uint8_t reg; - uint16_t value; - uint16_t delta; - - if(gRFAL.state != RFAL_STATE_WUM) { - return; - } - - switch(gRFAL.wum.state) { - case RFAL_WUM_STATE_ENABLED: - case RFAL_WUM_STATE_ENABLED_WOKE: - - irqs = st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_WT | ST25R3916_IRQ_MASK_WAM | ST25R3916_IRQ_MASK_WPH | - ST25R3916_IRQ_MASK_WCAP)); - if(irqs == ST25R3916_IRQ_MASK_NONE) { - break; /* No interrupt to process */ - } - - /*******************************************************************************/ - /* Check and mark which measurement(s) cause interrupt */ - if((irqs & ST25R3916_IRQ_MASK_WAM) != 0U) { - st25r3916ReadRegister(ST25R3916_REG_AMPLITUDE_MEASURE_RESULT, ®); - gRFAL.wum.state = RFAL_WUM_STATE_ENABLED_WOKE; - } - - if((irqs & ST25R3916_IRQ_MASK_WPH) != 0U) { - st25r3916ReadRegister(ST25R3916_REG_PHASE_MEASURE_RESULT, ®); - gRFAL.wum.state = RFAL_WUM_STATE_ENABLED_WOKE; - } - - if((irqs & ST25R3916_IRQ_MASK_WCAP) != 0U) { - st25r3916ReadRegister(ST25R3916_REG_CAPACITANCE_MEASURE_RESULT, ®); - gRFAL.wum.state = RFAL_WUM_STATE_ENABLED_WOKE; - } - - if((irqs & ST25R3916_IRQ_MASK_WT) != 0U) { - /*******************************************************************************/ - if(gRFAL.wum.cfg.swTagDetect) { - /* Enable Ready mode and wait the settle time */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_OP_CONTROL, - (ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_wu), - ST25R3916_REG_OP_CONTROL_en); - platformDelay(RFAL_ST25R3916_AAT_SETTLE); - - /*******************************************************************************/ - if(gRFAL.wum.cfg.indAmp.enabled) { - /* Perform amplitude measurement */ - st25r3916MeasureAmplitude(®); - - /* Convert inputs to TD format */ - value = rfalConvTDFormat(reg); - delta = rfalConvTDFormat(gRFAL.wum.cfg.indAmp.delta); - - /* Set first measurement as reference */ - if(gRFAL.wum.cfg.indAmp.reference == 0U) { - gRFAL.wum.cfg.indAmp.reference = value; - } - - /* Check if device should be woken */ - if((value >= (gRFAL.wum.cfg.indAmp.reference + delta)) || - (value <= (gRFAL.wum.cfg.indAmp.reference - delta))) { - gRFAL.wum.state = RFAL_WUM_STATE_ENABLED_WOKE; - break; - } - - /* Update moving reference if enabled */ - if(gRFAL.wum.cfg.indAmp.autoAvg) { - gRFAL.wum.cfg.indAmp.reference = rfalWakeUpModeFilter( - gRFAL.wum.cfg.indAmp.reference, - value, - (RFAL_WU_MIN_WEIGHT_VAL << (uint8_t)gRFAL.wum.cfg.indAmp.aaWeight)); - } - } - - /*******************************************************************************/ - if(gRFAL.wum.cfg.indPha.enabled) { - /* Perform Phase measurement */ - st25r3916MeasurePhase(®); - - /* Convert inputs to TD format */ - value = rfalConvTDFormat(reg); - delta = rfalConvTDFormat(gRFAL.wum.cfg.indPha.delta); - - /* Set first measurement as reference */ - if(gRFAL.wum.cfg.indPha.reference == 0U) { - gRFAL.wum.cfg.indPha.reference = value; - } - - /* Check if device should be woken */ - if((value >= (gRFAL.wum.cfg.indPha.reference + delta)) || - (value <= (gRFAL.wum.cfg.indPha.reference - delta))) { - gRFAL.wum.state = RFAL_WUM_STATE_ENABLED_WOKE; - break; - } - - /* Update moving reference if enabled */ - if(gRFAL.wum.cfg.indPha.autoAvg) { - gRFAL.wum.cfg.indPha.reference = rfalWakeUpModeFilter( - gRFAL.wum.cfg.indPha.reference, - value, - (RFAL_WU_MIN_WEIGHT_VAL << (uint8_t)gRFAL.wum.cfg.indPha.aaWeight)); - } - } - - /* Re-Enable low power Wake-Up mode for wto to trigger another measurement(s) */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_OP_CONTROL, - (ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_wu), - (ST25R3916_REG_OP_CONTROL_wu)); - } - } - break; - - default: - /* MISRA 16.4: no empty default statement (a comment being enough) */ - break; - } -} - -/*******************************************************************************/ -ReturnCode rfalWakeUpModeStop(void) { - /* Check if RFAL is in Wake-up mode */ - if(gRFAL.state != RFAL_STATE_WUM) { - return ERR_WRONG_STATE; - } - - gRFAL.wum.state = RFAL_WUM_STATE_NOT_INIT; - - /* Disable Wake-Up Mode */ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); - st25r3916DisableInterrupts( - (ST25R3916_IRQ_MASK_WT | ST25R3916_IRQ_MASK_WAM | ST25R3916_IRQ_MASK_WPH | - ST25R3916_IRQ_MASK_WCAP)); - - /* Re-Enable External Field Detector as: Automatics */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_OP_CONTROL, - ST25R3916_REG_OP_CONTROL_en_fd_mask, - ST25R3916_REG_OP_CONTROL_en_fd_auto_efd); - - /* Re-Enable the Oscillator */ - st25r3916OscOn(); - - /* Set Analog configurations for Wake-up Off event */ - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_WAKEUP_OFF)); - - return ERR_NONE; -} - -#endif /* RFAL_FEATURE_WAKEUP_MODE */ - -/******************************************************************************* - * Low-Power Mode * - *******************************************************************************/ - -#if RFAL_FEATURE_LOWPOWER_MODE - -/*******************************************************************************/ -ReturnCode rfalLowPowerModeStart(void) { - /* Check if RFAL is not initialized */ - if(gRFAL.state < RFAL_STATE_INIT) { - return ERR_WRONG_STATE; - } - - /* Stop any ongoing activity and set the device in low power by disabling oscillator, transmitter, receiver and external field detector */ - st25r3916ExecuteCommand(ST25R3916_CMD_STOP); - st25r3916ClrRegisterBits( - ST25R3916_REG_OP_CONTROL, - (ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_rx_en | - ST25R3916_REG_OP_CONTROL_wu | ST25R3916_REG_OP_CONTROL_tx_en | - ST25R3916_REG_OP_CONTROL_en_fd_mask)); - - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_LOWPOWER_ON)); - - gRFAL.state = RFAL_STATE_IDLE; - gRFAL.lpm.isRunning = true; - - platformDisableIrqCallback(); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalLowPowerModeStop(void) { - ReturnCode ret; - - platformEnableIrqCallback(); - - /* Check if RFAL is on right state */ - if(!gRFAL.lpm.isRunning) { - return ERR_WRONG_STATE; - } - - /* Re-enable device */ - EXIT_ON_ERR(ret, st25r3916OscOn()); - st25r3916ChangeRegisterBits( - ST25R3916_REG_OP_CONTROL, - ST25R3916_REG_OP_CONTROL_en_fd_mask, - ST25R3916_REG_OP_CONTROL_en_fd_auto_efd); - - rfalSetAnalogConfig((RFAL_ANALOG_CONFIG_TECH_CHIP | RFAL_ANALOG_CONFIG_CHIP_LOWPOWER_OFF)); - - gRFAL.state = RFAL_STATE_INIT; - return ERR_NONE; -} - -#endif /* RFAL_FEATURE_LOWPOWER_MODE */ - -/******************************************************************************* - * RF Chip * - *******************************************************************************/ - -/*******************************************************************************/ -ReturnCode rfalChipWriteReg(uint16_t reg, const uint8_t* values, uint8_t len) { - if(!st25r3916IsRegValid((uint8_t)reg)) { - return ERR_PARAM; - } - - return st25r3916WriteMultipleRegisters((uint8_t)reg, values, len); -} - -/*******************************************************************************/ -ReturnCode rfalChipReadReg(uint16_t reg, uint8_t* values, uint8_t len) { - if(!st25r3916IsRegValid((uint8_t)reg)) { - return ERR_PARAM; - } - - return st25r3916ReadMultipleRegisters((uint8_t)reg, values, len); -} - -/*******************************************************************************/ -ReturnCode rfalChipExecCmd(uint16_t cmd) { - if(!st25r3916IsCmdValid((uint8_t)cmd)) { - return ERR_PARAM; - } - - return st25r3916ExecuteCommand((uint8_t)cmd); -} - -/*******************************************************************************/ -ReturnCode rfalChipWriteTestReg(uint16_t reg, uint8_t value) { - return st25r3916WriteTestRegister((uint8_t)reg, value); -} - -/*******************************************************************************/ -ReturnCode rfalChipReadTestReg(uint16_t reg, uint8_t* value) { - return st25r3916ReadTestRegister((uint8_t)reg, value); -} - -/*******************************************************************************/ -ReturnCode rfalChipChangeRegBits(uint16_t reg, uint8_t valueMask, uint8_t value) { - if(!st25r3916IsRegValid((uint8_t)reg)) { - return ERR_PARAM; - } - - return st25r3916ChangeRegisterBits((uint8_t)reg, valueMask, value); -} - -/*******************************************************************************/ -ReturnCode rfalChipChangeTestRegBits(uint16_t reg, uint8_t valueMask, uint8_t value) { - st25r3916ChangeTestRegisterBits((uint8_t)reg, valueMask, value); - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalChipSetRFO(uint8_t rfo) { - return st25r3916ChangeRegisterBits( - ST25R3916_REG_TX_DRIVER, ST25R3916_REG_TX_DRIVER_d_res_mask, rfo); -} - -/*******************************************************************************/ -ReturnCode rfalChipGetRFO(uint8_t* result) { - ReturnCode ret; - - ret = st25r3916ReadRegister(ST25R3916_REG_TX_DRIVER, result); - - (*result) = ((*result) & ST25R3916_REG_TX_DRIVER_d_res_mask); - - return ret; -} - -/*******************************************************************************/ -ReturnCode rfalChipMeasureAmplitude(uint8_t* result) { - ReturnCode err; - uint8_t reg_opc, reg_mode, reg_conf1, reg_conf2; - - /* Save registers which will be adjusted below */ - st25r3916ReadRegister(ST25R3916_REG_OP_CONTROL, ®_opc); - st25r3916ReadRegister(ST25R3916_REG_MODE, ®_mode); - st25r3916ReadRegister(ST25R3916_REG_RX_CONF1, ®_conf1); - st25r3916ReadRegister(ST25R3916_REG_RX_CONF2, ®_conf2); - - /* Set values as per defaults of DS. These regs/bits influence receiver chain and change amplitude */ - /* Doing so achieves an amplitude comparable over a complete polling cylce */ - st25r3916WriteRegister(ST25R3916_REG_OP_CONTROL, (reg_opc & ~ST25R3916_REG_OP_CONTROL_rx_chn)); - st25r3916WriteRegister( - ST25R3916_REG_MODE, - ST25R3916_REG_MODE_om_iso14443a | ST25R3916_REG_MODE_targ_init | - ST25R3916_REG_MODE_tr_am_ook | ST25R3916_REG_MODE_nfc_ar_off); - st25r3916WriteRegister( - ST25R3916_REG_RX_CONF1, (reg_conf1 & ~ST25R3916_REG_RX_CONF1_ch_sel_AM)); - st25r3916WriteRegister( - ST25R3916_REG_RX_CONF2, - ((reg_conf2 & ~(ST25R3916_REG_RX_CONF2_demod_mode | ST25R3916_REG_RX_CONF2_amd_sel)) | - ST25R3916_REG_RX_CONF2_amd_sel_peak)); - - /* Perform the actual measurement */ - err = st25r3916MeasureAmplitude(result); - - /* Restore values */ - st25r3916WriteRegister(ST25R3916_REG_OP_CONTROL, reg_opc); - st25r3916WriteRegister(ST25R3916_REG_MODE, reg_mode); - st25r3916WriteRegister(ST25R3916_REG_RX_CONF1, reg_conf1); - st25r3916WriteRegister(ST25R3916_REG_RX_CONF2, reg_conf2); - - return err; -} - -/*******************************************************************************/ -ReturnCode rfalChipMeasurePhase(uint8_t* result) { - st25r3916MeasurePhase(result); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalChipMeasureCapacitance(uint8_t* result) { - st25r3916MeasureCapacitance(result); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode rfalChipMeasurePowerSupply(uint8_t param, uint8_t* result) { - *result = st25r3916MeasurePowerSupply(param); - - return ERR_NONE; -} - -/*******************************************************************************/ -extern uint8_t invalid_size_of_stream_configs - [(sizeof(struct st25r3916StreamConfig) == sizeof(struct iso15693StreamConfig)) ? 1 : (-1)]; diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916.c b/lib/ST25RFAL002/source/st25r3916/st25r3916.c deleted file mode 100644 index 9b6c22bff..000000000 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916.c +++ /dev/null @@ -1,792 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Gustavo Patricio - * - * \brief ST25R3916 high level interface - * - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ - -#include "st25r3916.h" -#include "st25r3916_com.h" -#include "st25r3916_led.h" -#include "st25r3916_irq.h" -#include "utils.h" - -/* -****************************************************************************** -* LOCAL DEFINES -****************************************************************************** -*/ - -#define ST25R3916_SUPPLY_THRESHOLD \ - 3600U /*!< Power supply measure threshold between 3.3V or 5V */ -#define ST25R3916_NRT_MAX \ - 0xFFFFU /*!< Max Register value of NRT */ - -#define ST25R3916_TOUT_MEASURE_VDD \ - 100U /*!< Max duration time of Measure Power Supply command Datasheet: 25us */ -#define ST25R3916_TOUT_MEASURE_AMPLITUDE \ - 10U /*!< Max duration time of Measure Amplitude command Datasheet: 25us */ -#define ST25R3916_TOUT_MEASURE_PHASE \ - 10U /*!< Max duration time of Measure Phase command Datasheet: 25us */ -#define ST25R3916_TOUT_MEASURE_CAPACITANCE \ - 10U /*!< Max duration time of Measure Capacitance command Datasheet: 25us */ -#define ST25R3916_TOUT_CALIBRATE_CAP_SENSOR \ - 4U /*!< Max duration Calibrate Capacitive Sensor command Datasheet: 3ms */ -#define ST25R3916_TOUT_ADJUST_REGULATORS \ - 6U /*!< Max duration time of Adjust Regulators command Datasheet: 5ms */ -#define ST25R3916_TOUT_CA \ - 10U /*!< Max duration time of Collision Avoidance command */ - -#define ST25R3916_TEST_REG_PATTERN \ - 0x33U /*!< Register Read Write test pattern used during selftest */ -#define ST25R3916_TEST_WU_TOUT \ - 12U /*!< Timeout used on WU timer during self test */ -#define ST25R3916_TEST_TMR_TOUT \ - 20U /*!< Timeout used during self test */ -#define ST25R3916_TEST_TMR_TOUT_DELTA \ - 2U /*!< Timeout used during self test */ -#define ST25R3916_TEST_TMR_TOUT_8FC \ - (ST25R3916_TEST_TMR_TOUT * 16950U) /*!< Timeout in 8/fc */ - -/* -****************************************************************************** -* LOCAL CONSTANTS -****************************************************************************** -*/ - -/* -****************************************************************************** -* LOCAL VARIABLES -****************************************************************************** -*/ - -static uint32_t gST25R3916NRT_64fcs; - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/* - ****************************************************************************** - * LOCAL FUNCTION - ****************************************************************************** - */ - -ReturnCode st25r3916ExecuteCommandAndGetResult( - uint8_t cmd, - uint8_t resReg, - uint8_t tout, - uint8_t* result) { - /* Clear and enable Direct Command interrupt */ - st25r3916GetInterrupt(ST25R3916_IRQ_MASK_DCT); - st25r3916EnableInterrupts(ST25R3916_IRQ_MASK_DCT); - - st25r3916ExecuteCommand(cmd); - - st25r3916WaitForInterruptsTimed(ST25R3916_IRQ_MASK_DCT, tout); - st25r3916DisableInterrupts(ST25R3916_IRQ_MASK_DCT); - - /* After execution read out the result if the pointer is not NULL */ - if(result != NULL) { - st25r3916ReadRegister(resReg, result); - } - - return ERR_NONE; -} - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -ReturnCode st25r3916Initialize(void) { - uint16_t vdd_mV; - ReturnCode ret; - - /* Set default state on the ST25R3916 */ - st25r3916ExecuteCommand(ST25R3916_CMD_SET_DEFAULT); - -#ifndef RFAL_USE_I2C - /* Increase MISO driving level as SPI can go up to 10MHz */ - st25r3916WriteRegister(ST25R3916_REG_IO_CONF2, ST25R3916_REG_IO_CONF2_io_drv_lvl); -#endif /* RFAL_USE_I2C */ - - if(!st25r3916CheckChipID(NULL)) { - platformErrorHandle(); - return ERR_HW_MISMATCH; - } - - st25r3916InitInterrupts(); - st25r3916ledInit(); - - gST25R3916NRT_64fcs = 0; - -#ifndef RFAL_USE_I2C - /* Enable pull downs on MISO line */ - st25r3916SetRegisterBits( - ST25R3916_REG_IO_CONF2, - (ST25R3916_REG_IO_CONF2_miso_pd1 | ST25R3916_REG_IO_CONF2_miso_pd2)); -#endif /* RFAL_USE_I2C */ - - /* Disable internal overheat protection */ - st25r3916ChangeTestRegisterBits(0x04, 0x10, 0x10); - -#ifdef ST25R_SELFTEST - /****************************************************************************** - * Check communication interface: - * - write a pattern in a register - * - reads back the register value - * - return ERR_IO in case the read value is different - */ - st25r3916WriteRegister(ST25R3916_REG_BIT_RATE, ST25R3916_TEST_REG_PATTERN); - if(!st25r3916CheckReg( - ST25R3916_REG_BIT_RATE, - (ST25R3916_REG_BIT_RATE_rxrate_mask | ST25R3916_REG_BIT_RATE_txrate_mask), - ST25R3916_TEST_REG_PATTERN)) { - platformErrorHandle(); - return ERR_IO; - } - - /* Restore default value */ - st25r3916WriteRegister(ST25R3916_REG_BIT_RATE, 0x00); - - /* - * Check IRQ Handling: - * - use the Wake-up timer to trigger an IRQ - * - wait the Wake-up timer interrupt - * - return ERR_TIMEOUT when the Wake-up timer interrupt is not received - */ - st25r3916WriteRegister( - ST25R3916_REG_WUP_TIMER_CONTROL, - ST25R3916_REG_WUP_TIMER_CONTROL_wur | ST25R3916_REG_WUP_TIMER_CONTROL_wto); - st25r3916EnableInterrupts(ST25R3916_IRQ_MASK_WT); - st25r3916ExecuteCommand(ST25R3916_CMD_START_WUP_TIMER); - if(st25r3916WaitForInterruptsTimed(ST25R3916_IRQ_MASK_WT, ST25R3916_TEST_WU_TOUT) == 0U) { - platformErrorHandle(); - return ERR_TIMEOUT; - } - st25r3916DisableInterrupts(ST25R3916_IRQ_MASK_WT); - st25r3916WriteRegister(ST25R3916_REG_WUP_TIMER_CONTROL, 0U); - /*******************************************************************************/ -#endif /* ST25R_SELFTEST */ - - /* Enable Oscillator and wait until it gets stable */ - ret = st25r3916OscOn(); - if(ret != ERR_NONE) { - platformErrorHandle(); - return ret; - } - - /* Measure VDD and set sup3V bit according to Power supplied */ - vdd_mV = st25r3916MeasureVoltage(ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd); - st25r3916ChangeRegisterBits( - ST25R3916_REG_IO_CONF2, - ST25R3916_REG_IO_CONF2_sup3V, - ((vdd_mV < ST25R3916_SUPPLY_THRESHOLD) ? ST25R3916_REG_IO_CONF2_sup3V_3V : - ST25R3916_REG_IO_CONF2_sup3V_5V)); - - /* Make sure Transmitter and Receiver are disabled */ - st25r3916TxRxOff(); - -#ifdef ST25R_SELFTEST_TIMER - /****************************************************************************** - * Check SW timer operation : - * - use the General Purpose timer to measure an amount of time - * - test whether an interrupt is seen when less time was given - * - test whether an interrupt is seen when sufficient time was given - */ - - st25r3916EnableInterrupts(ST25R3916_IRQ_MASK_GPE); - st25r3916SetStartGPTimer( - (uint16_t)ST25R3916_TEST_TMR_TOUT_8FC, ST25R3916_REG_TIMER_EMV_CONTROL_gptc_no_trigger); - if(st25r3916WaitForInterruptsTimed( - ST25R3916_IRQ_MASK_GPE, (ST25R3916_TEST_TMR_TOUT - ST25R3916_TEST_TMR_TOUT_DELTA)) != - 0U) { - platformErrorHandle(); - return ERR_SYSTEM; - } - - /* Stop all activities to stop the GP timer */ - st25r3916ExecuteCommand(ST25R3916_CMD_STOP); - st25r3916ClearAndEnableInterrupts(ST25R3916_IRQ_MASK_GPE); - st25r3916SetStartGPTimer( - (uint16_t)ST25R3916_TEST_TMR_TOUT_8FC, ST25R3916_REG_TIMER_EMV_CONTROL_gptc_no_trigger); - if(st25r3916WaitForInterruptsTimed( - ST25R3916_IRQ_MASK_GPE, (ST25R3916_TEST_TMR_TOUT + ST25R3916_TEST_TMR_TOUT_DELTA)) == - 0U) { - platformErrorHandle(); - return ERR_SYSTEM; - } - - /* Stop all activities to stop the GP timer */ - st25r3916ExecuteCommand(ST25R3916_CMD_STOP); - /*******************************************************************************/ -#endif /* ST25R_SELFTEST_TIMER */ - - /* After reset all interrupts are enabled, so disable them at first */ - st25r3916DisableInterrupts(ST25R3916_IRQ_MASK_ALL); - - /* And clear them, just to be sure */ - st25r3916ClearInterrupts(); - - return ERR_NONE; -} - -/*******************************************************************************/ -void st25r3916Deinitialize(void) { - st25r3916DisableInterrupts(ST25R3916_IRQ_MASK_ALL); - - /* Disable Tx and Rx, Keep OSC On */ - st25r3916TxRxOff(); - - return; -} - -/*******************************************************************************/ -ReturnCode st25r3916OscOn(void) { - /* Check if oscillator is already turned on and stable */ - /* Use ST25R3916_REG_OP_CONTROL_en instead of ST25R3916_REG_AUX_DISPLAY_osc_ok to be on the safe side */ - if(!st25r3916CheckReg( - ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_en, ST25R3916_REG_OP_CONTROL_en)) { - /* Clear any eventual previous oscillator IRQ */ - st25r3916GetInterrupt(ST25R3916_IRQ_MASK_OSC); - - /* Enable oscillator frequency stable interrupt */ - st25r3916EnableInterrupts(ST25R3916_IRQ_MASK_OSC); - - /* Enable oscillator and regulator output */ - st25r3916SetRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_en); - - /* Wait for the oscillator interrupt */ - st25r3916WaitForInterruptsTimed(ST25R3916_IRQ_MASK_OSC, ST25R3916_TOUT_OSC_STABLE); - st25r3916DisableInterrupts(ST25R3916_IRQ_MASK_OSC); - } - - if(!st25r3916CheckReg( - ST25R3916_REG_AUX_DISPLAY, - ST25R3916_REG_AUX_DISPLAY_osc_ok, - ST25R3916_REG_AUX_DISPLAY_osc_ok)) { - return ERR_SYSTEM; - } - - return ERR_NONE; -} - -/*******************************************************************************/ -uint8_t st25r3916MeasurePowerSupply(uint8_t mpsv) { - uint8_t result; - - /* Set the source of direct command: Measure Power Supply Voltage */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_REGULATOR_CONTROL, ST25R3916_REG_REGULATOR_CONTROL_mpsv_mask, mpsv); - - /* Execute command: Measure Power Supply Voltage */ - st25r3916ExecuteCommandAndGetResult( - ST25R3916_CMD_MEASURE_VDD, ST25R3916_REG_AD_RESULT, ST25R3916_TOUT_MEASURE_VDD, &result); - - return result; -} - -/*******************************************************************************/ -uint16_t st25r3916MeasureVoltage(uint8_t mpsv) { - uint8_t result; - uint16_t mV; - - result = st25r3916MeasurePowerSupply(mpsv); - - /* Convert cmd output into mV (each step represents 23.4 mV )*/ - mV = ((uint16_t)result) * 23U; - mV += (((((uint16_t)result) * 4U) + 5U) / 10U); - - return mV; -} - -/*******************************************************************************/ -ReturnCode st25r3916AdjustRegulators(uint16_t* result_mV) { - uint8_t result; - - /* Reset logic and set regulated voltages to be defined by result of Adjust Regulators command */ - st25r3916SetRegisterBits( - ST25R3916_REG_REGULATOR_CONTROL, ST25R3916_REG_REGULATOR_CONTROL_reg_s); - st25r3916ClrRegisterBits( - ST25R3916_REG_REGULATOR_CONTROL, ST25R3916_REG_REGULATOR_CONTROL_reg_s); - - /* Execute Adjust regulators cmd and retrieve result */ - st25r3916ExecuteCommandAndGetResult( - ST25R3916_CMD_ADJUST_REGULATORS, - ST25R3916_REG_REGULATOR_RESULT, - ST25R3916_TOUT_ADJUST_REGULATORS, - &result); - - /* Calculate result in mV */ - result >>= ST25R3916_REG_REGULATOR_RESULT_reg_shift; - - if(result_mV != NULL) { - if(st25r3916CheckReg( - ST25R3916_REG_IO_CONF2, - ST25R3916_REG_IO_CONF2_sup3V, - ST25R3916_REG_IO_CONF2_sup3V)) { - result = MIN( - result, - (uint8_t)(result - 5U)); /* In 3.3V mode [0,4] are not used */ - *result_mV = 2400U; /* Minimum regulated voltage 2.4V in case of 3.3V supply */ - } else { - *result_mV = 3600U; /* Minimum regulated voltage 3.6V in case of 5V supply */ - } - - *result_mV += - (uint16_t)result * 100U; /* 100mV steps in both 3.3V and 5V supply */ - } - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916MeasureAmplitude(uint8_t* result) { - return st25r3916ExecuteCommandAndGetResult( - ST25R3916_CMD_MEASURE_AMPLITUDE, - ST25R3916_REG_AD_RESULT, - ST25R3916_TOUT_MEASURE_AMPLITUDE, - result); -} - -/*******************************************************************************/ -ReturnCode st25r3916MeasurePhase(uint8_t* result) { - return st25r3916ExecuteCommandAndGetResult( - ST25R3916_CMD_MEASURE_PHASE, ST25R3916_REG_AD_RESULT, ST25R3916_TOUT_MEASURE_PHASE, result); -} - -/*******************************************************************************/ -ReturnCode st25r3916MeasureCapacitance(uint8_t* result) { - return st25r3916ExecuteCommandAndGetResult( - ST25R3916_CMD_MEASURE_CAPACITANCE, - ST25R3916_REG_AD_RESULT, - ST25R3916_TOUT_MEASURE_CAPACITANCE, - result); -} - -/*******************************************************************************/ -ReturnCode st25r3916CalibrateCapacitiveSensor(uint8_t* result) { - ReturnCode ret; - uint8_t res; - - /* Clear Manual calibration values to enable automatic calibration mode */ - st25r3916ClrRegisterBits( - ST25R3916_REG_CAP_SENSOR_CONTROL, ST25R3916_REG_CAP_SENSOR_CONTROL_cs_mcal_mask); - - /* Execute automatic calibration */ - ret = st25r3916ExecuteCommandAndGetResult( - ST25R3916_CMD_CALIBRATE_C_SENSOR, - ST25R3916_REG_CAP_SENSOR_RESULT, - ST25R3916_TOUT_CALIBRATE_CAP_SENSOR, - &res); - - /* Check whether the calibration was successull */ - if(((res & ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal_end) != - ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal_end) || - ((res & ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal_err) == - ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal_err) || - (ret != ERR_NONE)) { - return ERR_IO; - } - - if(result != NULL) { - (*result) = (uint8_t)(res >> ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal_shift); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916SetBitrate(uint8_t txrate, uint8_t rxrate) { - uint8_t reg; - - st25r3916ReadRegister(ST25R3916_REG_BIT_RATE, ®); - if(rxrate != ST25R3916_BR_DO_NOT_SET) { - if(rxrate > ST25R3916_BR_848) { - return ERR_PARAM; - } - - reg = (uint8_t)(reg & ~ST25R3916_REG_BIT_RATE_rxrate_mask); /* MISRA 10.3 */ - reg |= rxrate << ST25R3916_REG_BIT_RATE_rxrate_shift; - } - if(txrate != ST25R3916_BR_DO_NOT_SET) { - if(txrate > ST25R3916_BR_6780) { - return ERR_PARAM; - } - - reg = (uint8_t)(reg & ~ST25R3916_REG_BIT_RATE_txrate_mask); /* MISRA 10.3 */ - reg |= txrate << ST25R3916_REG_BIT_RATE_txrate_shift; - } - return st25r3916WriteRegister(ST25R3916_REG_BIT_RATE, reg); -} - -/*******************************************************************************/ -ReturnCode st25r3916PerformCollisionAvoidance( - uint8_t FieldONCmd, - uint8_t pdThreshold, - uint8_t caThreshold, - uint8_t nTRFW) { - uint8_t treMask; - uint32_t irqs; - ReturnCode err; - - if((FieldONCmd != ST25R3916_CMD_INITIAL_RF_COLLISION) && - (FieldONCmd != ST25R3916_CMD_RESPONSE_RF_COLLISION_N)) { - return ERR_PARAM; - } - - err = ERR_INTERNAL; - - /* Check if new thresholds are to be applied */ - if((pdThreshold != ST25R3916_THRESHOLD_DO_NOT_SET) || - (caThreshold != ST25R3916_THRESHOLD_DO_NOT_SET)) { - treMask = 0; - - if(pdThreshold != ST25R3916_THRESHOLD_DO_NOT_SET) { - treMask |= ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_mask; - } - - if(caThreshold != ST25R3916_THRESHOLD_DO_NOT_SET) { - treMask |= ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_mask; - } - - /* Set Detection Threshold and|or Collision Avoidance Threshold */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_FIELD_THRESHOLD_ACTV, - treMask, - (pdThreshold & ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_mask) | - (caThreshold & ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_mask)); - } - - /* Set n x TRFW */ - st25r3916ChangeRegisterBits(ST25R3916_REG_AUX, ST25R3916_REG_AUX_nfc_n_mask, nTRFW); - - /*******************************************************************************/ - /* Enable and clear CA specific interrupts and execute command */ - st25r3916GetInterrupt( - (ST25R3916_IRQ_MASK_CAC | ST25R3916_IRQ_MASK_CAT | ST25R3916_IRQ_MASK_APON)); - st25r3916EnableInterrupts( - (ST25R3916_IRQ_MASK_CAC | ST25R3916_IRQ_MASK_CAT | ST25R3916_IRQ_MASK_APON)); - - st25r3916ExecuteCommand(FieldONCmd); - - /*******************************************************************************/ - /* Wait for initial APON interrupt, indicating anticollision avoidance done and ST25R3916's - * field is now on, or a CAC indicating a collision */ - irqs = st25r3916WaitForInterruptsTimed( - (ST25R3916_IRQ_MASK_CAC | ST25R3916_IRQ_MASK_APON), ST25R3916_TOUT_CA); - - if((ST25R3916_IRQ_MASK_CAC & irqs) != 0U) /* Collision occurred */ - { - err = ERR_RF_COLLISION; - } else if((ST25R3916_IRQ_MASK_APON & irqs) != 0U) { - /* After APON wait for CAT interrupt, indication field was switched on minimum guard time has been fulfilled */ - irqs = st25r3916WaitForInterruptsTimed((ST25R3916_IRQ_MASK_CAT), ST25R3916_TOUT_CA); - - if((ST25R3916_IRQ_MASK_CAT & irqs) != 0U) /* No Collision detected, Field On */ - { - err = ERR_NONE; - } - } else { - /* MISRA 15.7 - Empty else */ - } - - /* Clear any previous External Field events and disable CA specific interrupts */ - st25r3916GetInterrupt((ST25R3916_IRQ_MASK_EOF | ST25R3916_IRQ_MASK_EON)); - st25r3916DisableInterrupts( - (ST25R3916_IRQ_MASK_CAC | ST25R3916_IRQ_MASK_CAT | ST25R3916_IRQ_MASK_APON)); - - return err; -} - -/*******************************************************************************/ -void st25r3916SetNumTxBits(uint16_t nBits) { - st25r3916WriteRegister(ST25R3916_REG_NUM_TX_BYTES2, (uint8_t)((nBits >> 0) & 0xFFU)); - st25r3916WriteRegister(ST25R3916_REG_NUM_TX_BYTES1, (uint8_t)((nBits >> 8) & 0xFFU)); -} - -/*******************************************************************************/ -uint16_t st25r3916GetNumFIFOBytes(void) { - uint8_t reg; - uint16_t result; - - st25r3916ReadRegister(ST25R3916_REG_FIFO_STATUS2, ®); - reg = - ((reg & ST25R3916_REG_FIFO_STATUS2_fifo_b_mask) >> - ST25R3916_REG_FIFO_STATUS2_fifo_b_shift); - result = ((uint16_t)reg << 8); - - st25r3916ReadRegister(ST25R3916_REG_FIFO_STATUS1, ®); - result |= (((uint16_t)reg) & 0x00FFU); - - return result; -} - -/*******************************************************************************/ -uint8_t st25r3916GetNumFIFOLastBits(void) { - uint8_t reg; - - st25r3916ReadRegister(ST25R3916_REG_FIFO_STATUS2, ®); - - return ( - (reg & ST25R3916_REG_FIFO_STATUS2_fifo_lb_mask) >> - ST25R3916_REG_FIFO_STATUS2_fifo_lb_shift); -} - -/*******************************************************************************/ -uint32_t st25r3916GetNoResponseTime(void) { - return gST25R3916NRT_64fcs; -} - -/*******************************************************************************/ -ReturnCode st25r3916SetNoResponseTime(uint32_t nrt_64fcs) { - ReturnCode err; - uint8_t nrt_step; - uint32_t tmpNRT; - - tmpNRT = nrt_64fcs; /* MISRA 17.8 */ - err = ERR_NONE; - - gST25R3916NRT_64fcs = tmpNRT; /* Store given NRT value in 64/fc into local var */ - nrt_step = - ST25R3916_REG_TIMER_EMV_CONTROL_nrt_step_64fc; /* Set default NRT in steps of 64/fc */ - - if(tmpNRT > ST25R3916_NRT_MAX) /* Check if the given NRT value fits using 64/fc steps */ - { - nrt_step = - ST25R3916_REG_TIMER_EMV_CONTROL_nrt_step_4096_fc; /* If not, change NRT set to 4096/fc */ - tmpNRT = ((tmpNRT + 63U) / 64U); /* Calculate number of steps in 4096/fc */ - - if(tmpNRT > ST25R3916_NRT_MAX) /* Check if the NRT value fits using 64/fc steps */ - { - tmpNRT = ST25R3916_NRT_MAX; /* Assign the maximum possible */ - err = ERR_PARAM; /* Signal parameter error */ - } - gST25R3916NRT_64fcs = (64U * tmpNRT); - } - - /* Set the ST25R3916 NRT step units and the value */ - st25r3916ChangeRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, ST25R3916_REG_TIMER_EMV_CONTROL_nrt_step, nrt_step); - st25r3916WriteRegister(ST25R3916_REG_NO_RESPONSE_TIMER1, (uint8_t)(tmpNRT >> 8U)); - st25r3916WriteRegister(ST25R3916_REG_NO_RESPONSE_TIMER2, (uint8_t)(tmpNRT & 0xFFU)); - - return err; -} - -/*******************************************************************************/ -ReturnCode st25r3916SetStartNoResponseTimer(uint32_t nrt_64fcs) { - ReturnCode err; - - err = st25r3916SetNoResponseTime(nrt_64fcs); - if(err == ERR_NONE) { - st25r3916ExecuteCommand(ST25R3916_CMD_START_NO_RESPONSE_TIMER); - } - - return err; -} - -/*******************************************************************************/ -void st25r3916SetGPTime(uint16_t gpt_8fcs) { - st25r3916WriteRegister(ST25R3916_REG_GPT1, (uint8_t)(gpt_8fcs >> 8)); - st25r3916WriteRegister(ST25R3916_REG_GPT2, (uint8_t)(gpt_8fcs & 0xFFU)); -} - -/*******************************************************************************/ -ReturnCode st25r3916SetStartGPTimer(uint16_t gpt_8fcs, uint8_t trigger_source) { - st25r3916SetGPTime(gpt_8fcs); - st25r3916ChangeRegisterBits( - ST25R3916_REG_TIMER_EMV_CONTROL, - ST25R3916_REG_TIMER_EMV_CONTROL_gptc_mask, - trigger_source); - - /* If there's no trigger source, start GPT immediately */ - if(trigger_source == ST25R3916_REG_TIMER_EMV_CONTROL_gptc_no_trigger) { - st25r3916ExecuteCommand(ST25R3916_CMD_START_GP_TIMER); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -bool st25r3916CheckChipID(uint8_t* rev) { - uint8_t ID; - - ID = 0; - st25r3916ReadRegister(ST25R3916_REG_IC_IDENTITY, &ID); - - /* Check if IC Identity Register contains ST25R3916's IC type code */ - if((ID & ST25R3916_REG_IC_IDENTITY_ic_type_mask) != - ST25R3916_REG_IC_IDENTITY_ic_type_st25r3916) { - return false; - } - - if(rev != NULL) { - *rev = (ID & ST25R3916_REG_IC_IDENTITY_ic_rev_mask); - } - - return true; -} - -/*******************************************************************************/ -ReturnCode st25r3916GetRegsDump(t_st25r3916Regs* regDump) { - uint8_t regIt; - - if(regDump == NULL) { - return ERR_PARAM; - } - - /* Dump Registers on space A */ - for(regIt = ST25R3916_REG_IO_CONF1; regIt <= ST25R3916_REG_IC_IDENTITY; regIt++) { - st25r3916ReadRegister(regIt, ®Dump->RsA[regIt]); - } - - regIt = 0; - - /* Read non-consecutive Registers on space B */ - st25r3916ReadRegister(ST25R3916_REG_EMD_SUP_CONF, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_SUBC_START_TIME, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_P2P_RX_CONF, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_CORR_CONF1, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_CORR_CONF2, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_SQUELCH_TIMER, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_FIELD_ON_GT, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_AUX_MOD, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_TX_DRIVER_TIMING, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_RES_AM_MOD, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_TX_DRIVER_STATUS, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_REGULATOR_RESULT, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_OVERSHOOT_CONF1, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_OVERSHOOT_CONF2, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_UNDERSHOOT_CONF1, ®Dump->RsB[regIt++]); - st25r3916ReadRegister(ST25R3916_REG_UNDERSHOOT_CONF2, ®Dump->RsB[regIt++]); - - return ERR_NONE; -} - -/*******************************************************************************/ -bool st25r3916IsCmdValid(uint8_t cmd) { - if(!((cmd >= ST25R3916_CMD_SET_DEFAULT) && (cmd <= ST25R3916_CMD_RESPONSE_RF_COLLISION_N)) && - !((cmd >= ST25R3916_CMD_GOTO_SENSE) && (cmd <= ST25R3916_CMD_GOTO_SLEEP)) && - !((cmd >= ST25R3916_CMD_MASK_RECEIVE_DATA) && (cmd <= ST25R3916_CMD_MEASURE_AMPLITUDE)) && - !((cmd >= ST25R3916_CMD_RESET_RXGAIN) && (cmd <= ST25R3916_CMD_ADJUST_REGULATORS)) && - !((cmd >= ST25R3916_CMD_CALIBRATE_DRIVER_TIMING) && - (cmd <= ST25R3916_CMD_START_PPON2_TIMER)) && - (cmd != ST25R3916_CMD_SPACE_B_ACCESS) && (cmd != ST25R3916_CMD_STOP_NRT)) { - return false; - } - return true; -} - -/*******************************************************************************/ -ReturnCode st25r3916StreamConfigure(const struct st25r3916StreamConfig* config) { - uint8_t smd; - uint8_t mode; - - smd = 0; - - if(config->useBPSK != 0U) { - mode = ST25R3916_REG_MODE_om_bpsk_stream; - if((config->din < 2U) || (config->din > 4U)) /* not in fc/4 .. fc/16 */ - { - return ERR_PARAM; - } - smd |= ((4U - config->din) << ST25R3916_REG_STREAM_MODE_scf_shift); - } else { - mode = ST25R3916_REG_MODE_om_subcarrier_stream; - if((config->din < 3U) || (config->din > 6U)) /* not in fc/8 .. fc/64 */ - { - return ERR_PARAM; - } - smd |= ((6U - config->din) << ST25R3916_REG_STREAM_MODE_scf_shift); - if(config->report_period_length == 0U) { - return ERR_PARAM; - } - } - - if((config->dout < 1U) || (config->dout > 7U)) /* not in fc/2 .. fc/128 */ - { - return ERR_PARAM; - } - smd |= (7U - config->dout) << ST25R3916_REG_STREAM_MODE_stx_shift; - - if(config->report_period_length > 3U) { - return ERR_PARAM; - } - smd |= (config->report_period_length << ST25R3916_REG_STREAM_MODE_scp_shift); - - st25r3916WriteRegister(ST25R3916_REG_STREAM_MODE, smd); - st25r3916ChangeRegisterBits(ST25R3916_REG_MODE, ST25R3916_REG_MODE_om_mask, mode); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916GetRSSI(uint16_t* amRssi, uint16_t* pmRssi) { - /*******************************************************************************/ - /* MISRA 8.9 An object should be defined at block scope if its identifier only appears in a single function */ - /*< ST25R3916 RSSI Display Reg values: 0 1 2 3 4 5 6 7 8 9 a b c d e f */ - static const uint16_t st25r3916Rssi2mV[] = { - 0, 20, 27, 37, 52, 72, 99, 136, 190, 262, 357, 500, 686, 950, 1150, 1150}; - - /* ST25R3916 2/3 stage gain reduction [dB] 0 0 0 0 0 3 6 9 12 15 18 na na na na na */ - static const uint16_t st25r3916Gain2Percent[] = { - 100, 100, 100, 100, 100, 141, 200, 281, 398, 562, 794, 1, 1, 1, 1, 1}; - /*******************************************************************************/ - - uint8_t rssi; - uint8_t gainRed; - - st25r3916ReadRegister(ST25R3916_REG_RSSI_RESULT, &rssi); - st25r3916ReadRegister(ST25R3916_REG_GAIN_RED_STATE, &gainRed); - - if(amRssi != NULL) { - *amRssi = - (uint16_t)(((uint32_t)st25r3916Rssi2mV[(rssi >> ST25R3916_REG_RSSI_RESULT_rssi_am_shift)] * (uint32_t)st25r3916Gain2Percent[(gainRed >> ST25R3916_REG_GAIN_RED_STATE_gs_am_shift)]) / 100U); - } - - if(pmRssi != NULL) { - *pmRssi = - (uint16_t)(((uint32_t)st25r3916Rssi2mV[(rssi & ST25R3916_REG_RSSI_RESULT_rssi_pm_mask)] * (uint32_t)st25r3916Gain2Percent[(gainRed & ST25R3916_REG_GAIN_RED_STATE_gs_pm_mask)]) / 100U); - } - - return ERR_NONE; -} diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916.h b/lib/ST25RFAL002/source/st25r3916/st25r3916.h deleted file mode 100644 index 2ba202d86..000000000 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916.h +++ /dev/null @@ -1,669 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Gustavo Patricio - * - * \brief ST25R3916 high level interface - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-HAL - * \brief RFAL Hardware Abstraction Layer - * @{ - * - * \addtogroup ST25R3916 - * \brief RFAL ST25R3916 Driver - * @{ - * - * \addtogroup ST25R3916_Driver - * \brief RFAL ST25R3916 Driver - * @{ - * - */ - -#ifndef ST25R3916_H -#define ST25R3916_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "platform.h" -#include "st_errno.h" -#include "st25r3916_com.h" - -/* -****************************************************************************** -* GLOBAL DATATYPES -****************************************************************************** -*/ - -/*! Struct to represent all regs on ST25R3916 */ -typedef struct { - uint8_t RsA[( - ST25R3916_REG_IC_IDENTITY + 1U)]; /*!< Registers contained on ST25R3916 space A (Rs-A) */ - uint8_t - RsB[ST25R3916_SPACE_B_REG_LEN]; /*!< Registers contained on ST25R3916 space B (Rs-B) */ -} t_st25r3916Regs; - -/*! Parameters how the stream mode should work */ -struct st25r3916StreamConfig { - uint8_t useBPSK; /*!< 0: subcarrier, 1:BPSK */ - uint8_t din; /*!< Divider for the in subcarrier frequency: fc/2^din */ - uint8_t dout; /*!< Divider for the in subcarrier frequency fc/2^dout */ - uint8_t report_period_length; /*!< Length of the reporting period 2^report_period_length*/ -}; - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ - -/* ST25R3916 direct commands */ -#define ST25R3916_CMD_SET_DEFAULT \ - 0xC1U /*!< Puts the chip in default state (same as after power-up) */ -#define ST25R3916_CMD_STOP 0xC2U /*!< Stops all activities and clears FIFO */ -#define ST25R3916_CMD_TRANSMIT_WITH_CRC \ - 0xC4U /*!< Transmit with CRC */ -#define ST25R3916_CMD_TRANSMIT_WITHOUT_CRC \ - 0xC5U /*!< Transmit without CRC */ -#define ST25R3916_CMD_TRANSMIT_REQA \ - 0xC6U /*!< Transmit REQA */ -#define ST25R3916_CMD_TRANSMIT_WUPA \ - 0xC7U /*!< Transmit WUPA */ -#define ST25R3916_CMD_INITIAL_RF_COLLISION \ - 0xC8U /*!< NFC transmit with Initial RF Collision Avoidance */ -#define ST25R3916_CMD_RESPONSE_RF_COLLISION_N \ - 0xC9U /*!< NFC transmit with Response RF Collision Avoidance */ -#define ST25R3916_CMD_GOTO_SENSE \ - 0xCDU /*!< Passive target logic to Sense/Idle state */ -#define ST25R3916_CMD_GOTO_SLEEP \ - 0xCEU /*!< Passive target logic to Sleep/Halt state */ -#define ST25R3916_CMD_MASK_RECEIVE_DATA \ - 0xD0U /*!< Mask receive data */ -#define ST25R3916_CMD_UNMASK_RECEIVE_DATA \ - 0xD1U /*!< Unmask receive data */ -#define ST25R3916_CMD_AM_MOD_STATE_CHANGE \ - 0xD2U /*!< AM Modulation state change */ -#define ST25R3916_CMD_MEASURE_AMPLITUDE \ - 0xD3U /*!< Measure signal amplitude on RFI inputs */ -#define ST25R3916_CMD_RESET_RXGAIN \ - 0xD5U /*!< Reset RX Gain */ -#define ST25R3916_CMD_ADJUST_REGULATORS \ - 0xD6U /*!< Adjust regulators */ -#define ST25R3916_CMD_CALIBRATE_DRIVER_TIMING \ - 0xD8U /*!< Starts the sequence to adjust the driver timing */ -#define ST25R3916_CMD_MEASURE_PHASE \ - 0xD9U /*!< Measure phase between RFO and RFI signal */ -#define ST25R3916_CMD_CLEAR_RSSI \ - 0xDAU /*!< Clear RSSI bits and restart the measurement */ -#define ST25R3916_CMD_CLEAR_FIFO \ - 0xDBU /*!< Clears FIFO, Collision and IRQ status */ -#define ST25R3916_CMD_TRANSPARENT_MODE \ - 0xDCU /*!< Transparent mode */ -#define ST25R3916_CMD_CALIBRATE_C_SENSOR \ - 0xDDU /*!< Calibrate the capacitive sensor */ -#define ST25R3916_CMD_MEASURE_CAPACITANCE \ - 0xDEU /*!< Measure capacitance */ -#define ST25R3916_CMD_MEASURE_VDD \ - 0xDFU /*!< Measure power supply voltage */ -#define ST25R3916_CMD_START_GP_TIMER \ - 0xE0U /*!< Start the general purpose timer */ -#define ST25R3916_CMD_START_WUP_TIMER \ - 0xE1U /*!< Start the wake-up timer */ -#define ST25R3916_CMD_START_MASK_RECEIVE_TIMER \ - 0xE2U /*!< Start the mask-receive timer */ -#define ST25R3916_CMD_START_NO_RESPONSE_TIMER \ - 0xE3U /*!< Start the no-response timer */ -#define ST25R3916_CMD_START_PPON2_TIMER \ - 0xE4U /*!< Start PPon2 timer */ -#define ST25R3916_CMD_STOP_NRT \ - 0xE8U /*!< Stop No Response Timer */ -#define ST25R3916_CMD_SPACE_B_ACCESS \ - 0xFBU /*!< Enable R/W access to the test registers */ -#define ST25R3916_CMD_TEST_ACCESS \ - 0xFCU /*!< Enable R/W access to the test registers */ - -#define ST25R3916_THRESHOLD_DO_NOT_SET \ - 0xFFU /*!< Indicates not to change this Threshold */ - -#define ST25R3916_BR_DO_NOT_SET \ - 0xFFU /*!< Indicates not to change this Bit Rate */ -#define ST25R3916_BR_106 0x00U /*!< ST25R3916 Bit Rate 106 kbit/s (fc/128) */ -#define ST25R3916_BR_212 0x01U /*!< ST25R3916 Bit Rate 212 kbit/s (fc/64) */ -#define ST25R3916_BR_424 0x02U /*!< ST25R3916 Bit Rate 424 kbit/s (fc/32) */ -#define ST25R3916_BR_848 0x03U /*!< ST25R3916 Bit Rate 848 kbit/s (fc/16) */ -#define ST25R3916_BR_1695 0x04U /*!< ST25R3916 Bit Rate 1696 kbit/s (fc/8) */ -#define ST25R3916_BR_3390 0x05U /*!< ST25R3916 Bit Rate 3390 kbit/s (fc/4) */ -#define ST25R3916_BR_6780 0x07U /*!< ST25R3916 Bit Rate 6780 kbit/s (fc/2) */ - -#define ST25R3916_FIFO_DEPTH 512U /*!< Depth of FIFO */ -#define ST25R3916_TOUT_OSC_STABLE \ - 10U /*!< Max timeout for Oscillator to get stable DS: 700us */ - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ - -/*! Enables the Transmitter (Field On) and Receiver */ -#define st25r3916TxRxOn() \ - st25r3916SetRegisterBits( \ - ST25R3916_REG_OP_CONTROL, \ - (ST25R3916_REG_OP_CONTROL_rx_en | ST25R3916_REG_OP_CONTROL_tx_en)) - -/*! Disables the Transmitter (Field Off) and Receiver */ -#define st25r3916TxRxOff() \ - st25r3916ClrRegisterBits( \ - ST25R3916_REG_OP_CONTROL, \ - (ST25R3916_REG_OP_CONTROL_rx_en | ST25R3916_REG_OP_CONTROL_tx_en)) - -/*! Disables the Transmitter (Field Off) */ -#define st25r3916TxOff() \ - st25r3916ClrRegisterBits(ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_tx_en) - -/*! Checks if General Purpose Timer is still running by reading gpt_on flag */ -#define st25r3916IsGPTRunning() \ - st25r3916CheckReg( \ - ST25R3916_REG_NFCIP1_BIT_RATE, \ - ST25R3916_REG_NFCIP1_BIT_RATE_gpt_on, \ - ST25R3916_REG_NFCIP1_BIT_RATE_gpt_on) - -/*! Checks if External Filed is detected by reading ST25R3916 External Field Detector output */ -#define st25r3916IsExtFieldOn() \ - st25r3916CheckReg( \ - ST25R3916_REG_AUX_DISPLAY, \ - ST25R3916_REG_AUX_DISPLAY_efd_o, \ - ST25R3916_REG_AUX_DISPLAY_efd_o) - -/*! Checks if Transmitter is enabled (Field On) */ -#define st25r3916IsTxEnabled() \ - st25r3916CheckReg( \ - ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_tx_en, ST25R3916_REG_OP_CONTROL_tx_en) - -/*! Checks if NRT is in EMV mode */ -#define st25r3916IsNRTinEMV() \ - st25r3916CheckReg( \ - ST25R3916_REG_TIMER_EMV_CONTROL, \ - ST25R3916_REG_TIMER_EMV_CONTROL_nrt_emv, \ - ST25R3916_REG_TIMER_EMV_CONTROL_nrt_emv_on) - -/*! Checks if last FIFO byte is complete */ -#define st25r3916IsLastFIFOComplete() \ - st25r3916CheckReg(ST25R3916_REG_FIFO_STATUS2, ST25R3916_REG_FIFO_STATUS2_fifo_lb_mask, 0) - -/*! Checks if the Oscillator is enabled */ -#define st25r3916IsOscOn() \ - st25r3916CheckReg( \ - ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_en, ST25R3916_REG_OP_CONTROL_en) - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Initialise ST25R3916 driver - * - * This function initialises the ST25R3916 driver. - * - * \return ERR_NONE : Operation successful - * \return ERR_HW_MISMATCH : Expected HW do not match or communication error - * \return ERR_IO : Error during communication selftest. Check communication interface - * \return ERR_TIMEOUT : Timeout during IRQ selftest. Check IRQ handling - * \return ERR_SYSTEM : Failure during oscillator activation or timer error - * - ***************************************************************************** - */ -ReturnCode st25r3916Initialize(void); - -/*! - ***************************************************************************** - * \brief Deinitialize ST25R3916 driver - * - * Calling this function deinitializes the ST25R3916 driver. - * - ***************************************************************************** - */ -void st25r3916Deinitialize(void); - -/*! - ***************************************************************************** - * \brief Turn on Oscillator and Regulator - * - * This function turn on oscillator and regulator and waits for the - * oscillator to become stable - * - * \return ERR_SYSTEM : Failure dusring Oscillator activation - * \return ERR_NONE : No error, Oscillator is active and stable, Regulator is on - * - ***************************************************************************** - */ -ReturnCode st25r3916OscOn(void); - -/*! - ***************************************************************************** - * \brief Sets the bitrate - * - * This function sets the bitrates for rx and tx - * - * \param txrate : speed is 2^txrate * 106 kb/s - * 0xff : don't set txrate (ST25R3916_BR_DO_NOT_SET) - * \param rxrate : speed is 2^rxrate * 106 kb/s - * 0xff : don't set rxrate (ST25R3916_BR_DO_NOT_SET) - * - * \return ERR_PARAM: At least one bit rate was invalid - * \return ERR_NONE : No error, both bit rates were set - * - ***************************************************************************** - */ -ReturnCode st25r3916SetBitrate(uint8_t txrate, uint8_t rxrate); - -/*! - ***************************************************************************** - * \brief Adjusts supply regulators according to the current supply voltage - * - * This function the power level is measured in maximum load conditions and - * the regulated voltage reference is set to 250mV below this level. - * Execution of this function lasts around 5ms. - * - * The regulated voltages will be set to the result of Adjust Regulators - * - * \param [out] result_mV : Result of calibration in milliVolts - * - * \return ERR_IO : Error during communication with ST25R3916 - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode st25r3916AdjustRegulators(uint16_t* result_mV); - -/*! - ***************************************************************************** - * \brief Measure Amplitude - * - * This function measured the amplitude on the RFI inputs and stores the - * result in parameter \a result. - * - * \param[out] result: result of RF measurement. - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode st25r3916MeasureAmplitude(uint8_t* result); - -/*! - ***************************************************************************** - * \brief Measure Power Supply - * - * This function executes Measure Power Supply and returns the raw value - * - * \param[in] mpsv : one of ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd - * ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_rf - * ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_a - * ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_d - * ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_am - * - * \return the measured voltage in raw format. - * - ***************************************************************************** - */ -uint8_t st25r3916MeasurePowerSupply(uint8_t mpsv); - -/*! - ***************************************************************************** - * \brief Measure Voltage - * - * This function measures the voltage on one of VDD and VDD_* and returns - * the result in mV - * - * \param[in] mpsv : one of ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd - * ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_rf - * ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_a - * ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_d - * or ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_am - * - * \return the measured voltage in mV - * - ***************************************************************************** - */ -uint16_t st25r3916MeasureVoltage(uint8_t mpsv); - -/*! - ***************************************************************************** - * \brief Measure Phase - * - * This function performs a Phase measurement. - * The result is stored in the \a result parameter. - * - * \param[out] result: 8 bit long result of the measurement. - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode st25r3916MeasurePhase(uint8_t* result); - -/*! - ***************************************************************************** - * \brief Measure Capacitance - * - * This function performs the capacitance measurement and stores the - * result in parameter \a result. - * - * \param[out] result: 8 bit long result of RF measurement. - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode st25r3916MeasureCapacitance(uint8_t* result); - -/*! - ***************************************************************************** - * \brief Calibrates Capacitive Sensor - * - * This function performs automatic calibration of the capacitive sensor - * and stores the result in parameter \a result. - * - * \warning To avoid interference with Xtal oscillator and reader magnetic - * field, it is strongly recommended to perform calibration - * in Power-down mode only. - * This method does not modify the Oscillator nor transmitter state, - * these should be configured before by user. - * - * \param[out] result: 5 bit long result of the calibration. - * Binary weighted, step 0.1 pF, max 3.1 pF - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_IO : The calibration was not successful - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode st25r3916CalibrateCapacitiveSensor(uint8_t* result); - -/*! - ***************************************************************************** - * \brief Get NRT time - * - * This returns the last value set on the NRT - * - * \warning it does not read chip register, just the sw var that contains the - * last value set before - * - * \return the value of the NRT in 64/fc - */ -uint32_t st25r3916GetNoResponseTime(void); - -/*! - ***************************************************************************** - * \brief Set NRT time - * - * This function sets the No Response Time with the given value - * - * \param [in] nrt_64fcs : no response time in steps of 64/fc (4.72us) - * - * \return ERR_PARAM : Invalid parameter (time is too large) - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode st25r3916SetNoResponseTime(uint32_t nrt_64fcs); - -/*! - ***************************************************************************** - * \brief Set and Start NRT - * - * This function sets the No Response Time with the given value and - * immediately starts it - * Used when needs to add more time before timeout without performing Tx - * - * \param [in] nrt_64fcs : no response time in steps of 64/fc (4.72us) - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode st25r3916SetStartNoResponseTimer(uint32_t nrt_64fcs); - -/*! - ***************************************************************************** - * \brief Set GPT time - * - * This function sets the General Purpose Timer time registers - * - * \param [in] gpt_8fcs : general purpose timer timeout in steps of 8/fc (590ns) - * - ***************************************************************************** - */ -void st25r3916SetGPTime(uint16_t gpt_8fcs); - -/*! - ***************************************************************************** - * \brief Set and Start GPT - * - * This function sets the General Purpose Timer with the given timeout and - * immediately starts it ONLY if the trigger source is not set to none. - * - * \param [in] gpt_8fcs : general purpose timer timeout in steps of8/fc (590ns) - * \param [in] trigger_source : no trigger, start of Rx, end of Rx, end of Tx in NFC mode - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode st25r3916SetStartGPTimer(uint16_t gpt_8fcs, uint8_t trigger_source); - -/*! - ***************************************************************************** - * \brief Sets the number Tx Bits - * - * Sets ST25R3916 internal registers with correct number of complete bytes and - * bits to be sent - * - * \param [in] nBits : number of bits to be set/transmitted - * - ***************************************************************************** - */ -void st25r3916SetNumTxBits(uint16_t nBits); - -/*! - ***************************************************************************** - * \brief Get amount of bytes in FIFO - * - * Gets the number of bytes currently in the FIFO - * - * \return the number of bytes currently in the FIFO - * - ***************************************************************************** - */ -uint16_t st25r3916GetNumFIFOBytes(void); - -/*! - ***************************************************************************** - * \brief Get amount of bits of the last FIFO byte if incomplete - * - * Gets the number of bits of the last FIFO byte if incomplete - * - * \return the number of bits of the last FIFO byte if incomplete, 0 if - * the last byte is complete - * - ***************************************************************************** - */ -uint8_t st25r3916GetNumFIFOLastBits(void); - -/*! - ***************************************************************************** - * \brief Perform Collision Avoidance - * - * Performs Collision Avoidance with the given threshold and with the - * n number of TRFW - * - * \param[in] FieldONCmd : Field ON command to be executed ST25R3916_CMD_INITIAL_RF_COLLISION - * or ST25R3916_CMD_RESPONSE_RF_COLLISION_N - * \param[in] pdThreshold : Peer Detection Threshold (ST25R3916_REG_FIELD_THRESHOLD_trg_xx) - * 0xff : don't set Threshold (ST25R3916_THRESHOLD_DO_NOT_SET) - * \param[in] caThreshold : Collision Avoidance Threshold (ST25R3916_REG_FIELD_THRESHOLD_rfe_xx) - * 0xff : don't set Threshold (ST25R3916_THRESHOLD_DO_NOT_SET) - * \param[in] nTRFW : Number of TRFW - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_RF_COLLISION : Collision detected - * \return ERR_NONE : No collision detected - * - ***************************************************************************** - */ -ReturnCode st25r3916PerformCollisionAvoidance( - uint8_t FieldONCmd, - uint8_t pdThreshold, - uint8_t caThreshold, - uint8_t nTRFW); - -/*! - ***************************************************************************** - * \brief Check Identity - * - * Checks if the chip ID is as expected. - * - * 5 bit IC type code for ST25R3916: 00101 - * The 3 lsb contain the IC revision code - * - * \param[out] rev : the IC revision code - * - * \return true when IC type is as expected - * \return false otherwise - */ -bool st25r3916CheckChipID(uint8_t* rev); - -/*! - ***************************************************************************** - * \brief Retrieves all internal registers from ST25R3916 - * - * \param[out] regDump : pointer to the struct/buffer where the reg dump - * will be written - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - ***************************************************************************** - */ -ReturnCode st25r3916GetRegsDump(t_st25r3916Regs* regDump); - -/*! - ***************************************************************************** - * \brief Check if command is valid - * - * Checks if the given command is a valid ST25R3916 command - * - * \param[in] cmd: Command to check - * - * \return true if is a valid command - * \return false otherwise - * - ***************************************************************************** - */ -bool st25r3916IsCmdValid(uint8_t cmd); - -/*! - ***************************************************************************** - * \brief Configure the stream mode of ST25R3916 - * - * This function initializes the stream with the given parameters - * - * \param[in] config : all settings for bitrates, type, etc. - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error, stream mode driver initialized - * - ***************************************************************************** - */ -ReturnCode st25r3916StreamConfigure(const struct st25r3916StreamConfig* config); - -/*! - ***************************************************************************** - * \brief Executes a direct command and returns the result - * - * This function executes the direct command given by \a cmd waits for - * \a sleeptime for I_dct and returns the result read from register \a resreg. - * The value of cmd is not checked. - * - * \param[in] cmd : direct command to execute - * \param[in] resReg: address of the register containing the result - * \param[in] tout : time in milliseconds to wait before reading the result - * \param[out] result: result - * - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode - st25r3916ExecuteCommandAndGetResult(uint8_t cmd, uint8_t resReg, uint8_t tout, uint8_t* result); - -/*! - ***************************************************************************** - * \brief Gets the RSSI values - * - * This function gets the RSSI value of the previous reception taking into - * account the gain reductions that were used. - * RSSI value for both AM and PM channel can be retrieved. - * - * \param[out] amRssi: the RSSI on the AM channel expressed in mV - * \param[out] pmRssi: the RSSI on the PM channel expressed in mV - * - * \return ERR_PARAM : Invalid parameter - * \return ERR_NONE : No error - * - ***************************************************************************** - */ -ReturnCode st25r3916GetRSSI(uint16_t* amRssi, uint16_t* pmRssi); -#endif /* ST25R3916_H */ - -/** - * @} - * - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916_aat.c b/lib/ST25RFAL002/source/st25r3916/st25r3916_aat.c deleted file mode 100644 index 234bb2e99..000000000 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916_aat.c +++ /dev/null @@ -1,366 +0,0 @@ -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file st25r3916_aat.c - * - * \author - * - * \brief ST25R3916 Antenna Tuning - * - * The antenna tuning algorithm tries to find the optimal settings for - * the AAT_A and AAT_B registers, which are connected to variable capacitors - * to tune the antenna matching. - * - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "st25r3916_aat.h" -#include "utils.h" -#include "st_errno.h" -#include "st25r3916.h" -#include "st25r3916_com.h" -#include "platform.h" -#include "rfal_chip.h" - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ -#define ST25R3916_AAT_CAP_DELAY_MAX 10 /*!< Max Variable Capacitor settle delay */ - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ -#define st25r3916AatLog(...) /* platformLog(__VA_ARGS__) */ /*!< Logging macro */ - -/* -****************************************************************************** -* LOCAL FUNCTION PROTOTYPES -****************************************************************************** -*/ -static ReturnCode aatHillClimb( - const struct st25r3916AatTuneParams* tuningParams, - struct st25r3916AatTuneResult* tuningStatus); -static int32_t aatGreedyDescent( - uint32_t* f_min, - const struct st25r3916AatTuneParams* tuningParams, - struct st25r3916AatTuneResult* tuningStatus, - int32_t previousDir); -static int32_t aatSteepestDescent( - uint32_t* f_min, - const struct st25r3916AatTuneParams* tuningParams, - struct st25r3916AatTuneResult* tuningStatus, - int32_t previousDir, - int32_t previousDir2); - -static ReturnCode aatMeasure( - uint8_t serCap, - uint8_t parCap, - uint8_t* amplitude, - uint8_t* phase, - uint16_t* measureCnt); -static uint32_t - aatCalcF(const struct st25r3916AatTuneParams* tuningParams, uint8_t amplitude, uint8_t phase); -static ReturnCode aatStepDacVals( - const struct st25r3916AatTuneParams* tuningParams, - uint8_t* a, - uint8_t* b, - int32_t dir); - -/*******************************************************************************/ -ReturnCode st25r3916AatTune( - const struct st25r3916AatTuneParams* tuningParams, - struct st25r3916AatTuneResult* tuningStatus) { - ReturnCode err; - const struct st25r3916AatTuneParams* tp = tuningParams; - struct st25r3916AatTuneResult* ts = tuningStatus; - struct st25r3916AatTuneParams defaultTuningParams = { - .aat_a_min = 0, - .aat_a_max = 255, - .aat_a_start = 127, - .aat_a_stepWidth = 32, - .aat_b_min = 0, - .aat_b_max = 255, - .aat_b_start = 127, - .aat_b_stepWidth = 32, - - .phaTarget = 128, - .phaWeight = 2, - .ampTarget = 196, - .ampWeight = 1, - - .doDynamicSteps = true, - .measureLimit = 50, - }; - struct st25r3916AatTuneResult defaultTuneResult; - - if((NULL != tp) && ((tp->aat_a_min > tp->aat_a_max) || (tp->aat_a_start < tp->aat_a_min) || - (tp->aat_a_start > tp->aat_a_max) || (tp->aat_b_min > tp->aat_b_max) || - (tp->aat_b_start < tp->aat_b_min) || (tp->aat_b_start > tp->aat_b_max))) { - return ERR_PARAM; - } - - if(NULL == tp) { /* Start from current caps with default params */ - st25r3916ReadRegister(ST25R3916_REG_ANT_TUNE_A, &defaultTuningParams.aat_a_start); - st25r3916ReadRegister(ST25R3916_REG_ANT_TUNE_B, &defaultTuningParams.aat_b_start); - tp = &defaultTuningParams; - } - - if(NULL == ts) { - ts = &defaultTuneResult; - } - - ts->measureCnt = 0; /* Clear current measure count */ - - err = aatHillClimb(tp, ts); - - return err; -} - -/*******************************************************************************/ -static ReturnCode aatHillClimb( - const struct st25r3916AatTuneParams* tuningParams, - struct st25r3916AatTuneResult* tuningStatus) { - ReturnCode err = ERR_NONE; - uint32_t f_min; - int32_t direction, gdirection; - uint8_t amp, phs; - struct st25r3916AatTuneParams tp = *tuningParams; // local copy to obey const - - tuningStatus->aat_a = tuningParams->aat_a_start; - tuningStatus->aat_b = tuningParams->aat_b_start; - - /* Get a proper start value */ - aatMeasure(tuningStatus->aat_a, tuningStatus->aat_b, &, &phs, &tuningStatus->measureCnt); - f_min = aatCalcF(&tp, amp, phs); - direction = 0; - - st25r3916AatLog("%d %d: %d***\n", tuningStatus->aat_a, tuningStatus->aat_b, f_min); - - do { - direction = - 0; /* Initially and after reducing step sizes we don't have a previous direction */ - do { - /* With the greedy step below always executed aftwards the -direction does never need to be investigated */ - direction = aatSteepestDescent(&f_min, &tp, tuningStatus, direction, -direction); - if(tuningStatus->measureCnt > tp.measureLimit) { - err = ERR_OVERRUN; - break; - } - do { - gdirection = aatGreedyDescent(&f_min, &tp, tuningStatus, direction); - if(tuningStatus->measureCnt > tp.measureLimit) { - err = ERR_OVERRUN; - break; - } - } while(0 != gdirection); - } while(0 != direction); - tp.aat_a_stepWidth /= 2U; /* Reduce step sizes */ - tp.aat_b_stepWidth /= 2U; - } while(tp.doDynamicSteps && ((tp.aat_a_stepWidth > 0U) || (tp.aat_b_stepWidth > 0U))); - - return err; -} - -/*******************************************************************************/ -static int32_t aatSteepestDescent( - uint32_t* f_min, - const struct st25r3916AatTuneParams* tuningParams, - struct st25r3916AatTuneResult* tuningStatus, - int32_t previousDir, - int32_t previousDir2) { - int32_t i; - uint8_t amp, phs; - uint32_t f; - int32_t bestdir = - 0; /* Negative direction: decrease, Positive: increase. (-)1: aat_a, (-)2: aat_b */ - - for(i = -2; i <= 2; i++) { - uint8_t a = tuningStatus->aat_a, b = tuningStatus->aat_b; - - if((0 == i) || (i == -previousDir) || - (i == -previousDir2)) { /* Skip no direction and avoid going backwards */ - continue; - } - if(0U != aatStepDacVals( - tuningParams, - &a, - &b, - i)) { /* If stepping did not change the value, omit this direction */ - continue; - } - - aatMeasure(a, b, &, &phs, &tuningStatus->measureCnt); - f = aatCalcF(tuningParams, amp, phs); - st25r3916AatLog("%d : %d %d: %d", i, a, b, f); - if(f < *f_min) { /* Value is better than all previous ones */ - st25r3916AatLog("*"); - *f_min = f; - bestdir = i; - } - st25r3916AatLog("\n"); - } - if(0 != bestdir) { /* Walk into the best direction */ - aatStepDacVals(tuningParams, &tuningStatus->aat_a, &tuningStatus->aat_b, bestdir); - } - return bestdir; -} - -/*******************************************************************************/ -static int32_t aatGreedyDescent( - uint32_t* f_min, - const struct st25r3916AatTuneParams* tuningParams, - struct st25r3916AatTuneResult* tuningStatus, - int32_t previousDir) { - uint8_t amp, phs; - uint32_t f; - uint8_t a = tuningStatus->aat_a, b = tuningStatus->aat_b; - - if(0U != aatStepDacVals( - tuningParams, - &a, - &b, - previousDir)) { /* If stepping did not change the value, omit this direction */ - return 0; - } - - aatMeasure(a, b, &, &phs, &tuningStatus->measureCnt); - f = aatCalcF(tuningParams, amp, phs); - st25r3916AatLog("g : %d %d: %d", a, b, f); - if(f < *f_min) { /* Value is better than previous one */ - st25r3916AatLog("*\n"); - tuningStatus->aat_a = a; - tuningStatus->aat_b = b; - *f_min = f; - return previousDir; - } - - st25r3916AatLog("\n"); - return 0; -} - -/*******************************************************************************/ -static uint32_t - aatCalcF(const struct st25r3916AatTuneParams* tuningParams, uint8_t amplitude, uint8_t phase) { - /* f(amp, pha) = (ampWeight * |amp - ampTarget|) + (phaWeight * |pha - phaTarget|) */ - uint8_t ampTarget = tuningParams->ampTarget; - uint8_t phaTarget = tuningParams->phaTarget; - - uint32_t ampWeight = tuningParams->ampWeight; - uint32_t phaWeight = tuningParams->phaWeight; - - /* Temp variables to avoid MISRA R10.8 (cast on composite expression) */ - uint8_t ad = ((amplitude > ampTarget) ? (amplitude - ampTarget) : (ampTarget - amplitude)); - uint8_t pd = ((phase > phaTarget) ? (phase - phaTarget) : (phaTarget - phase)); - - uint32_t ampDelta = (uint32_t)ad; - uint32_t phaDelta = (uint32_t)pd; - - return ((ampWeight * ampDelta) + (phaWeight * phaDelta)); -} - -/*******************************************************************************/ -static ReturnCode aatStepDacVals( - const struct st25r3916AatTuneParams* tuningParams, - uint8_t* a, - uint8_t* b, - int32_t dir) { - int16_t aat_a = (int16_t)*a, aat_b = (int16_t)*b; - - switch(abs(dir)) { /* Advance by steps size in requested direction */ - case 1: - aat_a = (dir < 0) ? (aat_a - (int16_t)tuningParams->aat_a_stepWidth) : - (aat_a + (int16_t)tuningParams->aat_a_stepWidth); - if(aat_a < (int16_t)tuningParams->aat_a_min) { - aat_a = (int16_t)tuningParams->aat_a_min; - } - if(aat_a > (int16_t)tuningParams->aat_a_max) { - aat_a = (int16_t)tuningParams->aat_a_max; - } - if((int16_t)*a == aat_a) { - return ERR_PARAM; - } - break; - case 2: - aat_b = (dir < 0) ? (aat_b - (int16_t)tuningParams->aat_b_stepWidth) : - (aat_b + (int16_t)tuningParams->aat_b_stepWidth); - if(aat_b < (int16_t)tuningParams->aat_b_min) { - aat_b = (int16_t)tuningParams->aat_b_min; - } - if(aat_b > (int16_t)tuningParams->aat_b_max) { - aat_b = (int16_t)tuningParams->aat_b_max; - } - if((int16_t)*b == aat_b) { - return ERR_PARAM; - } - break; - default: - return ERR_REQUEST; - } - /* We only get here if actual values have changed. In all other cases an error is returned */ - *a = (uint8_t)aat_a; - *b = (uint8_t)aat_b; - - return ERR_NONE; -} - -/*******************************************************************************/ -static ReturnCode aatMeasure( - uint8_t serCap, - uint8_t parCap, - uint8_t* amplitude, - uint8_t* phase, - uint16_t* measureCnt) { - ReturnCode err; - - *amplitude = 0; - *phase = 0; - - st25r3916WriteRegister(ST25R3916_REG_ANT_TUNE_A, serCap); - st25r3916WriteRegister(ST25R3916_REG_ANT_TUNE_B, parCap); - - /* Wait till caps have settled.. */ - platformDelay(ST25R3916_AAT_CAP_DELAY_MAX); - - /* Get amplitude and phase .. */ - err = rfalChipMeasureAmplitude(amplitude); - if(ERR_NONE == err) { - err = rfalChipMeasurePhase(phase); - } - - if(measureCnt != NULL) { - (*measureCnt)++; - } - return err; -} diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916_aat.h b/lib/ST25RFAL002/source/st25r3916/st25r3916_aat.h deleted file mode 100644 index 4c97ad355..000000000 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916_aat.h +++ /dev/null @@ -1,109 +0,0 @@ -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file st25r3916_aat.h - * - * \author - * - * \brief ST25R3916 Antenna Tuning - * - * The antenna tuning algorithm tries to find the optimal settings for - * the AAT_A and AAT_B registers, which are connected to variable capacitors - * to tune the antenna matching. - * - */ - -#ifndef ST25R3916_AAT_H -#define ST25R3916_AAT_H - -#include "platform.h" -#include "st_errno.h" - -/* -****************************************************************************** -* GLOBAL DATATYPES -****************************************************************************** -*/ - -/*! - * struct representing input parameters for the antenna tuning - */ -struct st25r3916AatTuneParams { - uint8_t aat_a_min; /*!< min value of A cap */ - uint8_t aat_a_max; /*!< max value of A cap */ - uint8_t aat_a_start; /*!< start value of A cap */ - uint8_t aat_a_stepWidth; /*!< increment stepWidth for A cap */ - uint8_t aat_b_min; /*!< min value of B cap */ - uint8_t aat_b_max; /*!< max value of B cap */ - uint8_t aat_b_start; /*!< start value of B cap */ - uint8_t aat_b_stepWidth; /*!< increment stepWidth for B cap */ - - uint8_t phaTarget; /*!< target phase */ - uint8_t phaWeight; /*!< weight of target phase */ - uint8_t ampTarget; /*!< target amplitude */ - uint8_t ampWeight; /*!< weight of target amplitude */ - - bool doDynamicSteps; /*!< dynamically reduce step size in algo */ - uint8_t measureLimit; /*!< max number of allowed steps/measurements */ -}; - -/*! - * struct representing out parameters for the antenna tuning - */ -struct st25r3916AatTuneResult { - uint8_t aat_a; /*!< serial cap after tuning */ - uint8_t aat_b; /*!< parallel cap after tuning */ - uint8_t pha; /*!< phase after tuning */ - uint8_t amp; /*!< amplitude after tuning */ - uint16_t measureCnt; /*!< number of measures performed */ -}; - -/*! - ***************************************************************************** - * \brief Perform antenna tuning - * - * This function starts an antenna tuning procedure by modifying the serial - * and parallel capacitors of the antenna matching circuit via the AAT_A - * and AAT_B registers. - * - * \param[in] tuningParams : Input parameters for the tuning algorithm. If NULL - * default values will be used. - * \param[out] tuningStatus : Result information of performed tuning. If NULL - * no further information is returned, only registers - * ST25R3916 (AAT_A,B) will be adapted. - * - * \return ERR_IO : Error during communication. - * \return ERR_PARAM : Invalid input parameters - * \return ERR_NONE : No error. - * - ***************************************************************************** - */ -extern ReturnCode st25r3916AatTune( - const struct st25r3916AatTuneParams* tuningParams, - struct st25r3916AatTuneResult* tuningStatus); - -#endif /* ST25R3916_AAT_H */ diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916_com.c b/lib/ST25RFAL002/source/st25r3916/st25r3916_com.c deleted file mode 100644 index 40d65807d..000000000 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916_com.c +++ /dev/null @@ -1,618 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Gustavo Patricio - * - * \brief Implementation of ST25R3916 communication - * - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ - -#include "st25r3916.h" -#include "st25r3916_com.h" -#include "st25r3916_led.h" -#include "st_errno.h" -#include "platform.h" -#include "utils.h" - -/* -****************************************************************************** -* LOCAL DEFINES -****************************************************************************** -*/ - -#define ST25R3916_OPTIMIZE \ - true /*!< Optimization switch: false always write value to register */ -#define ST25R3916_I2C_ADDR \ - (0xA0U >> 1) /*!< ST25R3916's default I2C address */ -#define ST25R3916_REG_LEN 1U /*!< Byte length of a ST25R3916 register */ - -#define ST25R3916_WRITE_MODE \ - (0U << 6) /*!< ST25R3916 Operation Mode: Write */ -#define ST25R3916_READ_MODE \ - (1U << 6) /*!< ST25R3916 Operation Mode: Read */ -#define ST25R3916_CMD_MODE \ - (3U << 6) /*!< ST25R3916 Operation Mode: Direct Command */ -#define ST25R3916_FIFO_LOAD \ - (0x80U) /*!< ST25R3916 Operation Mode: FIFO Load */ -#define ST25R3916_FIFO_READ \ - (0x9FU) /*!< ST25R3916 Operation Mode: FIFO Read */ -#define ST25R3916_PT_A_CONFIG_LOAD \ - (0xA0U) /*!< ST25R3916 Operation Mode: Passive Target Memory A-Config Load */ -#define ST25R3916_PT_F_CONFIG_LOAD \ - (0xA8U) /*!< ST25R3916 Operation Mode: Passive Target Memory F-Config Load */ -#define ST25R3916_PT_TSN_DATA_LOAD \ - (0xACU) /*!< ST25R3916 Operation Mode: Passive Target Memory TSN Load */ -#define ST25R3916_PT_MEM_READ \ - (0xBFU) /*!< ST25R3916 Operation Mode: Passive Target Memory Read */ - -#define ST25R3916_CMD_LEN \ - (1U) /*!< ST25R3916 CMD length */ -#define ST25R3916_BUF_LEN \ - (ST25R3916_CMD_LEN + \ - ST25R3916_FIFO_DEPTH) /*!< ST25R3916 communication buffer: CMD + FIFO length */ - -/* -****************************************************************************** -* MACROS -****************************************************************************** -*/ -#ifdef RFAL_USE_I2C -#define st25r3916I2CStart() \ - platformI2CStart() /*!< ST25R3916 HAL I2C driver macro to start a I2C transfer */ -#define st25r3916I2CStop() \ - platformI2CStop() /*!< ST25R3916 HAL I2C driver macro to stop a I2C transfer */ -#define st25r3916I2CRepeatStart() \ - platformI2CRepeatStart() /*!< ST25R3916 HAL I2C driver macro to repeat Start */ -#define st25r3916I2CSlaveAddrWR(sA) \ - platformI2CSlaveAddrWR( \ - sA) /*!< ST25R3916 HAL I2C driver macro to repeat Start */ -#define st25r3916I2CSlaveAddrRD(sA) \ - platformI2CSlaveAddrRD( \ - sA) /*!< ST25R3916 HAL I2C driver macro to repeat Start */ -#endif /* RFAL_USE_I2C */ - -#if defined(ST25R_COM_SINGLETXRX) && !defined(RFAL_USE_I2C) -static uint8_t - comBuf[ST25R3916_BUF_LEN]; /*!< ST25R3916 communication buffer */ -static uint16_t comBufIt; /*!< ST25R3916 communication buffer iterator */ -#endif /* ST25R_COM_SINGLETXRX */ - -/* - ****************************************************************************** - * LOCAL FUNCTION PROTOTYPES - ****************************************************************************** - */ - -/*! - ****************************************************************************** - * \brief ST25R3916 communication Start - * - * This method performs the required actions to start communications with - * ST25R3916, either by SPI or I2C - ****************************************************************************** - */ -static void st25r3916comStart(void); - -/*! - ****************************************************************************** - * \brief ST25R3916 communication Stop - * - * This method performs the required actions to terminate communications with - * ST25R3916, either by SPI or I2C - ****************************************************************************** - */ -static void st25r3916comStop(void); - -/*! - ****************************************************************************** - * \brief ST25R3916 communication Repeat Start - * - * This method performs the required actions to repeat start a transmission - * with ST25R3916, either by SPI or I2C - ****************************************************************************** - */ -#ifdef RFAL_USE_I2C -static void st25r3916comRepeatStart(void); -#else -#define st25r3916comRepeatStart() -#endif /* RFAL_USE_I2C */ - -/*! - ****************************************************************************** - * \brief ST25R3916 communication Tx - * - * This method performs the required actions to transmit the given buffer - * to ST25R3916, either by SPI or I2C - * - * \param[in] txBuf : the buffer to transmit - * \param[in] txLen : the length of the buffer to transmit - * \param[in] last : true if last data to be transmitted - * \param[in] txOnly : true no reception is to be performed - * - ****************************************************************************** - */ -static void st25r3916comTx(const uint8_t* txBuf, uint16_t txLen, bool last, bool txOnly); - -/*! - ****************************************************************************** - * \brief ST25R3916 communication Rx - * - * This method performs the required actions to receive from ST25R3916 the given - * amount of bytes, either by SPI or I2C - * - * \param[out] rxBuf : the buffer place the received bytes - * \param[in] rxLen : the length to receive - * - ****************************************************************************** - */ -static void st25r3916comRx(uint8_t* rxBuf, uint16_t rxLen); - -/*! - ****************************************************************************** - * \brief ST25R3916 communication Tx Byte - * - * This helper method transmits a byte passed by value and not by reference - * - * \param[in] txByte : the value of the byte to be transmitted - * \param[in] last : true if last byte to be transmitted - * \param[in] txOnly : true no reception is to be performed - * - ****************************************************************************** - */ -static void st25r3916comTxByte(uint8_t txByte, bool last, bool txOnly); - -/* - ****************************************************************************** - * LOCAL FUNCTION - ****************************************************************************** - */ -static void st25r3916comStart(void) { - /* Make this operation atomic, disabling ST25R3916 interrupt during communications*/ - platformProtectST25RComm(); - -#ifdef RFAL_USE_I2C - /* I2C Start and send Slave Address */ - st25r3916I2CStart(); - st25r3916I2CSlaveAddrWR(ST25R3916_I2C_ADDR); -#else - /* Perform the chip select */ - platformSpiSelect(); - -#if defined(ST25R_COM_SINGLETXRX) - comBufIt = 0; /* reset local buffer position */ -#endif /* ST25R_COM_SINGLETXRX */ - -#endif /* RFAL_USE_I2C */ -} - -/*******************************************************************************/ -static void st25r3916comStop(void) { -#ifdef RFAL_USE_I2C - /* Generate Stop signal */ - st25r3916I2CStop(); -#else - /* Release the chip select */ - platformSpiDeselect(); -#endif /* RFAL_USE_I2C */ - - /* reEnable the ST25R3916 interrupt */ - platformUnprotectST25RComm(); -} - -/*******************************************************************************/ -#ifdef RFAL_USE_I2C -static void st25r3916comRepeatStart(void) { - st25r3916I2CRepeatStart(); - st25r3916I2CSlaveAddrRD(ST25R3916_I2C_ADDR); -} -#endif /* RFAL_USE_I2C */ - -/*******************************************************************************/ -static void st25r3916comTx(const uint8_t* txBuf, uint16_t txLen, bool last, bool txOnly) { - NO_WARNING(last); - NO_WARNING(txOnly); - - if(txLen > 0U) { -#ifdef RFAL_USE_I2C - platformI2CTx(txBuf, txLen, last, txOnly); -#else /* RFAL_USE_I2C */ - -#ifdef ST25R_COM_SINGLETXRX - - ST_MEMCPY( - &comBuf[comBufIt], - txBuf, - MIN(txLen, - (ST25R3916_BUF_LEN - - comBufIt))); /* copy tx data to local buffer */ - comBufIt += - MIN(txLen, - (ST25R3916_BUF_LEN - - comBufIt)); /* store position on local buffer */ - - if(last && txOnly) /* only perform SPI transaction if no Rx will follow */ - { - platformSpiTxRx(comBuf, NULL, comBufIt); - } - -#else - platformSpiTxRx(txBuf, NULL, txLen); -#endif /* ST25R_COM_SINGLETXRX */ - -#endif /* RFAL_USE_I2C */ - } -} - -/*******************************************************************************/ -static void st25r3916comRx(uint8_t* rxBuf, uint16_t rxLen) { - if(rxLen > 0U) { -#ifdef RFAL_USE_I2C - platformI2CRx(rxBuf, rxLen); -#else /* RFAL_USE_I2C */ - -#ifdef ST25R_COM_SINGLETXRX - ST_MEMSET( - &comBuf[comBufIt], - 0x00, - MIN(rxLen, - (ST25R3916_BUF_LEN - - comBufIt))); /* clear outgoing buffer */ - platformSpiTxRx( - comBuf, - comBuf, - MIN((comBufIt + rxLen), - ST25R3916_BUF_LEN)); /* transceive as a single SPI call */ - ST_MEMCPY( - rxBuf, - &comBuf[comBufIt], - MIN(rxLen, - (ST25R3916_BUF_LEN - - comBufIt))); /* copy from local buf to output buffer and skip cmd byte */ -#else - if(rxBuf != NULL) { - ST_MEMSET( - rxBuf, 0x00, rxLen); /* clear outgoing buffer */ - } - platformSpiTxRx(NULL, rxBuf, rxLen); -#endif /* ST25R_COM_SINGLETXRX */ -#endif /* RFAL_USE_I2C */ - } -} - -/*******************************************************************************/ -static void st25r3916comTxByte(uint8_t txByte, bool last, bool txOnly) { - uint8_t val = txByte; /* MISRA 17.8: use intermediate variable */ - st25r3916comTx(&val, ST25R3916_REG_LEN, last, txOnly); -} - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -ReturnCode st25r3916ReadRegister(uint8_t reg, uint8_t* val) { - return st25r3916ReadMultipleRegisters(reg, val, ST25R3916_REG_LEN); -} - -/*******************************************************************************/ -ReturnCode st25r3916ReadMultipleRegisters(uint8_t reg, uint8_t* values, uint8_t length) { - if(length > 0U) { - st25r3916comStart(); - - /* If is a space-B register send a direct command first */ - if((reg & ST25R3916_SPACE_B) != 0U) { - st25r3916comTxByte(ST25R3916_CMD_SPACE_B_ACCESS, false, false); - } - - st25r3916comTxByte(((reg & ~ST25R3916_SPACE_B) | ST25R3916_READ_MODE), true, false); - st25r3916comRepeatStart(); - st25r3916comRx(values, length); - st25r3916comStop(); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916WriteRegister(uint8_t reg, uint8_t val) { - uint8_t value = val; /* MISRA 17.8: use intermediate variable */ - return st25r3916WriteMultipleRegisters(reg, &value, ST25R3916_REG_LEN); -} - -/*******************************************************************************/ -ReturnCode st25r3916WriteMultipleRegisters(uint8_t reg, const uint8_t* values, uint8_t length) { - if(length > 0U) { - st25r3916comStart(); - - if((reg & ST25R3916_SPACE_B) != 0U) { - st25r3916comTxByte(ST25R3916_CMD_SPACE_B_ACCESS, false, true); - } - - st25r3916comTxByte(((reg & ~ST25R3916_SPACE_B) | ST25R3916_WRITE_MODE), false, true); - st25r3916comTx(values, length, true, true); - st25r3916comStop(); - - /* Send a WriteMultiReg event to LED handling */ - st25r3916ledEvtWrMultiReg(reg, values, length); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916WriteFifo(const uint8_t* values, uint16_t length) { - if(length > ST25R3916_FIFO_DEPTH) { - return ERR_PARAM; - } - - if(length > 0U) { - st25r3916comStart(); - st25r3916comTxByte(ST25R3916_FIFO_LOAD, false, true); - st25r3916comTx(values, length, true, true); - st25r3916comStop(); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916ReadFifo(uint8_t* buf, uint16_t length) { - if(length > 0U) { - st25r3916comStart(); - st25r3916comTxByte(ST25R3916_FIFO_READ, true, false); - - st25r3916comRepeatStart(); - st25r3916comRx(buf, length); - st25r3916comStop(); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916WritePTMem(const uint8_t* values, uint16_t length) { - if(length > ST25R3916_PTM_LEN) { - return ERR_PARAM; - } - - if(length > 0U) { - st25r3916comStart(); - st25r3916comTxByte(ST25R3916_PT_A_CONFIG_LOAD, false, true); - st25r3916comTx(values, length, true, true); - st25r3916comStop(); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916ReadPTMem(uint8_t* values, uint16_t length) { - uint8_t - tmp[ST25R3916_REG_LEN + - ST25R3916_PTM_LEN]; /* local buffer to handle prepended byte on I2C and SPI */ - - if(length > 0U) { - if(length > ST25R3916_PTM_LEN) { - return ERR_PARAM; - } - - st25r3916comStart(); - st25r3916comTxByte(ST25R3916_PT_MEM_READ, true, false); - - st25r3916comRepeatStart(); - st25r3916comRx(tmp, (ST25R3916_REG_LEN + length)); /* skip prepended byte */ - st25r3916comStop(); - - /* Copy PTMem content without prepended byte */ - ST_MEMCPY(values, (tmp + ST25R3916_REG_LEN), length); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916WritePTMemF(const uint8_t* values, uint16_t length) { - if(length > (ST25R3916_PTM_F_LEN + ST25R3916_PTM_TSN_LEN)) { - return ERR_PARAM; - } - - if(length > 0U) { - st25r3916comStart(); - st25r3916comTxByte(ST25R3916_PT_F_CONFIG_LOAD, false, true); - st25r3916comTx(values, length, true, true); - st25r3916comStop(); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916WritePTMemTSN(const uint8_t* values, uint16_t length) { - if(length > ST25R3916_PTM_TSN_LEN) { - return ERR_PARAM; - } - - if(length > 0U) { - st25r3916comStart(); - st25r3916comTxByte(ST25R3916_PT_TSN_DATA_LOAD, false, true); - st25r3916comTx(values, length, true, true); - st25r3916comStop(); - } - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916ExecuteCommand(uint8_t cmd) { - st25r3916comStart(); - st25r3916comTxByte((cmd | ST25R3916_CMD_MODE), true, true); - st25r3916comStop(); - - /* Send a cmd event to LED handling */ - st25r3916ledEvtCmd(cmd); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916ReadTestRegister(uint8_t reg, uint8_t* val) { - st25r3916comStart(); - st25r3916comTxByte(ST25R3916_CMD_TEST_ACCESS, false, false); - st25r3916comTxByte((reg | ST25R3916_READ_MODE), true, false); - st25r3916comRepeatStart(); - st25r3916comRx(val, ST25R3916_REG_LEN); - st25r3916comStop(); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916WriteTestRegister(uint8_t reg, uint8_t val) { - uint8_t value = val; /* MISRA 17.8: use intermediate variable */ - - st25r3916comStart(); - st25r3916comTxByte(ST25R3916_CMD_TEST_ACCESS, false, true); - st25r3916comTxByte((reg | ST25R3916_WRITE_MODE), false, true); - st25r3916comTx(&value, ST25R3916_REG_LEN, true, true); - st25r3916comStop(); - - return ERR_NONE; -} - -/*******************************************************************************/ -ReturnCode st25r3916ClrRegisterBits(uint8_t reg, uint8_t clr_mask) { - ReturnCode ret; - uint8_t rdVal; - - /* Read current reg value */ - EXIT_ON_ERR(ret, st25r3916ReadRegister(reg, &rdVal)); - - /* Only perform a Write if value to be written is different */ - if(ST25R3916_OPTIMIZE && (rdVal == (uint8_t)(rdVal & ~clr_mask))) { - return ERR_NONE; - } - - /* Write new reg value */ - return st25r3916WriteRegister(reg, (uint8_t)(rdVal & ~clr_mask)); -} - -/*******************************************************************************/ -ReturnCode st25r3916SetRegisterBits(uint8_t reg, uint8_t set_mask) { - ReturnCode ret; - uint8_t rdVal; - - /* Read current reg value */ - EXIT_ON_ERR(ret, st25r3916ReadRegister(reg, &rdVal)); - - /* Only perform a Write if the value to be written is different */ - if(ST25R3916_OPTIMIZE && (rdVal == (rdVal | set_mask))) { - return ERR_NONE; - } - - /* Write new reg value */ - return st25r3916WriteRegister(reg, (rdVal | set_mask)); -} - -/*******************************************************************************/ -ReturnCode st25r3916ChangeRegisterBits(uint8_t reg, uint8_t valueMask, uint8_t value) { - return st25r3916ModifyRegister(reg, valueMask, (valueMask & value)); -} - -/*******************************************************************************/ -ReturnCode st25r3916ModifyRegister(uint8_t reg, uint8_t clr_mask, uint8_t set_mask) { - ReturnCode ret; - uint8_t rdVal; - uint8_t wrVal; - - /* Read current reg value */ - EXIT_ON_ERR(ret, st25r3916ReadRegister(reg, &rdVal)); - - /* Compute new value */ - wrVal = (uint8_t)(rdVal & ~clr_mask); - wrVal |= set_mask; - - /* Only perform a Write if the value to be written is different */ - if(ST25R3916_OPTIMIZE && (rdVal == wrVal)) { - return ERR_NONE; - } - - /* Write new reg value */ - return st25r3916WriteRegister(reg, wrVal); -} - -/*******************************************************************************/ -ReturnCode st25r3916ChangeTestRegisterBits(uint8_t reg, uint8_t valueMask, uint8_t value) { - ReturnCode ret; - uint8_t rdVal; - uint8_t wrVal; - - /* Read current reg value */ - EXIT_ON_ERR(ret, st25r3916ReadTestRegister(reg, &rdVal)); - - /* Compute new value */ - wrVal = (uint8_t)(rdVal & ~valueMask); - wrVal |= (uint8_t)(value & valueMask); - - /* Only perform a Write if the value to be written is different */ - if(ST25R3916_OPTIMIZE && (rdVal == wrVal)) { - return ERR_NONE; - } - - /* Write new reg value */ - return st25r3916WriteTestRegister(reg, wrVal); -} - -/*******************************************************************************/ -bool st25r3916CheckReg(uint8_t reg, uint8_t mask, uint8_t val) { - uint8_t regVal; - - regVal = 0; - st25r3916ReadRegister(reg, ®Val); - - return ((regVal & mask) == val); -} - -/*******************************************************************************/ -bool st25r3916IsRegValid(uint8_t reg) { -#pragma GCC diagnostic ignored "-Wtype-limits" - if(!(((int16_t)reg >= (int32_t)ST25R3916_REG_IO_CONF1) && - (reg <= (ST25R3916_SPACE_B | ST25R3916_REG_IC_IDENTITY)))) { - return false; - } - return true; -} diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916_irq.c b/lib/ST25RFAL002/source/st25r3916/st25r3916_irq.c deleted file mode 100644 index 74c2797ce..000000000 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916_irq.c +++ /dev/null @@ -1,231 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Gustavo Patricio - * - * \brief ST25R3916 Interrupt handling - * - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ - -#include "st25r3916_irq.h" -#include "st25r3916_com.h" -#include "st25r3916_led.h" -#include "st25r3916.h" -#include "utils.h" - -/* - ****************************************************************************** - * LOCAL DATA TYPES - ****************************************************************************** - */ - -/*! Holds current and previous interrupt callback pointer as well as current Interrupt status and mask */ -typedef struct { - void (*prevCallback)(void); /*!< call back function for ST25R3916 interrupt */ - void (*callback)(void); /*!< call back function for ST25R3916 interrupt */ - uint32_t status; /*!< latest interrupt status */ - uint32_t mask; /*!< Interrupt mask. Negative mask = ST25R3916 mask regs */ -} st25r3916Interrupt; - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ - -/*! Length of the interrupt registers */ -#define ST25R3916_INT_REGS_LEN ((ST25R3916_REG_IRQ_TARGET - ST25R3916_REG_IRQ_MAIN) + 1U) - -/* -****************************************************************************** -* GLOBAL VARIABLES -****************************************************************************** -*/ - -static volatile st25r3916Interrupt st25r3916interrupt; /*!< Instance of ST25R3916 interrupt */ - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ -void st25r3916InitInterrupts(void) { - platformIrqST25RPinInitialize(); - platformIrqST25RSetCallback(st25r3916Isr); - - st25r3916interrupt.callback = NULL; - st25r3916interrupt.prevCallback = NULL; - st25r3916interrupt.status = ST25R3916_IRQ_MASK_NONE; - st25r3916interrupt.mask = ST25R3916_IRQ_MASK_NONE; -} - -/*******************************************************************************/ -void st25r3916Isr(void) { - st25r3916CheckForReceivedInterrupts(); - - // Check if callback is set and run it - if(NULL != st25r3916interrupt.callback) { - st25r3916interrupt.callback(); - } -} - -/*******************************************************************************/ -void st25r3916CheckForReceivedInterrupts(void) { - uint8_t iregs[ST25R3916_INT_REGS_LEN]; - uint32_t irqStatus; - - /* Initialize iregs */ - irqStatus = ST25R3916_IRQ_MASK_NONE; - ST_MEMSET(iregs, (int32_t)(ST25R3916_IRQ_MASK_ALL & 0xFFU), ST25R3916_INT_REGS_LEN); - - /* In case the IRQ is Edge (not Level) triggered read IRQs until done */ - while(platformGpioIsHigh(ST25R_INT_PORT, ST25R_INT_PIN)) { - st25r3916ReadMultipleRegisters(ST25R3916_REG_IRQ_MAIN, iregs, ST25R3916_INT_REGS_LEN); - - irqStatus |= (uint32_t)iregs[0]; - irqStatus |= (uint32_t)iregs[1] << 8; - irqStatus |= (uint32_t)iregs[2] << 16; - irqStatus |= (uint32_t)iregs[3] << 24; - } - - /* Forward all interrupts, even masked ones to application */ - platformProtectST25RIrqStatus(); - st25r3916interrupt.status |= irqStatus; - platformUnprotectST25RIrqStatus(); - - /* Send an IRQ event to LED handling */ - st25r3916ledEvtIrq(st25r3916interrupt.status); -} - -/*******************************************************************************/ -void st25r3916ModifyInterrupts(uint32_t clr_mask, uint32_t set_mask) { - uint8_t i; - uint32_t old_mask; - uint32_t new_mask; - - old_mask = st25r3916interrupt.mask; - new_mask = ((~old_mask & set_mask) | (old_mask & clr_mask)); - st25r3916interrupt.mask &= ~clr_mask; - st25r3916interrupt.mask |= set_mask; - - for(i = 0; i < ST25R3916_INT_REGS_LEN; i++) { - if(((new_mask >> (8U * i)) & 0xFFU) == 0U) { - continue; - } - - st25r3916WriteRegister( - ST25R3916_REG_IRQ_MASK_MAIN + i, - (uint8_t)((st25r3916interrupt.mask >> (8U * i)) & 0xFFU)); - } - return; -} - -/*******************************************************************************/ -uint32_t st25r3916WaitForInterruptsTimed(uint32_t mask, uint16_t tmo) { - uint32_t tmrDelay; - uint32_t status; - - tmrDelay = platformTimerCreate(tmo); - - /* Run until specific interrupt has happen or the timer has expired */ - do { - status = (st25r3916interrupt.status & mask); - } while((!platformTimerIsExpired(tmrDelay) || (tmo == 0U)) && (status == 0U)); - - platformTimerDestroy(tmrDelay); - - status = st25r3916interrupt.status & mask; - - platformProtectST25RIrqStatus(); - st25r3916interrupt.status &= ~status; - platformUnprotectST25RIrqStatus(); - - return status; -} - -/*******************************************************************************/ -uint32_t st25r3916GetInterrupt(uint32_t mask) { - uint32_t irqs; - - irqs = (st25r3916interrupt.status & mask); - if(irqs != ST25R3916_IRQ_MASK_NONE) { - platformProtectST25RIrqStatus(); - st25r3916interrupt.status &= ~irqs; - platformUnprotectST25RIrqStatus(); - } - - return irqs; -} - -/*******************************************************************************/ -void st25r3916ClearAndEnableInterrupts(uint32_t mask) { - st25r3916GetInterrupt(mask); - st25r3916EnableInterrupts(mask); -} - -/*******************************************************************************/ -void st25r3916EnableInterrupts(uint32_t mask) { - st25r3916ModifyInterrupts(mask, 0); -} - -/*******************************************************************************/ -void st25r3916DisableInterrupts(uint32_t mask) { - st25r3916ModifyInterrupts(0, mask); -} - -/*******************************************************************************/ -void st25r3916ClearInterrupts(void) { - uint8_t iregs[ST25R3916_INT_REGS_LEN]; - - st25r3916ReadMultipleRegisters(ST25R3916_REG_IRQ_MAIN, iregs, ST25R3916_INT_REGS_LEN); - - platformProtectST25RIrqStatus(); - st25r3916interrupt.status = ST25R3916_IRQ_MASK_NONE; - platformUnprotectST25RIrqStatus(); - return; -} - -/*******************************************************************************/ -void st25r3916IRQCallbackSet(void (*cb)(void)) { - st25r3916interrupt.prevCallback = st25r3916interrupt.callback; - st25r3916interrupt.callback = cb; -} - -/*******************************************************************************/ -void st25r3916IRQCallbackRestore(void) { - st25r3916interrupt.callback = st25r3916interrupt.prevCallback; - st25r3916interrupt.prevCallback = NULL; -} diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916_irq.h b/lib/ST25RFAL002/source/st25r3916/st25r3916_irq.h deleted file mode 100644 index e8ce2d07a..000000000 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916_irq.h +++ /dev/null @@ -1,296 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Gustavo Patricio - * - * \brief ST25R3916 Interrupt handling - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-HAL - * \brief RFAL Hardware Abstraction Layer - * @{ - * - * \addtogroup ST25R3916 - * \brief RFAL ST25R3916 Driver - * @{ - * - * \addtogroup ST25R3916_IRQ - * \brief RFAL ST25R3916 IRQ - * @{ - * - */ - -#ifndef ST25R3916_IRQ_H -#define ST25R3916_IRQ_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ - -#include "platform.h" - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ - -#define ST25R3916_IRQ_MASK_ALL \ - (uint32_t)(0xFFFFFFFFUL) /*!< All ST25R3916 interrupt sources */ -#define ST25R3916_IRQ_MASK_NONE \ - (uint32_t)(0x00000000UL) /*!< No ST25R3916 interrupt source */ - -/* Main interrupt register */ -#define ST25R3916_IRQ_MASK_OSC \ - (uint32_t)(0x00000080U) /*!< ST25R3916 oscillator stable interrupt */ -#define ST25R3916_IRQ_MASK_FWL \ - (uint32_t)(0x00000040U) /*!< ST25R3916 FIFO water level interrupt */ -#define ST25R3916_IRQ_MASK_RXS \ - (uint32_t)(0x00000020U) /*!< ST25R3916 start of receive interrupt */ -#define ST25R3916_IRQ_MASK_RXE \ - (uint32_t)(0x00000010U) /*!< ST25R3916 end of receive interrupt */ -#define ST25R3916_IRQ_MASK_TXE \ - (uint32_t)(0x00000008U) /*!< ST25R3916 end of transmission interrupt */ -#define ST25R3916_IRQ_MASK_COL \ - (uint32_t)(0x00000004U) /*!< ST25R3916 bit collision interrupt */ -#define ST25R3916_IRQ_MASK_RX_REST \ - (uint32_t)(0x00000002U) /*!< ST25R3916 automatic reception restart interrupt */ -#define ST25R3916_IRQ_MASK_RFU \ - (uint32_t)(0x00000001U) /*!< ST25R3916 RFU interrupt */ - -/* Timer and NFC interrupt register */ -#define ST25R3916_IRQ_MASK_DCT \ - (uint32_t)(0x00008000U) /*!< ST25R3916 termination of direct command interrupt. */ -#define ST25R3916_IRQ_MASK_NRE \ - (uint32_t)(0x00004000U) /*!< ST25R3916 no-response timer expired interrupt */ -#define ST25R3916_IRQ_MASK_GPE \ - (uint32_t)(0x00002000U) /*!< ST25R3916 general purpose timer expired interrupt */ -#define ST25R3916_IRQ_MASK_EON \ - (uint32_t)(0x00001000U) /*!< ST25R3916 external field on interrupt */ -#define ST25R3916_IRQ_MASK_EOF \ - (uint32_t)(0x00000800U) /*!< ST25R3916 external field off interrupt */ -#define ST25R3916_IRQ_MASK_CAC \ - (uint32_t)(0x00000400U) /*!< ST25R3916 collision during RF collision avoidance interrupt */ -#define ST25R3916_IRQ_MASK_CAT \ - (uint32_t)(0x00000200U) /*!< ST25R3916 minimum guard time expired interrupt */ -#define ST25R3916_IRQ_MASK_NFCT \ - (uint32_t)(0x00000100U) /*!< ST25R3916 initiator bit rate recognised interrupt */ - -/* Error and wake-up interrupt register */ -#define ST25R3916_IRQ_MASK_CRC \ - (uint32_t)(0x00800000U) /*!< ST25R3916 CRC error interrupt */ -#define ST25R3916_IRQ_MASK_PAR \ - (uint32_t)(0x00400000U) /*!< ST25R3916 parity error interrupt */ -#define ST25R3916_IRQ_MASK_ERR2 \ - (uint32_t)(0x00200000U) /*!< ST25R3916 soft framing error interrupt */ -#define ST25R3916_IRQ_MASK_ERR1 \ - (uint32_t)(0x00100000U) /*!< ST25R3916 hard framing error interrupt */ -#define ST25R3916_IRQ_MASK_WT \ - (uint32_t)(0x00080000U) /*!< ST25R3916 wake-up interrupt */ -#define ST25R3916_IRQ_MASK_WAM \ - (uint32_t)(0x00040000U) /*!< ST25R3916 wake-up due to amplitude interrupt */ -#define ST25R3916_IRQ_MASK_WPH \ - (uint32_t)(0x00020000U) /*!< ST25R3916 wake-up due to phase interrupt */ -#define ST25R3916_IRQ_MASK_WCAP \ - (uint32_t)(0x00010000U) /*!< ST25R3916 wake-up due to capacitance measurement */ - -/* Passive Target Interrupt Register */ -#define ST25R3916_IRQ_MASK_PPON2 \ - (uint32_t)(0x80000000U) /*!< ST25R3916 PPON2 Field on waiting Timer interrupt */ -#define ST25R3916_IRQ_MASK_SL_WL \ - (uint32_t)(0x40000000U) /*!< ST25R3916 Passive target slot number water level interrupt */ -#define ST25R3916_IRQ_MASK_APON \ - (uint32_t)(0x20000000U) /*!< ST25R3916 Anticollision done and Field On interrupt */ -#define ST25R3916_IRQ_MASK_RXE_PTA \ - (uint32_t)(0x10000000U) /*!< ST25R3916 RXE with an automatic response interrupt */ -#define ST25R3916_IRQ_MASK_WU_F \ - (uint32_t)(0x08000000U) /*!< ST25R3916 212/424b/s Passive target interrupt: Active */ -#define ST25R3916_IRQ_MASK_RFU2 \ - (uint32_t)(0x04000000U) /*!< ST25R3916 RFU2 interrupt */ -#define ST25R3916_IRQ_MASK_WU_A_X \ - (uint32_t)(0x02000000U) /*!< ST25R3916 106kb/s Passive target state interrupt: Active* */ -#define ST25R3916_IRQ_MASK_WU_A \ - (uint32_t)(0x01000000U) /*!< ST25R3916 106kb/s Passive target state interrupt: Active */ - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Wait until an ST25R3916 interrupt occurs - * - * This function is used to access the ST25R3916 interrupt flags. Use this - * to wait for max. \a tmo milliseconds for the \b first interrupt indicated - * with mask \a mask to occur. - * - * \param[in] mask : mask indicating the interrupts to wait for. - * \param[in] tmo : time in milliseconds until timeout occurs. If set to 0 - * the functions waits forever. - * - * \return : 0 if timeout occurred otherwise a mask indicating the cleared - * interrupts. - * - ***************************************************************************** - */ -uint32_t st25r3916WaitForInterruptsTimed(uint32_t mask, uint16_t tmo); - -/*! - ***************************************************************************** - * \brief Get status for the given interrupt - * - * This function is used to check whether the interrupt given by \a mask - * has occurred. If yes the interrupt gets cleared. This function returns - * only status bits which are inside \a mask. - * - * \param[in] mask : mask indicating the interrupt to check for. - * - * \return the mask of the interrupts occurred - * - ***************************************************************************** - */ -uint32_t st25r3916GetInterrupt(uint32_t mask); - -/*! - ***************************************************************************** - * \brief Init the 3916 interrupt - * - * This function is used to check whether the interrupt given by \a mask - * has occurred. - * - ***************************************************************************** - */ -void st25r3916InitInterrupts(void); - -/*! - ***************************************************************************** - * \brief Modifies the Interrupt - * - * This function modifies the interrupt - * - * \param[in] clr_mask : bit mask to be cleared on the interrupt mask - * \param[in] set_mask : bit mask to be set on the interrupt mask - ***************************************************************************** - */ -void st25r3916ModifyInterrupts(uint32_t clr_mask, uint32_t set_mask); - -/*! - ***************************************************************************** - * \brief Checks received interrupts - * - * Checks received interrupts and saves the result into global params - ***************************************************************************** - */ -void st25r3916CheckForReceivedInterrupts(void); - -/*! - ***************************************************************************** - * \brief ISR Service routine - * - * This function modiefies the interrupt - ***************************************************************************** - */ -void st25r3916Isr(void); - -/*! - ***************************************************************************** - * \brief Enable a given ST25R3916 Interrupt source - * - * This function enables all interrupts given by \a mask, - * ST25R3916_IRQ_MASK_ALL enables all interrupts. - * - * \param[in] mask: mask indicating the interrupts to be enabled - * - ***************************************************************************** - */ -void st25r3916EnableInterrupts(uint32_t mask); - -/*! - ***************************************************************************** - * \brief Disable one or more a given ST25R3916 Interrupt sources - * - * This function disables all interrupts given by \a mask. 0xff disables all. - * - * \param[in] mask: mask indicating the interrupts to be disabled. - * - ***************************************************************************** - */ -void st25r3916DisableInterrupts(uint32_t mask); - -/*! - ***************************************************************************** - * \brief Clear all ST25R3916 irq flags - * - ***************************************************************************** - */ -void st25r3916ClearInterrupts(void); - -/*! - ***************************************************************************** - * \brief Clears and then enables the given ST25R3916 Interrupt sources - * - * \param[in] mask: mask indicating the interrupts to be cleared and enabled - ***************************************************************************** - */ -void st25r3916ClearAndEnableInterrupts(uint32_t mask); - -/*! - ***************************************************************************** - * \brief Sets IRQ callback for the ST25R3916 interrupt - * - ***************************************************************************** - */ -void st25r3916IRQCallbackSet(void (*cb)(void)); - -/*! - ***************************************************************************** - * \brief Sets IRQ callback for the ST25R3916 interrupt - * - ***************************************************************************** - */ -void st25r3916IRQCallbackRestore(void); - -#endif /* ST25R3916_IRQ_H */ - -/** - * @} - * - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916_led.c b/lib/ST25RFAL002/source/st25r3916/st25r3916_led.c deleted file mode 100644 index 9737337ca..000000000 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916_led.c +++ /dev/null @@ -1,148 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Gustavo Patricio - * - * \brief ST25R3916 LEDs handling - * - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ - -#include "st25r3916_led.h" -#include "st25r3916_irq.h" -#include "st25r3916_com.h" -#include "st25r3916.h" - -/* -****************************************************************************** -* MACROS -****************************************************************************** -*/ - -#ifdef PLATFORM_LED_RX_PIN -#define st25r3916ledRxOn() \ - platformLedOn( \ - PLATFORM_LED_RX_PORT, \ - PLATFORM_LED_RX_PIN); /*!< LED Rx Pin On from system HAL */ -#define st25r3916ledRxOff() \ - platformLedOff( \ - PLATFORM_LED_RX_PORT, \ - PLATFORM_LED_RX_PIN); /*!< LED Rx Pin Off from system HAL */ -#else /* PLATFORM_LED_RX_PIN */ -#define st25r3916ledRxOn() -#define st25r3916ledRxOff() -#endif /* PLATFORM_LED_RX_PIN */ - -#ifdef PLATFORM_LED_FIELD_PIN -#define st25r3916ledFieldOn() \ - platformLedOn( \ - PLATFORM_LED_FIELD_PORT, \ - PLATFORM_LED_FIELD_PIN); /*!< LED Field Pin On from system HAL */ -#define st25r3916ledFieldOff() \ - platformLedOff( \ - PLATFORM_LED_FIELD_PORT, \ - PLATFORM_LED_FIELD_PIN); /*!< LED Field Pin Off from system HAL */ -#else /* PLATFORM_LED_FIELD_PIN */ -#define st25r3916ledFieldOn() -#define st25r3916ledFieldOff() -#endif /* PLATFORM_LED_FIELD_PIN */ - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -void st25r3916ledInit(void) { - /* Initialize LEDs if existing and defined */ - platformLedsInitialize(); - - st25r3916ledRxOff(); - st25r3916ledFieldOff(); -} - -/*******************************************************************************/ -void st25r3916ledEvtIrq(uint32_t irqs) { - if((irqs & (ST25R3916_IRQ_MASK_TXE | ST25R3916_IRQ_MASK_CAT)) != 0U) { - st25r3916ledFieldOn(); - } - - if((irqs & (ST25R3916_IRQ_MASK_RXS | ST25R3916_IRQ_MASK_NFCT)) != 0U) { - st25r3916ledRxOn(); - } - - if((irqs & (ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_NRE | ST25R3916_IRQ_MASK_RX_REST | - ST25R3916_IRQ_MASK_RXE_PTA | ST25R3916_IRQ_MASK_WU_A | ST25R3916_IRQ_MASK_WU_A_X | - ST25R3916_IRQ_MASK_WU_F | ST25R3916_IRQ_MASK_RFU2)) != 0U) { - st25r3916ledRxOff(); - } -} - -/*******************************************************************************/ -void st25r3916ledEvtWrReg(uint8_t reg, uint8_t val) { - if(reg == ST25R3916_REG_OP_CONTROL) { - if((ST25R3916_REG_OP_CONTROL_tx_en & val) != 0U) { - st25r3916ledFieldOn(); - } else { - st25r3916ledFieldOff(); - } - } -} - -/*******************************************************************************/ -void st25r3916ledEvtWrMultiReg(uint8_t reg, const uint8_t* vals, uint8_t len) { - uint8_t i; - - for(i = 0; i < (len); i++) { - st25r3916ledEvtWrReg((reg + i), vals[i]); - } -} - -/*******************************************************************************/ -void st25r3916ledEvtCmd(uint8_t cmd) { - if((cmd >= ST25R3916_CMD_TRANSMIT_WITH_CRC) && - (cmd <= ST25R3916_CMD_RESPONSE_RF_COLLISION_N)) { - st25r3916ledFieldOff(); - } - - if(cmd == ST25R3916_CMD_UNMASK_RECEIVE_DATA) { - st25r3916ledRxOff(); - } - - if(cmd == ST25R3916_CMD_SET_DEFAULT) { - st25r3916ledFieldOff(); - st25r3916ledRxOff(); - } -} diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916_led.h b/lib/ST25RFAL002/source/st25r3916/st25r3916_led.h deleted file mode 100644 index 376a8d7df..000000000 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916_led.h +++ /dev/null @@ -1,151 +0,0 @@ - -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Gustavo Patricio - * - * \brief ST25R3916 LEDs handling - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-HAL - * \brief RFAL Hardware Abstraction Layer - * @{ - * - * \addtogroup ST25R3916 - * \brief RFAL ST25R3916 Driver - * @{ - * - * \addtogroup ST25R3916_LED - * \brief RFAL ST25R3916 LED - * @{ - * - */ - -#ifndef ST25R3916_LED_H -#define ST25R3916_LED_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ - -#include "platform.h" - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief ST25R3916 LED Initialize - * - * This function initializes the LEDs that represent ST25R3916 activity - * - ***************************************************************************** - */ -void st25r3916ledInit(void); - -/*! - ***************************************************************************** - * \brief ST25R3916 LED Event Interrupt - * - * This function should be called upon a ST25R3916 Interrupt, providing - * the interrupt event with ST25R3916 irq flags to update LEDs - * - * \param[in] irqs: ST25R3916 irqs mask - * - ***************************************************************************** - */ -void st25r3916ledEvtIrq(uint32_t irqs); - -/*! - ***************************************************************************** - * \brief ST25R3916 LED Event Write Register - * - * This function should be called on a ST25R3916 Write Register operation - * providing the event with the register and value to update LEDs - * - * \param[in] reg: ST25R3916 register to be written - * \param[in] val: value to be written on the register - * - ***************************************************************************** - */ -void st25r3916ledEvtWrReg(uint8_t reg, uint8_t val); - -/*! - ***************************************************************************** - * \brief ST25R3916 LED Event Write Multiple Register - * - * This function should be called upon a ST25R3916 Write Multiple Registers, - * providing the event with the registers and values to update LEDs - * - * \param[in] reg : ST25R3916 first register written - * \param[in] vals: pointer to the values written - * \param[in] len : number of registers written - * - ***************************************************************************** - */ -void st25r3916ledEvtWrMultiReg(uint8_t reg, const uint8_t* vals, uint8_t len); - -/*! - ***************************************************************************** - * \brief ST25R3916 LED Event Direct Command - * - * This function should be called upon a ST25R3916 direct command, providing - * the event with the command executed - * - * \param[in] cmd: ST25R3916 cmd executed - * - ***************************************************************************** - */ -void st25r3916ledEvtCmd(uint8_t cmd); - -#endif /* ST25R3916_LED_H */ - -/** - * @} - * - * @} - * - * @} - * - * @} - */ diff --git a/lib/ST25RFAL002/st_errno.h b/lib/ST25RFAL002/st_errno.h deleted file mode 100644 index cd706b3d4..000000000 --- a/lib/ST25RFAL002/st_errno.h +++ /dev/null @@ -1,158 +0,0 @@ - -/****************************************************************************** - * @attention - * - *

© COPYRIGHT 2018 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: STxxxx firmware - * LANGUAGE: ISO C99 - */ - -/*! \file st_errno.h - * - * \author - * - * \brief Main error codes - * - */ - -#ifndef ST_ERRNO_H -#define ST_ERRNO_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ - -#include - -/* -****************************************************************************** -* GLOBAL DATA TYPES -****************************************************************************** -*/ - -typedef uint16_t ReturnCode; /*!< Standard Return Code type from function. */ - -/* -****************************************************************************** -* DEFINES -****************************************************************************** -*/ - -/* - * Error codes to be used within the application. - * They are represented by an uint8_t - */ -enum { - ERR_NONE = 0, /*!< no error occurred */ - ERR_NOMEM = 1, /*!< not enough memory to perform the requested operation */ - ERR_BUSY = 2, /*!< device or resource busy */ - ERR_IO = 3, /*!< generic IO error */ - ERR_TIMEOUT = 4, /*!< error due to timeout */ - ERR_REQUEST = 5, /*!< invalid request or requested function can't be executed at the moment */ - ERR_NOMSG = 6, /*!< No message of desired type */ - ERR_PARAM = 7, /*!< Parameter error */ - ERR_SYSTEM = 8, /*!< System error */ - ERR_FRAMING = 9, /*!< Framing error */ - ERR_OVERRUN = 10, /*!< lost one or more received bytes */ - ERR_PROTO = 11, /*!< protocol error */ - ERR_INTERNAL = 12, /*!< Internal Error */ - ERR_AGAIN = 13, /*!< Call again */ - ERR_MEM_CORRUPT = 14, /*!< memory corruption */ - ERR_NOT_IMPLEMENTED = 15, /*!< not implemented */ - ERR_PC_CORRUPT = - 16, /*!< Program Counter has been manipulated or spike/noise trigger illegal operation */ - ERR_SEND = 17, /*!< error sending*/ - ERR_IGNORE = 18, /*!< indicates error detected but to be ignored */ - ERR_SEMANTIC = 19, /*!< indicates error in state machine (unexpected cmd) */ - ERR_SYNTAX = 20, /*!< indicates error in state machine (unknown cmd) */ - ERR_CRC = 21, /*!< crc error */ - ERR_NOTFOUND = 22, /*!< transponder not found */ - ERR_NOTUNIQUE = 23, /*!< transponder not unique - more than one transponder in field */ - ERR_NOTSUPP = 24, /*!< requested operation not supported */ - ERR_WRITE = 25, /*!< write error */ - ERR_FIFO = 26, /*!< fifo over or underflow error */ - ERR_PAR = 27, /*!< parity error */ - ERR_DONE = 28, /*!< transfer has already finished */ - ERR_RF_COLLISION = - 29, /*!< collision error (Bit Collision or during RF Collision avoidance ) */ - ERR_HW_OVERRUN = 30, /*!< lost one or more received bytes */ - ERR_RELEASE_REQ = 31, /*!< device requested release */ - ERR_SLEEP_REQ = 32, /*!< device requested sleep */ - ERR_WRONG_STATE = 33, /*!< incorrent state for requested operation */ - ERR_MAX_RERUNS = 34, /*!< blocking procedure reached maximum runs */ - ERR_DISABLED = 35, /*!< operation aborted due to disabled configuration */ - ERR_HW_MISMATCH = 36, /*!< expected hw do not match */ - ERR_LINK_LOSS = - 37, /*!< Other device's field didn't behave as expected: turned off by Initiator in Passive mode, or AP2P did not turn on field */ - ERR_INVALID_HANDLE = 38, /*!< invalid or not initalized device handle */ - - ERR_INCOMPLETE_BYTE = 40, /*!< Incomplete byte rcvd */ - ERR_INCOMPLETE_BYTE_01 = 41, /*!< Incomplete byte rcvd - 1 bit */ - ERR_INCOMPLETE_BYTE_02 = 42, /*!< Incomplete byte rcvd - 2 bit */ - ERR_INCOMPLETE_BYTE_03 = 43, /*!< Incomplete byte rcvd - 3 bit */ - ERR_INCOMPLETE_BYTE_04 = 44, /*!< Incomplete byte rcvd - 4 bit */ - ERR_INCOMPLETE_BYTE_05 = 45, /*!< Incomplete byte rcvd - 5 bit */ - ERR_INCOMPLETE_BYTE_06 = 46, /*!< Incomplete byte rcvd - 6 bit */ - ERR_INCOMPLETE_BYTE_07 = 47, /*!< Incomplete byte rcvd - 7 bit */ -}; - -/* General Sub-category number */ -#define ERR_GENERIC_GRP (0x0000) /*!< Reserved value for generic error no */ -#define ERR_WARN_GRP (0x0100) /*!< Errors which are not expected in normal operation */ -#define ERR_PROCESS_GRP (0x0200) /*!< Processes management errors */ -#define ERR_SIO_GRP (0x0800) /*!< SIO errors due to logging */ -#define ERR_RINGBUF_GRP (0x0900) /*!< Ring Buffer errors */ -#define ERR_MQ_GRP (0x0A00) /*!< MQ errors */ -#define ERR_TIMER_GRP (0x0B00) /*!< Timer errors */ -#define ERR_RFAL_GRP (0x0C00) /*!< RFAL errors */ -#define ERR_UART_GRP (0x0D00) /*!< UART errors */ -#define ERR_SPI_GRP (0x0E00) /*!< SPI errors */ -#define ERR_I2C_GRP (0x0F00) /*!< I2c errors */ - -#define ERR_INSERT_SIO_GRP(x) (ERR_SIO_GRP | x) /*!< Insert the SIO grp */ -#define ERR_INSERT_RINGBUF_GRP(x) (ERR_RINGBUF_GRP | x) /*!< Insert the Ring Buffer grp */ -#define ERR_INSERT_RFAL_GRP(x) (ERR_RFAL_GRP | x) /*!< Insert the RFAL grp */ -#define ERR_INSERT_SPI_GRP(x) (ERR_SPI_GRP | x) /*!< Insert the spi grp */ -#define ERR_INSERT_I2C_GRP(x) (ERR_I2C_GRP | x) /*!< Insert the i2c grp */ -#define ERR_INSERT_UART_GRP(x) (ERR_UART_GRP | x) /*!< Insert the uart grp */ -#define ERR_INSERT_TIMER_GRP(x) (ERR_TIMER_GRP | x) /*!< Insert the timer grp */ -#define ERR_INSERT_MQ_GRP(x) (ERR_MQ_GRP | x) /*!< Insert the mq grp */ -#define ERR_INSERT_PROCESS_GRP(x) (ERR_PROCESS_GRP | x) /*!< Insert the process grp */ -#define ERR_INSERT_WARN_GRP(x) (ERR_WARN_GRP | x) /*!< Insert the i2c grp */ -#define ERR_INSERT_GENERIC_GRP(x) (ERR_GENERIC_GRP | x) /*!< Insert the generic grp */ - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ - -#define ERR_NO_MASK(x) (x & 0x00FF) /*!< Mask the error number */ - -/*! Common code to exit a function with the error if function f return error */ -#define EXIT_ON_ERR(r, f) \ - if(ERR_NONE != (r = f)) { \ - return r; \ - } - -#endif /* ST_ERRNO_H */ diff --git a/lib/ST25RFAL002/timer.c b/lib/ST25RFAL002/timer.c deleted file mode 100644 index ea0678a60..000000000 --- a/lib/ST25RFAL002/timer.c +++ /dev/null @@ -1,105 +0,0 @@ -/****************************************************************************** - * @attention - * - *

© COPYRIGHT 2016 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ -/* - * PROJECT: ST25R391x firmware - * $Revision: $ - * LANGUAGE: ANSI C - */ - -/*! \file timer.c - * - * \brief SW Timer implementation - * - * \author Gustavo Patricio - * - * This module makes use of a System Tick in millisconds and provides - * an abstraction for SW timers - * - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "timer.h" -#include - -/* -****************************************************************************** -* LOCAL DEFINES -****************************************************************************** -*/ - -/* -****************************************************************************** -* LOCAL VARIABLES -****************************************************************************** -*/ - -static uint32_t timerStopwatchTick; - -/* -****************************************************************************** -* GLOBAL FUNCTIONS -****************************************************************************** -*/ - -/*******************************************************************************/ -uint32_t timerCalculateTimer(uint16_t time) { - return (furi_get_tick() + time); -} - -/*******************************************************************************/ -bool timerIsExpired(uint32_t timer) { - uint32_t uDiff; - int32_t sDiff; - - uDiff = (timer - furi_get_tick()); /* Calculate the diff between the timers */ - sDiff = uDiff; /* Convert the diff to a signed var */ - - /* Check if the given timer has expired already */ - if(sDiff < 0) { - return true; - } - - return false; -} - -/*******************************************************************************/ -void timerDelay(uint16_t tOut) { - uint32_t t; - - /* Calculate the timer and wait blocking until is running */ - t = timerCalculateTimer(tOut); - while(timerIsRunning(t)) - ; -} - -/*******************************************************************************/ -void timerStopwatchStart(void) { - timerStopwatchTick = furi_get_tick(); -} - -/*******************************************************************************/ -uint32_t timerStopwatchMeasure(void) { - return (uint32_t)(furi_get_tick() - timerStopwatchTick); -} diff --git a/lib/ST25RFAL002/timer.h b/lib/ST25RFAL002/timer.h deleted file mode 100644 index b5f5eb329..000000000 --- a/lib/ST25RFAL002/timer.h +++ /dev/null @@ -1,125 +0,0 @@ -#pragma once -/****************************************************************************** - * @attention - * - *

© COPYRIGHT 2016 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ -/* - * PROJECT: ST25R391x firmware - * $Revision: $ - * LANGUAGE: ANSI C - */ - -/*! \file timer.h - * - * \brief SW Timer implementation header file - * - * This module makes use of a System Tick in millisconds and provides - * an abstraction for SW timers - * - */ - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include -#include - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ -#define timerIsRunning(t) (!timerIsExpired(t)) - -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Calculate Timer - * - * This method calculates when the timer will be expired given the amount - * time in milliseconds /a tOut. - * Once the timer has been calculated it will then be used to check when - * it expires. - * - * \see timersIsExpired - * - * \param[in] time : time/duration in Milliseconds for the timer - * - * \return u32 : The new timer calculated based on the given time - ***************************************************************************** - */ -uint32_t timerCalculateTimer(uint16_t time); - -/*! - ***************************************************************************** - * \brief Checks if a Timer is Expired - * - * This method checks if a timer has already expired. - * Based on the given timer previously calculated it checks if this timer - * has already elapsed - * - * \see timersCalculateTimer - * - * \param[in] timer : the timer to check - * - * \return true : timer has already expired - * \return false : timer is still running - ***************************************************************************** - */ -bool timerIsExpired(uint32_t timer); - -/*! - ***************************************************************************** - * \brief Performs a Delay - * - * This method performs a delay for the given amount of time in Milliseconds - * - * \param[in] time : time/duration in Milliseconds of the delay - * - ***************************************************************************** - */ -void timerDelay(uint16_t time); - -/*! - ***************************************************************************** - * \brief Stopwatch start - * - * This method initiates the stopwatch to later measure the time in ms - * - ***************************************************************************** - */ -void timerStopwatchStart(void); - -/*! - ***************************************************************************** - * \brief Stopwatch Measure - * - * This method returns the elapsed time in ms since the stopwatch was initiated - * - * \return The time in ms since the stopwatch was started - ***************************************************************************** - */ -uint32_t timerStopwatchMeasure(void); diff --git a/lib/ST25RFAL002/utils.h b/lib/ST25RFAL002/utils.h deleted file mode 100644 index 44a141986..000000000 --- a/lib/ST25RFAL002/utils.h +++ /dev/null @@ -1,100 +0,0 @@ - -/****************************************************************************** - * @attention - * - *

© COPYRIGHT 2018 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ - -/* - * PROJECT: NFCC firmware - * $Revision: $ - * LANGUAGE: ISO C99 - */ - -/*! \file - * - * \author Ulrich Herrmann - * - * \brief Common and helpful macros - * - */ - -#ifndef UTILS_H -#define UTILS_H - -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include -#include - -/* -****************************************************************************** -* GLOBAL MACROS -****************************************************************************** -*/ -/*! - * this macro evaluates an error variable \a ERR against an error code \a EC. - * in case it is not equal it jumps to the given label \a LABEL. - */ -#define EVAL_ERR_NE_GOTO(EC, ERR, LABEL) \ - if(EC != ERR) goto LABEL; - -/*! - * this macro evaluates an error variable \a ERR against an error code \a EC. - * in case it is equal it jumps to the given label \a LABEL. - */ -#define EVAL_ERR_EQ_GOTO(EC, ERR, LABEL) \ - if(EC == ERR) goto LABEL; -#define BITMASK_1 (0x01) /*!< Bit mask for lsb bit */ -#define BITMASK_2 (0x03) /*!< Bit mask for two lsb bits */ -#define BITMASK_3 (0x07) /*!< Bit mask for three lsb bits */ -#define BITMASK_4 (0x0F) /*!< Bit mask for four lsb bits */ -#define U16TOU8(a) ((a)&0x00FF) /*!< Cast 16-bit unsigned to 8-bit unsigned */ -#define GETU16(a) \ - (uint16_t)( \ - (a[0] << 8) | a[1]) /*!< Cast two Big Endian 8-bits byte array to 16-bits unsigned */ - -#define REVERSE_BYTES(pData, nDataSize) \ - unsigned char swap, *lo = pData, *hi = pData + nDataSize - 1; \ - while(lo < hi) { \ - swap = *lo; \ - *lo++ = *hi; \ - *hi-- = swap; \ - } - -#define ST_MEMMOVE memmove /*!< map memmove to string library code */ -#define ST_MEMCPY memcpy /*!< map memcpy to string library code */ -#define ST_MEMSET memset /*!< map memset to string library code */ -#define ST_BYTECMP memcmp /*!< map bytecmp to string library code */ - -#define NO_WARNING(v) ((void)(v)) /*!< Macro to suppress compiler warning */ - -#ifndef NULL -#define NULL (void*)0 /*!< represents a NULL pointer */ -#endif /* !NULL */ - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -#endif /* UTILS_H */ diff --git a/lib/digital_signal/SConscript b/lib/digital_signal/SConscript index 2ddf7a58b..b94c26f78 100644 --- a/lib/digital_signal/SConscript +++ b/lib/digital_signal/SConscript @@ -6,6 +6,7 @@ env.Append( ], SDK_HEADERS=[ File("digital_signal.h"), + File("digital_sequence.h"), ], ) diff --git a/lib/digital_signal/digital_sequence.c b/lib/digital_signal/digital_sequence.c new file mode 100644 index 000000000..c85aae8c0 --- /dev/null +++ b/lib/digital_signal/digital_sequence.c @@ -0,0 +1,381 @@ +#include "digital_sequence.h" +#include "digital_signal_i.h" + +#include +#include + +#include +#include + +/** + * To enable debug output on an additional pin, set DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN to the required + * GpioPin variable. It can be passed at compile time via the --extra-define fbt switch. + * NOTE: This pin must be on the same GPIO port as the main pin. + * + * Example: + * ./fbt --extra-define=DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN=gpio_ext_pb3 + */ + +#define TAG "DigitalSequence" + +/* Special value used to indicate the end of DMA ring buffer. */ +#define DIGITAL_SEQUENCE_TIMER_MAX 0xFFFFFFFFUL + +/* Time to wait in loops before returning */ +#define DIGITAL_SEQUENCE_LOCK_WAIT_MS 10UL +#define DIGITAL_SEQUENCE_LOCK_WAIT_TICKS (DIGITAL_SEQUENCE_LOCK_WAIT_MS * 1000 * 64) + +#define DIGITAL_SEQUENCE_GPIO_BUFFER_SIZE 2 + +/* Maximum capacity of the DMA ring buffer. */ +#define DIGITAL_SEQUENCE_RING_BUFFER_SIZE 128 + +#define DIGITAL_SEQUENCE_RING_BUFFER_MIN_FREE_SIZE 2 + +/* Maximum amount of registered signals. */ +#define DIGITAL_SEQUENCE_BANK_SIZE 32 + +typedef enum { + DigitalSequenceStateIdle, + DigitalSequenceStateActive, +} DigitalSequenceState; + +typedef struct { + uint32_t data[DIGITAL_SEQUENCE_RING_BUFFER_SIZE]; + uint32_t write_pos; + uint32_t read_pos; +} DigitalSequenceRingBuffer; + +typedef uint32_t DigitalSequenceGpioBuffer[DIGITAL_SEQUENCE_GPIO_BUFFER_SIZE]; + +typedef const DigitalSignal* DigitalSequenceSignalBank[DIGITAL_SEQUENCE_BANK_SIZE]; + +struct DigitalSequence { + const GpioPin* gpio; + + uint32_t size; + uint32_t max_size; + uint8_t* data; + + LL_DMA_InitTypeDef dma_config_gpio; + LL_DMA_InitTypeDef dma_config_timer; + + DigitalSequenceGpioBuffer gpio_buf; + DigitalSequenceRingBuffer timer_buf; + DigitalSequenceSignalBank signals; + DigitalSequenceState state; +}; + +DigitalSequence* digital_sequence_alloc(uint32_t size, const GpioPin* gpio) { + furi_assert(size); + furi_assert(gpio); + + DigitalSequence* sequence = malloc(sizeof(DigitalSequence)); + + sequence->gpio = gpio; + sequence->max_size = size; + + sequence->data = malloc(sequence->max_size); + + sequence->dma_config_gpio.PeriphOrM2MSrcAddress = (uint32_t)&gpio->port->BSRR; + sequence->dma_config_gpio.MemoryOrM2MDstAddress = (uint32_t)sequence->gpio_buf; + sequence->dma_config_gpio.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH; + sequence->dma_config_gpio.Mode = LL_DMA_MODE_CIRCULAR; + sequence->dma_config_gpio.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; + sequence->dma_config_gpio.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; + sequence->dma_config_gpio.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; + sequence->dma_config_gpio.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; + sequence->dma_config_gpio.NbData = DIGITAL_SEQUENCE_GPIO_BUFFER_SIZE; + sequence->dma_config_gpio.PeriphRequest = LL_DMAMUX_REQ_TIM2_UP; + sequence->dma_config_gpio.Priority = LL_DMA_PRIORITY_VERYHIGH; + + sequence->dma_config_timer.PeriphOrM2MSrcAddress = (uint32_t)&TIM2->ARR; + sequence->dma_config_timer.MemoryOrM2MDstAddress = (uint32_t)sequence->timer_buf.data; + sequence->dma_config_timer.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH; + sequence->dma_config_timer.Mode = LL_DMA_MODE_CIRCULAR; + sequence->dma_config_timer.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; + sequence->dma_config_timer.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; + sequence->dma_config_timer.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; + sequence->dma_config_timer.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; + sequence->dma_config_timer.NbData = DIGITAL_SEQUENCE_RING_BUFFER_SIZE; + sequence->dma_config_timer.PeriphRequest = LL_DMAMUX_REQ_TIM2_UP; + sequence->dma_config_timer.Priority = LL_DMA_PRIORITY_HIGH; + + return sequence; +} + +void digital_sequence_free(DigitalSequence* sequence) { + furi_assert(sequence); + + free(sequence->data); + free(sequence); +} + +void digital_sequence_register_signal( + DigitalSequence* sequence, + uint8_t signal_index, + const DigitalSignal* signal) { + furi_assert(sequence); + furi_assert(signal); + furi_assert(signal_index < DIGITAL_SEQUENCE_BANK_SIZE); + + sequence->signals[signal_index] = signal; +} + +void digital_sequence_add_signal(DigitalSequence* sequence, uint8_t signal_index) { + furi_assert(sequence); + furi_assert(signal_index < DIGITAL_SEQUENCE_BANK_SIZE); + furi_assert(sequence->size < sequence->max_size); + + sequence->data[sequence->size++] = signal_index; +} + +static inline void digital_sequence_start_dma(DigitalSequence* sequence) { + furi_assert(sequence); + + LL_DMA_Init(DMA1, LL_DMA_CHANNEL_1, &sequence->dma_config_gpio); + LL_DMA_Init(DMA1, LL_DMA_CHANNEL_2, &sequence->dma_config_timer); + + LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); + LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_2); +} + +static inline void digital_sequence_stop_dma() { + LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1); + LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_2); + LL_DMA_ClearFlag_TC1(DMA1); + LL_DMA_ClearFlag_TC2(DMA1); +} + +static inline void digital_sequence_start_timer() { + furi_hal_bus_enable(FuriHalBusTIM2); + + LL_TIM_SetCounterMode(TIM2, LL_TIM_COUNTERMODE_UP); + LL_TIM_SetClockDivision(TIM2, LL_TIM_CLOCKDIVISION_DIV1); + LL_TIM_SetPrescaler(TIM2, 0); + LL_TIM_SetAutoReload(TIM2, DIGITAL_SEQUENCE_TIMER_MAX); + LL_TIM_SetCounter(TIM2, 0); + + LL_TIM_EnableCounter(TIM2); + LL_TIM_EnableUpdateEvent(TIM2); + LL_TIM_EnableDMAReq_UPDATE(TIM2); + LL_TIM_GenerateEvent_UPDATE(TIM2); +} + +static void digital_sequence_stop_timer() { + LL_TIM_DisableCounter(TIM2); + LL_TIM_DisableUpdateEvent(TIM2); + LL_TIM_DisableDMAReq_UPDATE(TIM2); + + furi_hal_bus_disable(FuriHalBusTIM2); +} + +static inline void digital_sequence_init_gpio_buffer( + DigitalSequence* sequence, + const DigitalSignal* first_signal) { + const uint32_t bit_set = sequence->gpio->pin << GPIO_BSRR_BS0_Pos +#ifdef DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN + | DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN.pin << GPIO_BSRR_BS0_Pos +#endif + ; + + const uint32_t bit_reset = sequence->gpio->pin << GPIO_BSRR_BR0_Pos +#ifdef DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN + | DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN.pin << GPIO_BSRR_BR0_Pos +#endif + ; + + if(first_signal->start_level) { + sequence->gpio_buf[0] = bit_set; + sequence->gpio_buf[1] = bit_reset; + } else { + sequence->gpio_buf[0] = bit_reset; + sequence->gpio_buf[1] = bit_set; + } +} + +static inline void digital_sequence_finish(DigitalSequence* sequence) { + if(sequence->state == DigitalSequenceStateActive) { + const uint32_t prev_timer = DWT->CYCCNT; + + do { + /* Special value has been loaded into the timer, signaling the end of transmission. */ + if(TIM2->ARR == DIGITAL_SEQUENCE_TIMER_MAX) { + break; + } + + if(DWT->CYCCNT - prev_timer > DIGITAL_SEQUENCE_LOCK_WAIT_TICKS) { + DigitalSequenceRingBuffer* dma_buffer = &sequence->timer_buf; + dma_buffer->read_pos = DIGITAL_SEQUENCE_RING_BUFFER_SIZE - + LL_DMA_GetDataLength(DMA1, LL_DMA_CHANNEL_2); + FURI_LOG_D( + TAG, + "[SEQ] hung %lu ms in finish (ARR 0x%08lx, read %lu, write %lu)", + DIGITAL_SEQUENCE_LOCK_WAIT_MS, + TIM2->ARR, + dma_buffer->read_pos, + dma_buffer->write_pos); + break; + } + } while(true); + } + + digital_sequence_stop_timer(); + digital_sequence_stop_dma(); +} + +static inline void digital_sequence_enqueue_period(DigitalSequence* sequence, uint32_t length) { + DigitalSequenceRingBuffer* dma_buffer = &sequence->timer_buf; + + if(sequence->state == DigitalSequenceStateActive) { + const uint32_t prev_timer = DWT->CYCCNT; + + do { + dma_buffer->read_pos = + DIGITAL_SEQUENCE_RING_BUFFER_SIZE - LL_DMA_GetDataLength(DMA1, LL_DMA_CHANNEL_2); + + const uint32_t size_free = (DIGITAL_SEQUENCE_RING_BUFFER_SIZE + dma_buffer->read_pos - + dma_buffer->write_pos) % + DIGITAL_SEQUENCE_RING_BUFFER_SIZE; + + if(size_free > DIGITAL_SEQUENCE_RING_BUFFER_MIN_FREE_SIZE) { + break; + } + + if(DWT->CYCCNT - prev_timer > DIGITAL_SEQUENCE_LOCK_WAIT_TICKS) { + FURI_LOG_D( + TAG, + "[SEQ] hung %lu ms in queue (ARR 0x%08lx, read %lu, write %lu)", + DIGITAL_SEQUENCE_LOCK_WAIT_MS, + TIM2->ARR, + dma_buffer->read_pos, + dma_buffer->write_pos); + break; + } + + if(TIM2->ARR == DIGITAL_SEQUENCE_TIMER_MAX) { + FURI_LOG_D( + TAG, + "[SEQ] buffer underrun in queue (ARR 0x%08lx, read %lu, write %lu)", + TIM2->ARR, + dma_buffer->read_pos, + dma_buffer->write_pos); + break; + } + } while(true); + } + + dma_buffer->data[dma_buffer->write_pos] = length; + + dma_buffer->write_pos += 1; + dma_buffer->write_pos %= DIGITAL_SEQUENCE_RING_BUFFER_SIZE; + + dma_buffer->data[dma_buffer->write_pos] = DIGITAL_SEQUENCE_TIMER_MAX; +} + +static inline void digital_sequence_timer_buffer_reset(DigitalSequence* sequence) { + sequence->timer_buf.data[0] = DIGITAL_SEQUENCE_TIMER_MAX; + sequence->timer_buf.read_pos = 0; + sequence->timer_buf.write_pos = 0; +} + +void digital_sequence_transmit(DigitalSequence* sequence) { + furi_assert(sequence); + furi_assert(sequence->size); + furi_assert(sequence->state == DigitalSequenceStateIdle); + + FURI_CRITICAL_ENTER(); + + furi_hal_gpio_init(sequence->gpio, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); +#ifdef DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN + furi_hal_gpio_init( + &DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); +#endif + + const DigitalSignal* signal_current = sequence->signals[sequence->data[0]]; + + digital_sequence_init_gpio_buffer(sequence, signal_current); + + int32_t remainder_ticks = 0; + uint32_t reload_value_carry = 0; + uint32_t next_signal_index = 1; + + for(;;) { + const DigitalSignal* signal_next = + (next_signal_index < sequence->size) ? + sequence->signals[sequence->data[next_signal_index++]] : + NULL; + + for(uint32_t i = 0; i < signal_current->size; i++) { + const bool is_last_value = (i == signal_current->size - 1); + const uint32_t reload_value = signal_current->data[i] + reload_value_carry; + + reload_value_carry = 0; + + if(is_last_value) { + if(signal_next != NULL) { + /* Special case: signal boundary. Depending on whether the adjacent levels are equal or not, + * they will be combined to a single one or handled separately. */ + const bool end_level = signal_current->start_level ^ + ((signal_current->size % 2) == 0); + + /* If the adjacent levels are equal, carry the current period duration over to the next signal. */ + if(end_level == signal_next->start_level) { + reload_value_carry = reload_value; + } + } else { + /** Special case: during the last period of the last signal, hold the output level indefinitely. + * @see digital_signal.h + * + * Setting reload_value_carry to a non-zero value will prevent the respective period from being + * added to the DMA ring buffer. */ + reload_value_carry = 1; + } + } + + /* A non-zero reload_value_carry means that the level was the same on the both sides of the signal boundary + * and the two respective periods were combined to one. */ + if(reload_value_carry == 0) { + digital_sequence_enqueue_period(sequence, reload_value); + } + + if(sequence->state == DigitalSequenceStateIdle) { + const bool is_buffer_filled = sequence->timer_buf.write_pos >= + (DIGITAL_SEQUENCE_RING_BUFFER_SIZE - + DIGITAL_SEQUENCE_RING_BUFFER_MIN_FREE_SIZE); + const bool is_end_of_data = (signal_next == NULL) && is_last_value; + + if(is_buffer_filled || is_end_of_data) { + digital_sequence_start_dma(sequence); + digital_sequence_start_timer(); + sequence->state = DigitalSequenceStateActive; + } + } + } + + /* Exit the loop here when no further signals are available */ + if(signal_next == NULL) break; + + /* Prevent the rounding error from accumulating by distributing it across multiple periods. */ + remainder_ticks += signal_current->remainder; + if(remainder_ticks >= DIGITAL_SIGNAL_T_TIM_DIV2) { + remainder_ticks -= DIGITAL_SIGNAL_T_TIM; + reload_value_carry += 1; + } + + signal_current = signal_next; + }; + + digital_sequence_finish(sequence); + digital_sequence_timer_buffer_reset(sequence); + + FURI_CRITICAL_EXIT(); + + sequence->state = DigitalSequenceStateIdle; +} + +void digital_sequence_clear(DigitalSequence* sequence) { + furi_assert(sequence); + + sequence->size = 0; +} diff --git a/lib/digital_signal/digital_sequence.h b/lib/digital_signal/digital_sequence.h new file mode 100644 index 000000000..4f04ecc46 --- /dev/null +++ b/lib/digital_signal/digital_sequence.h @@ -0,0 +1,112 @@ +/** + * @file digital_sequence.h + * @brief Fast and precise digital signal generation library. + * + * Each sequence is represented by one or more (up to 32) registered signals, which are addressed + * by their indices, and a list of signal indices to be transmitted. + * + * The registered signals must be set up prior to actually defining the sequence. + * + * Example: A sequence containing 4 registered signals and n indices to transmit. + * + * |Signal | Index | + * |:-----:|:-----:| + * | SOF | 0 | + * | EOF | 1 | + * | Zero | 2 | + * | One | 3 | + * + * ``` + * Signal index | 0 | 3 | 2 | 2 | ... | 3 | 1 | + * 0 1 2 3 ... n - 2 n - 1 + * ``` + * + * The above sequence starts by transmitting the signal with index 0, which is SOF in this case, + * then it proceeds with indices 3, 2, 2, which are One, Zero, Zero and after n - 2 signals, + * it will conclude with indices 3 and 1 which are One and EOF respectively. + * + * This way, only the order in which the signals are sent is stored, while the signals themselves + * are not duplicated. + */ +#pragma once + +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct DigitalSequence DigitalSequence; + +/** + * @brief Allocate a DigitalSequence instance of a given size which will operate on a set GPIO pin. + * + * @param[in] size maximum number of signal indices contained in the instance. + * @param[in] gpio the GPIO pin used to generate the signal. + * @returns pointer to the allocated DigitalSequence instance. + */ +DigitalSequence* digital_sequence_alloc(uint32_t size, const GpioPin* gpio); + +/** + * @brief Delete a previously allocated DigitalSequence instance. + * + * @param[in,out] sequence pointer to the instance to be deleted. + */ +void digital_sequence_free(DigitalSequence* sequence); + +/** + * @brief Register a signal within a DigitalSequence instance by its index. + * + * This function must be called for each signal to be used in the sequence. The DigitalSequence + * instance does not own the signals, therefore, their lifetime must be no less than the instance's. + * + * The user is responsible for creation and deletion of DigitalSignal instances and + * also for keeping track of their respective indices. + * + * @param[in,out] sequence pointer to the instance to be modified. + * @param[in] signal_index index to register the signal under (must be less than 32). + * @param[in] signal pointer to the DigitalSignal instance to be registered. + */ +void digital_sequence_register_signal( + DigitalSequence* sequence, + uint8_t signal_index, + const DigitalSignal* signal); + +/** + * @brief Append a signal index to a DigitalSequence instance. + * + * The signal under the index must be registered beforehand by calling digital_sequence_set_signal(). + * + * @param[in,out] sequence pointer to the instance to be modified. + * @param[in] signal_index signal index to be appended to the sequence (must be less than 32). + */ +void digital_sequence_add_signal(DigitalSequence* sequence, uint8_t signal_index); + +/** + * @brief Transmit the sequence contained in the DigitalSequence instance. + * + * Must contain at least one registered signal and one signal index. + * + * NOTE: The current implementation will properly initialise the GPIO provided during construction, + * but it is the caller's responsibility to reconfigure it back before reusing for other purposes. + * This is due to performance reasons. + * + * @param[in] sequence pointer to the sequence to be transmitted. + */ +void digital_sequence_transmit(DigitalSequence* sequence); + +/** + * @brief Clear the signal sequence in a DigitalSequence instance. + * + * Calling this function does not un-register the registered signals, so it is + * safe to call digital_sequence_add_signal() right afterwards. + * + * @param[in,out] sequence pointer to the instance to be cleared. + */ +void digital_sequence_clear(DigitalSequence* sequence); + +#ifdef __cplusplus +} +#endif diff --git a/lib/digital_signal/digital_signal.c b/lib/digital_signal/digital_signal.c index 25adb878b..a0408900d 100644 --- a/lib/digital_signal/digital_signal.c +++ b/lib/digital_signal/digital_signal.c @@ -1,106 +1,15 @@ #include "digital_signal.h" +#include "digital_signal_i.h" #include -#include -#include -#include - -#include -#include - -/* must be on bank B */ -// For debugging purposes use `--extra-define=DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN=gpio_ext_pb3` fbt option - -struct ReloadBuffer { - uint32_t* buffer; /* DMA ringbuffer */ - uint32_t size; /* maximum entry count of the ring buffer */ - uint32_t write_pos; /* current buffer write index */ - uint32_t read_pos; /* current buffer read index */ - bool dma_active; -}; - -struct DigitalSequence { - uint8_t signals_size; - bool bake; - uint32_t sequence_used; - uint32_t sequence_size; - DigitalSignal** signals; - uint8_t* sequence; - const GpioPin* gpio; - uint32_t send_time; - bool send_time_active; - LL_DMA_InitTypeDef dma_config_gpio; - LL_DMA_InitTypeDef dma_config_timer; - uint32_t* gpio_buff; - struct ReloadBuffer* dma_buffer; -}; - -struct DigitalSignalInternals { - uint64_t factor; - uint32_t reload_reg_entries; - uint32_t reload_reg_remainder; - uint32_t gpio_buff[2]; - const GpioPin* gpio; - LL_DMA_InitTypeDef dma_config_gpio; - LL_DMA_InitTypeDef dma_config_timer; -}; #define TAG "DigitalSignal" -#define F_TIM (64000000.0) -#define T_TIM 1562 /* 15.625 ns *100 */ -#define T_TIM_DIV2 781 /* 15.625 ns / 2 *100 */ - -/* end marker in DMA ringbuffer, will get written into timer register at the end */ -#define SEQ_TIMER_MAX 0xFFFFFFFF - -/* time to wait in loops before returning */ -#define SEQ_LOCK_WAIT_MS 10UL -#define SEQ_LOCK_WAIT_TICKS (SEQ_LOCK_WAIT_MS * 1000 * 64) - -/* maximum entry count of the sequence dma ring buffer */ -#define RINGBUFFER_SIZE 128 - -/* maximum number of DigitalSignals in a sequence */ -#define SEQUENCE_SIGNALS_SIZE 32 -/* - * if sequence size runs out from the initial value passed to digital_sequence_alloc - * the size will be increased by this amount and reallocated - */ -#define SEQUENCE_SIZE_REALLOCATE_INCREMENT 256 - -DigitalSignal* digital_signal_alloc(uint32_t max_edges_cnt) { +DigitalSignal* digital_signal_alloc(uint32_t max_size) { DigitalSignal* signal = malloc(sizeof(DigitalSignal)); - signal->start_level = true; - signal->edges_max_cnt = max_edges_cnt; - signal->edge_timings = malloc(signal->edges_max_cnt * sizeof(uint32_t)); - signal->edge_cnt = 0; - signal->reload_reg_buff = malloc(signal->edges_max_cnt * sizeof(uint32_t)); - signal->internals = malloc(sizeof(DigitalSignalInternals)); - DigitalSignalInternals* internals = signal->internals; - - internals->factor = 1024 * 1024; - - internals->dma_config_gpio.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH; - internals->dma_config_gpio.Mode = LL_DMA_MODE_CIRCULAR; - internals->dma_config_gpio.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; - internals->dma_config_gpio.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; - internals->dma_config_gpio.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; - internals->dma_config_gpio.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; - internals->dma_config_gpio.NbData = 2; - internals->dma_config_gpio.PeriphRequest = LL_DMAMUX_REQ_TIM2_UP; - internals->dma_config_gpio.Priority = LL_DMA_PRIORITY_VERYHIGH; - - internals->dma_config_timer.PeriphOrM2MSrcAddress = (uint32_t) & (TIM2->ARR); - internals->dma_config_timer.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH; - internals->dma_config_timer.Mode = LL_DMA_MODE_NORMAL; - internals->dma_config_timer.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; - internals->dma_config_timer.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; - internals->dma_config_timer.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; - internals->dma_config_timer.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; - internals->dma_config_timer.PeriphRequest = LL_DMAMUX_REQ_TIM2_UP; - internals->dma_config_timer.Priority = LL_DMA_PRIORITY_HIGH; + signal->max_size = max_size; + signal->data = malloc(max_size * sizeof(uint32_t)); return signal; } @@ -108,559 +17,81 @@ DigitalSignal* digital_signal_alloc(uint32_t max_edges_cnt) { void digital_signal_free(DigitalSignal* signal) { furi_assert(signal); - free(signal->edge_timings); - free(signal->reload_reg_buff); - free(signal->internals); + free(signal->data); free(signal); } -bool digital_signal_append(DigitalSignal* signal_a, DigitalSignal* signal_b) { - furi_assert(signal_a); - furi_assert(signal_b); - - if(signal_a->edges_max_cnt < signal_a->edge_cnt + signal_b->edge_cnt) { - return false; - } - /* in case there are no edges in our target signal, the signal to append makes the rules */ - if(!signal_a->edge_cnt) { - signal_a->start_level = signal_b->start_level; - } - bool end_level = signal_a->start_level; - if(signal_a->edge_cnt) { - end_level = signal_a->start_level ^ !(signal_a->edge_cnt % 2); - } - uint8_t start_copy = 0; - if(end_level == signal_b->start_level) { - if(signal_a->edge_cnt) { - signal_a->edge_timings[signal_a->edge_cnt - 1] += signal_b->edge_timings[0]; - start_copy += 1; - } else { - signal_a->edge_timings[signal_a->edge_cnt] += signal_b->edge_timings[0]; - } - } - - for(size_t i = 0; i < signal_b->edge_cnt - start_copy; i++) { - signal_a->edge_timings[signal_a->edge_cnt + i] = signal_b->edge_timings[start_copy + i]; - } - signal_a->edge_cnt += signal_b->edge_cnt - start_copy; - - return true; -} - -bool digital_signal_get_start_level(DigitalSignal* signal) { +bool digital_signal_get_start_level(const DigitalSignal* signal) { furi_assert(signal); return signal->start_level; } -uint32_t digital_signal_get_edges_cnt(DigitalSignal* signal) { +void digital_signal_set_start_level(DigitalSignal* signal, bool level) { furi_assert(signal); - return signal->edge_cnt; + signal->start_level = level; } -void digital_signal_add(DigitalSignal* signal, uint32_t ticks) { +uint32_t digital_signal_get_size(const DigitalSignal* signal) { furi_assert(signal); - furi_assert(signal->edge_cnt < signal->edges_max_cnt); - signal->edge_timings[signal->edge_cnt++] = ticks; + return signal->size; } -void digital_signal_add_pulse(DigitalSignal* signal, uint32_t ticks, bool level) { +void digital_signal_add_period(DigitalSignal* signal, uint32_t ticks) { furi_assert(signal); - furi_assert(signal->edge_cnt < signal->edges_max_cnt); + furi_assert(signal->size < signal->max_size); - /* virgin signal? add it as the only level */ - if(signal->edge_cnt == 0) { + const uint32_t duration = ticks + signal->remainder; + + uint32_t reload_value = duration / DIGITAL_SIGNAL_T_TIM; + int32_t remainder = duration - reload_value * DIGITAL_SIGNAL_T_TIM; + + if(remainder >= DIGITAL_SIGNAL_T_TIM_DIV2) { + reload_value += 1; + remainder -= DIGITAL_SIGNAL_T_TIM; + } + + furi_check(reload_value > 1); + + signal->data[signal->size++] = reload_value - 1; + signal->remainder = remainder; +} + +static void digital_signal_extend_last_period(DigitalSignal* signal, uint32_t ticks) { + furi_assert(signal->size <= signal->max_size); + + const uint32_t reload_value_old = signal->data[signal->size - 1] + 1; + const uint32_t duration = ticks + signal->remainder + reload_value_old * DIGITAL_SIGNAL_T_TIM; + + uint32_t reload_value = duration / DIGITAL_SIGNAL_T_TIM; + int32_t remainder = duration - reload_value * DIGITAL_SIGNAL_T_TIM; + + if(remainder >= DIGITAL_SIGNAL_T_TIM_DIV2) { + reload_value += 1; + remainder -= DIGITAL_SIGNAL_T_TIM; + } + + furi_check(reload_value > 1); + + signal->data[signal->size - 1] = reload_value - 1; + signal->remainder = remainder; +} + +void digital_signal_add_period_with_level(DigitalSignal* signal, uint32_t ticks, bool level) { + furi_assert(signal); + + if(signal->size == 0) { signal->start_level = level; - signal->edge_timings[signal->edge_cnt++] = ticks; + digital_signal_add_period(signal, ticks); } else { - bool end_level = signal->start_level ^ !(signal->edge_cnt % 2); + const bool end_level = signal->start_level ^ !(signal->size % 2); if(level != end_level) { - signal->edge_timings[signal->edge_cnt++] = ticks; + digital_signal_add_period(signal, ticks); } else { - signal->edge_timings[signal->edge_cnt - 1] += ticks; - } - } -} - -uint32_t digital_signal_get_edge(DigitalSignal* signal, uint32_t edge_num) { - furi_assert(signal); - furi_assert(edge_num < signal->edge_cnt); - - return signal->edge_timings[edge_num]; -} - -void digital_signal_prepare_arr(DigitalSignal* signal) { - furi_assert(signal); - - DigitalSignalInternals* internals = signal->internals; - - /* set up signal polarities */ - if(internals->gpio) { - uint32_t bit_set = internals->gpio->pin; - uint32_t bit_reset = internals->gpio->pin << 16; - -#ifdef DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN - bit_set |= DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN.pin; - bit_reset |= DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN.pin << 16; -#endif - - if(signal->start_level) { - internals->gpio_buff[0] = bit_set; - internals->gpio_buff[1] = bit_reset; - } else { - internals->gpio_buff[0] = bit_reset; - internals->gpio_buff[1] = bit_set; - } - } - - /* set up edge timings */ - internals->reload_reg_entries = 0; - - for(size_t pos = 0; pos < signal->edge_cnt; pos++) { - uint32_t pulse_duration = signal->edge_timings[pos] + internals->reload_reg_remainder; - if(pulse_duration < 10 || pulse_duration > 10000000) { - FURI_LOG_D( - TAG, - "[prepare] pulse_duration out of range: %lu = %lu * %llu", - pulse_duration, - signal->edge_timings[pos], - internals->factor); - pulse_duration = 100; - } - uint32_t pulse_ticks = (pulse_duration + T_TIM_DIV2) / T_TIM; - internals->reload_reg_remainder = pulse_duration - (pulse_ticks * T_TIM); - - if(pulse_ticks > 1) { - signal->reload_reg_buff[internals->reload_reg_entries++] = pulse_ticks - 1; - } - } -} - -static void digital_signal_stop_dma() { - LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_1); - LL_DMA_DisableChannel(DMA1, LL_DMA_CHANNEL_2); - LL_DMA_ClearFlag_TC1(DMA1); - LL_DMA_ClearFlag_TC2(DMA1); -} - -static void digital_signal_stop_timer() { - LL_TIM_DisableCounter(TIM2); - LL_TIM_DisableUpdateEvent(TIM2); - LL_TIM_DisableDMAReq_UPDATE(TIM2); - - furi_hal_bus_disable(FuriHalBusTIM2); -} - -static void digital_signal_setup_timer() { - furi_hal_bus_enable(FuriHalBusTIM2); - - LL_TIM_SetCounterMode(TIM2, LL_TIM_COUNTERMODE_UP); - LL_TIM_SetClockDivision(TIM2, LL_TIM_CLOCKDIVISION_DIV1); - LL_TIM_SetPrescaler(TIM2, 0); - LL_TIM_SetAutoReload(TIM2, SEQ_TIMER_MAX); - LL_TIM_SetCounter(TIM2, 0); -} - -static void digital_signal_start_timer() { - LL_TIM_EnableCounter(TIM2); - LL_TIM_EnableUpdateEvent(TIM2); - LL_TIM_EnableDMAReq_UPDATE(TIM2); - LL_TIM_GenerateEvent_UPDATE(TIM2); -} - -static bool digital_signal_setup_dma(DigitalSignal* signal) { - furi_assert(signal); - DigitalSignalInternals* internals = signal->internals; - - if(!signal->internals->reload_reg_entries) { - return false; - } - digital_signal_stop_dma(); - - internals->dma_config_gpio.MemoryOrM2MDstAddress = (uint32_t)internals->gpio_buff; - internals->dma_config_gpio.PeriphOrM2MSrcAddress = (uint32_t) & (internals->gpio->port->BSRR); - internals->dma_config_timer.MemoryOrM2MDstAddress = (uint32_t)signal->reload_reg_buff; - internals->dma_config_timer.NbData = signal->internals->reload_reg_entries; - - /* set up DMA channel 1 and 2 for GPIO and timer copy operations */ - LL_DMA_Init(DMA1, LL_DMA_CHANNEL_1, &internals->dma_config_gpio); - LL_DMA_Init(DMA1, LL_DMA_CHANNEL_2, &internals->dma_config_timer); - - /* enable both DMA channels */ - LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); - LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_2); - - return true; -} - -void digital_signal_send(DigitalSignal* signal, const GpioPin* gpio) { - furi_assert(signal); - - if(!signal->edge_cnt) { - return; - } - - /* Configure gpio as output */ - signal->internals->gpio = gpio; - furi_hal_gpio_init( - signal->internals->gpio, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - - digital_signal_prepare_arr(signal); - - digital_signal_setup_dma(signal); - digital_signal_setup_timer(); - digital_signal_start_timer(); - - while(!LL_DMA_IsActiveFlag_TC2(DMA1)) { - } - - digital_signal_stop_timer(); - digital_signal_stop_dma(); -} - -static void digital_sequence_alloc_signals(DigitalSequence* sequence, uint32_t size) { - sequence->signals_size = size; - sequence->signals = malloc(sequence->signals_size * sizeof(DigitalSignal*)); -} - -static void digital_sequence_alloc_sequence(DigitalSequence* sequence, uint32_t size) { - sequence->sequence_used = 0; - sequence->sequence_size = size; - sequence->sequence = malloc(sequence->sequence_size); - sequence->send_time = 0; - sequence->send_time_active = false; -} - -DigitalSequence* digital_sequence_alloc(uint32_t size, const GpioPin* gpio) { - furi_assert(gpio); - - DigitalSequence* sequence = malloc(sizeof(DigitalSequence)); - - sequence->gpio = gpio; - sequence->bake = false; - - sequence->dma_buffer = malloc(sizeof(struct ReloadBuffer)); - sequence->dma_buffer->size = RINGBUFFER_SIZE; - sequence->dma_buffer->buffer = malloc(sequence->dma_buffer->size * sizeof(uint32_t)); - - sequence->dma_config_gpio.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH; - sequence->dma_config_gpio.Mode = LL_DMA_MODE_CIRCULAR; - sequence->dma_config_gpio.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; - sequence->dma_config_gpio.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; - sequence->dma_config_gpio.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; - sequence->dma_config_gpio.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; - sequence->dma_config_gpio.NbData = 2; - sequence->dma_config_gpio.PeriphRequest = LL_DMAMUX_REQ_TIM2_UP; - sequence->dma_config_gpio.Priority = LL_DMA_PRIORITY_VERYHIGH; - - sequence->dma_config_timer.Direction = LL_DMA_DIRECTION_MEMORY_TO_PERIPH; - sequence->dma_config_timer.Mode = LL_DMA_MODE_CIRCULAR; - sequence->dma_config_timer.PeriphOrM2MSrcIncMode = LL_DMA_PERIPH_NOINCREMENT; - sequence->dma_config_timer.MemoryOrM2MDstIncMode = LL_DMA_MEMORY_INCREMENT; - sequence->dma_config_timer.PeriphOrM2MSrcDataSize = LL_DMA_PDATAALIGN_WORD; - sequence->dma_config_timer.MemoryOrM2MDstDataSize = LL_DMA_MDATAALIGN_WORD; - sequence->dma_config_timer.PeriphOrM2MSrcAddress = (uint32_t) & (TIM2->ARR); - sequence->dma_config_timer.MemoryOrM2MDstAddress = (uint32_t)sequence->dma_buffer->buffer; - sequence->dma_config_timer.NbData = sequence->dma_buffer->size; - sequence->dma_config_timer.PeriphRequest = LL_DMAMUX_REQ_TIM2_UP; - sequence->dma_config_timer.Priority = LL_DMA_PRIORITY_HIGH; - - digital_sequence_alloc_signals(sequence, SEQUENCE_SIGNALS_SIZE); - digital_sequence_alloc_sequence(sequence, size); - - return sequence; -} - -void digital_sequence_free(DigitalSequence* sequence) { - furi_assert(sequence); - - free(sequence->signals); - free(sequence->sequence); - free(sequence->dma_buffer->buffer); - free(sequence->dma_buffer); - free(sequence); -} - -void digital_sequence_set_signal( - DigitalSequence* sequence, - uint8_t signal_index, - DigitalSignal* signal) { - furi_assert(sequence); - furi_assert(signal); - furi_assert(signal_index < sequence->signals_size); - - sequence->signals[signal_index] = signal; - signal->internals->gpio = sequence->gpio; - signal->internals->reload_reg_remainder = 0; - - digital_signal_prepare_arr(signal); -} - -void digital_sequence_set_sendtime(DigitalSequence* sequence, uint32_t send_time) { - furi_assert(sequence); - - sequence->send_time = send_time; - sequence->send_time_active = true; -} - -void digital_sequence_add(DigitalSequence* sequence, uint8_t signal_index) { - furi_assert(sequence); - furi_assert(signal_index < sequence->signals_size); - - if(sequence->sequence_used >= sequence->sequence_size) { - sequence->sequence_size += SEQUENCE_SIZE_REALLOCATE_INCREMENT; - sequence->sequence = realloc(sequence->sequence, sequence->sequence_size); //-V701 - furi_assert(sequence->sequence); - } - - sequence->sequence[sequence->sequence_used++] = signal_index; -} - -static bool digital_sequence_setup_dma(DigitalSequence* sequence) { - furi_assert(sequence); - - digital_signal_stop_dma(); - - sequence->dma_config_gpio.MemoryOrM2MDstAddress = (uint32_t)sequence->gpio_buff; - sequence->dma_config_gpio.PeriphOrM2MSrcAddress = (uint32_t) & (sequence->gpio->port->BSRR); - - /* set up DMA channel 1 and 2 for GPIO and timer copy operations */ - LL_DMA_Init(DMA1, LL_DMA_CHANNEL_1, &sequence->dma_config_gpio); - LL_DMA_Init(DMA1, LL_DMA_CHANNEL_2, &sequence->dma_config_timer); - - /* enable both DMA channels */ - LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_1); - LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_2); - - return true; -} - -static DigitalSignal* digital_sequence_bake(DigitalSequence* sequence) { - furi_assert(sequence); - - uint32_t edges = 0; - - for(uint32_t pos = 0; pos < sequence->sequence_used; pos++) { - uint8_t signal_index = sequence->sequence[pos]; - DigitalSignal* sig = sequence->signals[signal_index]; - - edges += sig->edge_cnt; - } - - DigitalSignal* ret = digital_signal_alloc(edges); - - for(uint32_t pos = 0; pos < sequence->sequence_used; pos++) { - uint8_t signal_index = sequence->sequence[pos]; - DigitalSignal* sig = sequence->signals[signal_index]; - - digital_signal_append(ret, sig); - } - - return ret; -} - -static void digital_sequence_finish(DigitalSequence* sequence) { - struct ReloadBuffer* dma_buffer = sequence->dma_buffer; - - if(dma_buffer->dma_active) { - uint32_t prev_timer = DWT->CYCCNT; - do { - /* we are finished, when the DMA transferred the SEQ_TIMER_MAX marker */ - if(TIM2->ARR == SEQ_TIMER_MAX) { - break; - } - if(DWT->CYCCNT - prev_timer > SEQ_LOCK_WAIT_TICKS) { - dma_buffer->read_pos = - RINGBUFFER_SIZE - LL_DMA_GetDataLength(DMA1, LL_DMA_CHANNEL_2); - FURI_LOG_D( - TAG, - "[SEQ] hung %lu ms in finish (ARR 0x%08lx, read %lu, write %lu)", - SEQ_LOCK_WAIT_MS, - TIM2->ARR, - dma_buffer->read_pos, - dma_buffer->write_pos); - break; - } - } while(1); - } - - digital_signal_stop_timer(); - digital_signal_stop_dma(); -} - -static void digital_sequence_queue_pulse(DigitalSequence* sequence, uint32_t length) { - struct ReloadBuffer* dma_buffer = sequence->dma_buffer; - - if(dma_buffer->dma_active) { - uint32_t prev_timer = DWT->CYCCNT; - do { - dma_buffer->read_pos = RINGBUFFER_SIZE - LL_DMA_GetDataLength(DMA1, LL_DMA_CHANNEL_2); - - uint32_t free = - (RINGBUFFER_SIZE + dma_buffer->read_pos - dma_buffer->write_pos) % RINGBUFFER_SIZE; - - if(free > 2) { - break; - } - - if(DWT->CYCCNT - prev_timer > SEQ_LOCK_WAIT_TICKS) { - FURI_LOG_D( - TAG, - "[SEQ] hung %lu ms in queue (ARR 0x%08lx, read %lu, write %lu)", - SEQ_LOCK_WAIT_MS, - TIM2->ARR, - dma_buffer->read_pos, - dma_buffer->write_pos); - break; - } - if(TIM2->ARR == SEQ_TIMER_MAX) { - FURI_LOG_D( - TAG, - "[SEQ] buffer underrun in queue (ARR 0x%08lx, read %lu, write %lu)", - TIM2->ARR, - dma_buffer->read_pos, - dma_buffer->write_pos); - break; - } - } while(1); - } - - dma_buffer->buffer[dma_buffer->write_pos] = length; - dma_buffer->write_pos++; - dma_buffer->write_pos %= RINGBUFFER_SIZE; - dma_buffer->buffer[dma_buffer->write_pos] = SEQ_TIMER_MAX; -} - -bool digital_sequence_send(DigitalSequence* sequence) { - furi_assert(sequence); - - struct ReloadBuffer* dma_buffer = sequence->dma_buffer; - - furi_hal_gpio_init(sequence->gpio, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); -#ifdef DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN - furi_hal_gpio_init( - &DIGITAL_SIGNAL_DEBUG_OUTPUT_PIN, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); -#endif - - if(sequence->bake) { - DigitalSignal* sig = digital_sequence_bake(sequence); - - digital_signal_send(sig, sequence->gpio); - digital_signal_free(sig); - return true; - } - - if(!sequence->sequence_used) { - return false; - } - - int32_t remainder = 0; - uint32_t trade_for_next = 0; - uint32_t seq_pos_next = 1; - - dma_buffer->dma_active = false; - dma_buffer->buffer[0] = SEQ_TIMER_MAX; - dma_buffer->read_pos = 0; - dma_buffer->write_pos = 0; - - /* already prepare the current signal pointer */ - DigitalSignal* sig = sequence->signals[sequence->sequence[0]]; - DigitalSignal* sig_next = NULL; - /* re-use the GPIO buffer from the first signal */ - sequence->gpio_buff = sig->internals->gpio_buff; - - FURI_CRITICAL_ENTER(); - - while(sig) { - bool last_signal = (seq_pos_next >= sequence->sequence_used); - - if(!last_signal) { - sig_next = sequence->signals[sequence->sequence[seq_pos_next++]]; - } - - for(uint32_t pulse_pos = 0; pulse_pos < sig->internals->reload_reg_entries; pulse_pos++) { - bool last_pulse = ((pulse_pos + 1) >= sig->internals->reload_reg_entries); - uint32_t pulse_length = sig->reload_reg_buff[pulse_pos] + trade_for_next; - - trade_for_next = 0; - - /* when we are too late more than half a tick, make the first edge temporarily longer */ - if(remainder >= T_TIM_DIV2) { - remainder -= T_TIM; - pulse_length += 1; - } - - /* last pulse in current signal and have a next signal? */ - if(last_pulse && sig_next) { - /* when a signal ends with the same level as the next signal begins, let the next signal generate the whole pulse. - beware, we do not want the level after the last edge, but the last level before that edge */ - bool end_level = sig->start_level ^ ((sig->edge_cnt % 2) == 0); - - /* if they have the same level, pass the duration to the next pulse(s) */ - if(end_level == sig_next->start_level) { - trade_for_next = pulse_length; - } - } - - /* if it was decided, that the next signal's first pulse shall also handle our "length", then do not queue here */ - if(!trade_for_next) { - digital_sequence_queue_pulse(sequence, pulse_length); - - if(!dma_buffer->dma_active) { - /* start transmission when buffer was filled enough */ - bool start_send = sequence->dma_buffer->write_pos >= (RINGBUFFER_SIZE - 2); - - /* or it was the last pulse */ - if(last_pulse && last_signal) { - start_send = true; - } - - /* start transmission */ - if(start_send) { - digital_sequence_setup_dma(sequence); - digital_signal_setup_timer(); - - /* if the send time is specified, wait till the core timer passed beyond that time */ - if(sequence->send_time_active) { - sequence->send_time_active = false; - while(sequence->send_time - DWT->CYCCNT < 0x80000000) { - } - } - digital_signal_start_timer(); - dma_buffer->dma_active = true; - } - } - } - } - - remainder += sig->internals->reload_reg_remainder; - sig = sig_next; - sig_next = NULL; - } - - /* wait until last dma transaction was finished */ - FURI_CRITICAL_EXIT(); - digital_sequence_finish(sequence); - - return true; -} - -void digital_sequence_clear(DigitalSequence* sequence) { - furi_assert(sequence); - - sequence->sequence_used = 0; -} - -void digital_sequence_timebase_correction(DigitalSequence* sequence, float factor) { - for(uint32_t sig_pos = 0; sig_pos < sequence->signals_size; sig_pos++) { - DigitalSignal* signal = sequence->signals[sig_pos]; - - if(signal) { - signal->internals->factor = (uint32_t)(1024 * 1024 * factor); - digital_signal_prepare_arr(signal); + digital_signal_extend_last_period(signal, ticks); } } } diff --git a/lib/digital_signal/digital_signal.h b/lib/digital_signal/digital_signal.h index 404d02605..f29facfd8 100644 --- a/lib/digital_signal/digital_signal.h +++ b/lib/digital_signal/digital_signal.h @@ -1,74 +1,121 @@ +/** + * @file digital_signal.h + * @brief Simple digital signal container for the DigitalSequence library. + * + * Each signal is represented by its start level (high or low) and one or more periods. + * The output will transition to its inverse value on each period boundary. + * + * Example: A signal with n periods and HIGH start level. + * + * ``` + * ----+ +------+ +- ... -+ + * t0 | t1 | t2 | t3 | | tn - 1 + * +--------+ +----+ +-------- + * ``` + * + */ #pragma once #include -#include #include -#include - #ifdef __cplusplus extern "C" { #endif -/* helper for easier signal generation */ +// DigitalSignal uses 10 picosecond time units (1 tick = 10 ps). +// Use the macros below to convert the time from other units. + #define DIGITAL_SIGNAL_MS(x) ((x)*100000000UL) #define DIGITAL_SIGNAL_US(x) ((x)*100000UL) #define DIGITAL_SIGNAL_NS(x) ((x)*100UL) #define DIGITAL_SIGNAL_PS(x) ((x) / 10UL) -/* using an anonymous type for the internals */ -typedef struct DigitalSignalInternals DigitalSignalInternals; +typedef struct DigitalSignal DigitalSignal; -/* and a public one for accessing user-side fields */ -typedef struct DigitalSignal { - bool start_level; - uint32_t edge_cnt; - uint32_t edges_max_cnt; - uint32_t* edge_timings; - uint32_t* reload_reg_buff; /* internal, but used by unit tests */ - DigitalSignalInternals* internals; -} DigitalSignal; - -typedef struct DigitalSequence DigitalSequence; - -DigitalSignal* digital_signal_alloc(uint32_t max_edges_cnt); +/** + * @brief Allocate a DigitalSignal instance with a defined maximum size. + * + * @param[in] max_size the maximum number of periods the instance will be able to contain. + * @returns pointer to the allocated instance. + */ +DigitalSignal* digital_signal_alloc(uint32_t max_size); +/** + * @brief Delete a previously allocated DigitalSignal instance. + * + * @param[in,out] signal pointer to the instance to be deleted. + */ void digital_signal_free(DigitalSignal* signal); -void digital_signal_add(DigitalSignal* signal, uint32_t ticks); +/** + * @brief Append one period to the end of the DigitalSignal instance. + * + * @param[in,out] signal pointer to a the instance to append to. + * @param[in] ticks the period length, in 10 picosecond units. + */ +void digital_signal_add_period(DigitalSignal* signal, uint32_t ticks); -void digital_signal_add_pulse(DigitalSignal* signal, uint32_t ticks, bool level); +/** + * @brief Append one period to the end of the DigitalSignal instance, with the level specified. + * + * If the level is the same as the last level contained in the instance, then it is extened + * by the given ticks value. Otherwise, the behaviour is identical to digital_signal_add_period(). + * + * Example 1: add tc with HIGH level + * ``` + * before: + * ... ------+ + * ta | tb + * +------- + * after: + * ... ------+ +------- + * ta | tb | tc + * +------+ + * ``` + * Example 2: add tc with LOW level + * ``` + * before: + * ... ------+ + * ta | tb + * +------- + * after: + * ... ------+ + * ta | tb + tc + * +-------------- + * ``` + * + * @param[in,out] signal pointer to the instance to append to. + * @param[in] ticks the period length, in 10 picosecond units. + * @param[in] level the level to be set during the period. + */ +void digital_signal_add_period_with_level(DigitalSignal* signal, uint32_t ticks, bool level); -bool digital_signal_append(DigitalSignal* signal_a, DigitalSignal* signal_b); +/** + * @brief Get the current start level contained in the DigitalSignal instance. + * + * If not explicitly set with digital_signal_set_start_level(), it defaults to false. + * + * @param[in] signal pointer to the instance to be queried. + * @returns the start level value. + */ +bool digital_signal_get_start_level(const DigitalSignal* signal); -void digital_signal_prepare_arr(DigitalSignal* signal); +/** + * @brief Set the start level contained in the DigitalSignal instance. + * + * @param[in,out] signal pointer to the instance to be modified. + * @param[in] level signal level to be set as the start level. + */ +void digital_signal_set_start_level(DigitalSignal* signal, bool level); -bool digital_signal_get_start_level(DigitalSignal* signal); - -uint32_t digital_signal_get_edges_cnt(DigitalSignal* signal); - -uint32_t digital_signal_get_edge(DigitalSignal* signal, uint32_t edge_num); - -void digital_signal_send(DigitalSignal* signal, const GpioPin* gpio); - -DigitalSequence* digital_sequence_alloc(uint32_t size, const GpioPin* gpio); - -void digital_sequence_free(DigitalSequence* sequence); - -void digital_sequence_set_signal( - DigitalSequence* sequence, - uint8_t signal_index, - DigitalSignal* signal); - -void digital_sequence_set_sendtime(DigitalSequence* sequence, uint32_t send_time); - -void digital_sequence_add(DigitalSequence* sequence, uint8_t signal_index); - -bool digital_sequence_send(DigitalSequence* sequence); - -void digital_sequence_clear(DigitalSequence* sequence); - -void digital_sequence_timebase_correction(DigitalSequence* sequence, float factor); +/** + * @brief Get the number of periods currently stored in a DigitalSignal instance. + * + * @param[in] signal pointer to the instance to be queried. + * @return the number of periods stored in the instance. + */ +uint32_t digital_signal_get_size(const DigitalSignal* signal); #ifdef __cplusplus } diff --git a/lib/digital_signal/digital_signal_i.h b/lib/digital_signal/digital_signal_i.h new file mode 100644 index 000000000..e473c80c0 --- /dev/null +++ b/lib/digital_signal/digital_signal_i.h @@ -0,0 +1,23 @@ +/** + * @file digital_signal_i.h + * @brief DigitalSignal private definitions. + * + * This file is an implementation detail. It must not be included in + * any public API-related headers. + */ +#include +#include + +#define DIGITAL_SIGNAL_T_TIM 1562 /**< 15.625 ns *100 */ +#define DIGITAL_SIGNAL_T_TIM_DIV2 (DIGITAL_SIGNAL_T_TIM / 2) /**< 15.625 ns / 2 *100 */ + +/** + * @brief DigitalSignal structure type. + */ +struct DigitalSignal { + bool start_level; /**< The level to begin the signal with. */ + uint32_t size; /**< Current period count contained in the instance. */ + uint32_t max_size; /**< Maximum period count this instance can hold. */ + uint32_t* data; /**< Pointer to the array of time periods. */ + int32_t remainder; /**< Remainder left after converting all periods into timer ticks. */ +}; diff --git a/lib/digital_signal/presets/nfc/iso14443_3a_signal.c b/lib/digital_signal/presets/nfc/iso14443_3a_signal.c new file mode 100644 index 000000000..1f3824e2d --- /dev/null +++ b/lib/digital_signal/presets/nfc/iso14443_3a_signal.c @@ -0,0 +1,139 @@ +#include "iso14443_3a_signal.h" + +#include + +#define BITS_IN_BYTE (8) + +#define ISO14443_3A_SIGNAL_BIT_MAX_EDGES (10) +#define ISO14443_3A_SIGNAL_MAX_EDGES (1350) + +#define ISO14443_3A_SIGNAL_SEQUENCE_SIZE \ + (ISO14443_3A_SIGNAL_MAX_EDGES / (ISO14443_3A_SIGNAL_BIT_MAX_EDGES - 2)) + +#define ISO14443_3A_SIGNAL_F_SIG (13560000.0) +#define ISO14443_3A_SIGNAL_T_SIG 7374 //73.746ns*100 +#define ISO14443_3A_SIGNAL_T_SIG_X8 58992 //T_SIG*8 +#define ISO14443_3A_SIGNAL_T_SIG_X8_X8 471936 //T_SIG*8*8 +#define ISO14443_3A_SIGNAL_T_SIG_X8_X9 530928 //T_SIG*8*9 + +typedef enum { + Iso14443_3aSignalIndexZero, + Iso14443_3aSignalIndexOne, + Iso14443_3aSignalIndexCount, +} Iso14443_3aSignalIndex; + +typedef DigitalSignal* Iso14443_3aSignalBank[Iso14443_3aSignalIndexCount]; + +struct Iso14443_3aSignal { + DigitalSequence* tx_sequence; + Iso14443_3aSignalBank signals; +}; + +static void iso14443_3a_signal_add_byte(Iso14443_3aSignal* instance, uint8_t byte, bool parity) { + for(size_t i = 0; i < BITS_IN_BYTE; i++) { + digital_sequence_add_signal( + instance->tx_sequence, + FURI_BIT(byte, i) ? Iso14443_3aSignalIndexOne : Iso14443_3aSignalIndexZero); + } + digital_sequence_add_signal( + instance->tx_sequence, parity ? Iso14443_3aSignalIndexOne : Iso14443_3aSignalIndexZero); +} + +static void iso14443_3a_signal_encode( + Iso14443_3aSignal* instance, + const uint8_t* tx_data, + const uint8_t* tx_parity, + size_t tx_bits) { + furi_assert(instance); + furi_assert(tx_data); + furi_assert(tx_parity); + + // Start of frame + digital_sequence_add_signal(instance->tx_sequence, Iso14443_3aSignalIndexOne); + + if(tx_bits < BITS_IN_BYTE) { + for(size_t i = 0; i < tx_bits; i++) { + digital_sequence_add_signal( + instance->tx_sequence, + FURI_BIT(tx_data[0], i) ? Iso14443_3aSignalIndexOne : Iso14443_3aSignalIndexZero); + } + } else { + for(size_t i = 0; i < tx_bits / BITS_IN_BYTE; i++) { + bool parity = FURI_BIT(tx_parity[i / BITS_IN_BYTE], i % BITS_IN_BYTE); + iso14443_3a_signal_add_byte(instance, tx_data[i], parity); + } + } +} + +static inline void iso14443_3a_signal_set_bit(DigitalSignal* signal, bool bit) { + digital_signal_set_start_level(signal, bit); + + if(bit) { + for(uint32_t i = 0; i < 7; ++i) { + digital_signal_add_period(signal, ISO14443_3A_SIGNAL_T_SIG_X8); + } + digital_signal_add_period(signal, ISO14443_3A_SIGNAL_T_SIG_X8_X9); + } else { + digital_signal_add_period(signal, ISO14443_3A_SIGNAL_T_SIG_X8_X8); + for(uint32_t i = 0; i < 8; ++i) { + digital_signal_add_period(signal, ISO14443_3A_SIGNAL_T_SIG_X8); + } + } +} + +static inline void iso14443_3a_signal_bank_fill(Iso14443_3aSignalBank bank) { + for(uint32_t i = 0; i < Iso14443_3aSignalIndexCount; ++i) { + bank[i] = digital_signal_alloc(ISO14443_3A_SIGNAL_BIT_MAX_EDGES); + iso14443_3a_signal_set_bit(bank[i], i % Iso14443_3aSignalIndexCount != 0); + } +} + +static inline void iso14443_3a_signal_bank_clear(Iso14443_3aSignalBank bank) { + for(uint32_t i = 0; i < Iso14443_3aSignalIndexCount; ++i) { + digital_signal_free(bank[i]); + } +} + +static inline void + iso14443_3a_signal_bank_register(Iso14443_3aSignalBank bank, DigitalSequence* sequence) { + for(uint32_t i = 0; i < Iso14443_3aSignalIndexCount; ++i) { + digital_sequence_register_signal(sequence, i, bank[i]); + } +} + +Iso14443_3aSignal* iso14443_3a_signal_alloc(const GpioPin* pin) { + furi_assert(pin); + + Iso14443_3aSignal* instance = malloc(sizeof(Iso14443_3aSignal)); + instance->tx_sequence = digital_sequence_alloc(ISO14443_3A_SIGNAL_SEQUENCE_SIZE, pin); + + iso14443_3a_signal_bank_fill(instance->signals); + iso14443_3a_signal_bank_register(instance->signals, instance->tx_sequence); + + return instance; +} + +void iso14443_3a_signal_free(Iso14443_3aSignal* instance) { + furi_assert(instance); + furi_assert(instance->tx_sequence); + + iso14443_3a_signal_bank_clear(instance->signals); + digital_sequence_free(instance->tx_sequence); + free(instance); +} + +void iso14443_3a_signal_tx( + Iso14443_3aSignal* instance, + const uint8_t* tx_data, + const uint8_t* tx_parity, + size_t tx_bits) { + furi_assert(instance); + furi_assert(tx_data); + furi_assert(tx_parity); + + FURI_CRITICAL_ENTER(); + digital_sequence_clear(instance->tx_sequence); + iso14443_3a_signal_encode(instance, tx_data, tx_parity, tx_bits); + digital_sequence_transmit(instance->tx_sequence); + FURI_CRITICAL_EXIT(); +} diff --git a/lib/digital_signal/presets/nfc/iso14443_3a_signal.h b/lib/digital_signal/presets/nfc/iso14443_3a_signal.h new file mode 100644 index 000000000..73269e66c --- /dev/null +++ b/lib/digital_signal/presets/nfc/iso14443_3a_signal.h @@ -0,0 +1,51 @@ +/** + * @file iso14443_3a_signal.h + * @brief DigitalSequence preset for generating ISO14443-3A compliant signals. + */ +#pragma once + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso14443_3aSignal Iso14443_3aSignal; + +/** + * @brief Allocate an Iso14443_3aSignal instance with a set GPIO pin. + * + * @param[in] pin GPIO pin to use during transmission. + * @returns pointer to the allocated instance. + */ +Iso14443_3aSignal* iso14443_3a_signal_alloc(const GpioPin* pin); + +/** + * @brief Delete an Iso14443_3aSignal instance. + * + * @param[in,out] instance pointer to the instance to be deleted. + */ +void iso14443_3a_signal_free(Iso14443_3aSignal* instance); + +/** + * @brief Transmit arbitrary bytes using an Iso14443_3aSignal instance. + * + * This function will block until the transmisson has been completed. + * + * @param[in] instance pointer to the instance used in transmission. + * @param[in] tx_data pointer to the data to be transmitted. + * @param[in] tx_parity pointer to the bit-packed parity array. + * @param[in] tx_bits size of the data to be transmitted in bits. + */ +void iso14443_3a_signal_tx( + Iso14443_3aSignal* instance, + const uint8_t* tx_data, + const uint8_t* tx_parity, + size_t tx_bits); + +#ifdef __cplusplus +} +#endif diff --git a/lib/digital_signal/presets/nfc/iso15693_signal.c b/lib/digital_signal/presets/nfc/iso15693_signal.c new file mode 100644 index 000000000..735a88f57 --- /dev/null +++ b/lib/digital_signal/presets/nfc/iso15693_signal.c @@ -0,0 +1,204 @@ +#include "iso15693_signal.h" + +#include + +#define BITS_IN_BYTE (8U) + +#define ISO15693_SIGNAL_COEFF_HI (1U) +#define ISO15693_SIGNAL_COEFF_LO (4U) + +#define ISO15693_SIGNAL_ZERO_EDGES (16U) +#define ISO15693_SIGNAL_ONE_EDGES (ISO15693_SIGNAL_ZERO_EDGES + 1U) +#define ISO15693_SIGNAL_EOF_EDGES (64U) +#define ISO15693_SIGNAL_SOF_EDGES (ISO15693_SIGNAL_EOF_EDGES + 1U) +#define ISO15693_SIGNAL_EDGES (1350U) + +#define ISO15693_SIGNAL_FC (13.56e6) +#define ISO15693_SIGNAL_FC_16 (16.0e11 / ISO15693_SIGNAL_FC) +#define ISO15693_SIGNAL_FC_256 (256.0e11 / ISO15693_SIGNAL_FC) +#define ISO15693_SIGNAL_FC_768 (768.0e11 / ISO15693_SIGNAL_FC) + +typedef enum { + Iso15693SignalIndexSof, + Iso15693SignalIndexEof, + Iso15693SignalIndexOne, + Iso15693SignalIndexZero, + Iso15693SignalIndexNum, +} Iso15693SignalIndex; + +typedef DigitalSignal* Iso15693SignalBank[Iso15693SignalIndexNum]; + +struct Iso15693Signal { + DigitalSequence* tx_sequence; + Iso15693SignalBank banks[Iso15693SignalDataRateNum]; +}; + +// Add an unmodulated signal for the length of Fc / 256 * k (where k = 1 or 4) +static void iso15693_add_silence(DigitalSignal* signal, Iso15693SignalDataRate data_rate) { + const uint32_t k = data_rate == Iso15693SignalDataRateHi ? ISO15693_SIGNAL_COEFF_HI : + ISO15693_SIGNAL_COEFF_LO; + digital_signal_add_period_with_level(signal, ISO15693_SIGNAL_FC_256 * k, false); +} + +// Add 8 * k subcarrier pulses of Fc / 16 (where k = 1 or 4) +static void iso15693_add_subcarrier(DigitalSignal* signal, Iso15693SignalDataRate data_rate) { + const uint32_t k = data_rate == Iso15693SignalDataRateHi ? ISO15693_SIGNAL_COEFF_HI : + ISO15693_SIGNAL_COEFF_LO; + for(uint32_t i = 0; i < ISO15693_SIGNAL_ZERO_EDGES * k; ++i) { + digital_signal_add_period_with_level(signal, ISO15693_SIGNAL_FC_16, !(i % 2)); + } +} + +static void iso15693_add_bit(DigitalSignal* signal, Iso15693SignalDataRate data_rate, bool bit) { + if(bit) { + iso15693_add_silence(signal, data_rate); + iso15693_add_subcarrier(signal, data_rate); + } else { + iso15693_add_subcarrier(signal, data_rate); + iso15693_add_silence(signal, data_rate); + } +} + +static inline void iso15693_add_sof(DigitalSignal* signal, Iso15693SignalDataRate data_rate) { + // Not adding silence since it only increases response time + + for(uint32_t i = 0; i < ISO15693_SIGNAL_FC_768 / ISO15693_SIGNAL_FC_256; ++i) { + iso15693_add_subcarrier(signal, data_rate); + } + + iso15693_add_bit(signal, data_rate, true); +} + +static inline void iso15693_add_eof(DigitalSignal* signal, Iso15693SignalDataRate data_rate) { + iso15693_add_bit(signal, data_rate, false); + + for(uint32_t i = 0; i < ISO15693_SIGNAL_FC_768 / ISO15693_SIGNAL_FC_256; ++i) { + iso15693_add_subcarrier(signal, data_rate); + } + + // Not adding silence since it does nothing here +} + +static inline uint32_t + iso15693_get_sequence_index(Iso15693SignalIndex index, Iso15693SignalDataRate data_rate) { + return index + data_rate * Iso15693SignalIndexNum; +} + +static inline void + iso15693_add_byte(Iso15693Signal* instance, Iso15693SignalDataRate data_rate, uint8_t byte) { + for(size_t i = 0; i < BITS_IN_BYTE; i++) { + const uint8_t bit = byte & (1U << i); + digital_sequence_add_signal( + instance->tx_sequence, + iso15693_get_sequence_index( + bit ? Iso15693SignalIndexOne : Iso15693SignalIndexZero, data_rate)); + } +} + +static inline void iso15693_signal_encode( + Iso15693Signal* instance, + Iso15693SignalDataRate data_rate, + const uint8_t* tx_data, + size_t tx_data_size) { + digital_sequence_add_signal( + instance->tx_sequence, iso15693_get_sequence_index(Iso15693SignalIndexSof, data_rate)); + + for(size_t i = 0; i < tx_data_size; i++) { + iso15693_add_byte(instance, data_rate, tx_data[i]); + } + + digital_sequence_add_signal( + instance->tx_sequence, iso15693_get_sequence_index(Iso15693SignalIndexEof, data_rate)); +} + +static void iso15693_signal_bank_fill(Iso15693Signal* instance, Iso15693SignalDataRate data_rate) { + const uint32_t k = data_rate == Iso15693SignalDataRateHi ? ISO15693_SIGNAL_COEFF_HI : + ISO15693_SIGNAL_COEFF_LO; + DigitalSignal** bank = instance->banks[data_rate]; + + bank[Iso15693SignalIndexSof] = digital_signal_alloc(ISO15693_SIGNAL_SOF_EDGES * k); + bank[Iso15693SignalIndexEof] = digital_signal_alloc(ISO15693_SIGNAL_EOF_EDGES * k); + bank[Iso15693SignalIndexOne] = digital_signal_alloc(ISO15693_SIGNAL_ONE_EDGES * k); + bank[Iso15693SignalIndexZero] = digital_signal_alloc(ISO15693_SIGNAL_ZERO_EDGES * k); + + iso15693_add_sof(bank[Iso15693SignalIndexSof], data_rate); + iso15693_add_eof(bank[Iso15693SignalIndexEof], data_rate); + iso15693_add_bit(bank[Iso15693SignalIndexOne], data_rate, true); + iso15693_add_bit(bank[Iso15693SignalIndexZero], data_rate, false); +} + +static void + iso15693_signal_bank_clear(Iso15693Signal* instance, Iso15693SignalDataRate data_rate) { + DigitalSignal** bank = instance->banks[data_rate]; + + for(uint32_t i = 0; i < Iso15693SignalIndexNum; ++i) { + digital_signal_free(bank[i]); + } +} + +static void + iso15693_signal_bank_register(Iso15693Signal* instance, Iso15693SignalDataRate data_rate) { + for(uint32_t i = 0; i < Iso15693SignalIndexNum; ++i) { + digital_sequence_register_signal( + instance->tx_sequence, + iso15693_get_sequence_index(i, data_rate), + instance->banks[data_rate][i]); + } +} + +Iso15693Signal* iso15693_signal_alloc(const GpioPin* pin) { + furi_assert(pin); + + Iso15693Signal* instance = malloc(sizeof(Iso15693Signal)); + + instance->tx_sequence = digital_sequence_alloc(BITS_IN_BYTE * 255 + 2, pin); + + for(uint32_t i = 0; i < Iso15693SignalDataRateNum; ++i) { + iso15693_signal_bank_fill(instance, i); + iso15693_signal_bank_register(instance, i); + } + + return instance; +} + +void iso15693_signal_free(Iso15693Signal* instance) { + furi_assert(instance); + + digital_sequence_free(instance->tx_sequence); + + for(uint32_t i = 0; i < Iso15693SignalDataRateNum; ++i) { + iso15693_signal_bank_clear(instance, i); + } + + free(instance); +} + +void iso15693_signal_tx( + Iso15693Signal* instance, + Iso15693SignalDataRate data_rate, + const uint8_t* tx_data, + size_t tx_data_size) { + furi_assert(instance); + furi_assert(data_rate < Iso15693SignalDataRateNum); + furi_assert(tx_data); + + FURI_CRITICAL_ENTER(); + digital_sequence_clear(instance->tx_sequence); + iso15693_signal_encode(instance, data_rate, tx_data, tx_data_size); + digital_sequence_transmit(instance->tx_sequence); + + FURI_CRITICAL_EXIT(); +} + +void iso15693_signal_tx_sof(Iso15693Signal* instance, Iso15693SignalDataRate data_rate) { + furi_assert(instance); + furi_assert(data_rate < Iso15693SignalDataRateNum); + + FURI_CRITICAL_ENTER(); + digital_sequence_clear(instance->tx_sequence); + digital_sequence_add_signal( + instance->tx_sequence, iso15693_get_sequence_index(Iso15693SignalIndexSof, data_rate)); + digital_sequence_transmit(instance->tx_sequence); + + FURI_CRITICAL_EXIT(); +} diff --git a/lib/digital_signal/presets/nfc/iso15693_signal.h b/lib/digital_signal/presets/nfc/iso15693_signal.h new file mode 100644 index 000000000..8219cff15 --- /dev/null +++ b/lib/digital_signal/presets/nfc/iso15693_signal.h @@ -0,0 +1,73 @@ +/** + * @file iso15693_signal.h + * @brief DigitalSequence preset for generating ISO15693-compliant signals. + * + */ +#pragma once + +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso15693Signal Iso15693Signal; + +/** + * @brief Supported data rates. + */ +typedef enum { + Iso15693SignalDataRateHi, /**< High data rate. */ + Iso15693SignalDataRateLo, /**< Low data rate. */ + Iso15693SignalDataRateNum, /**< Data rate mode count. Internal use. */ +} Iso15693SignalDataRate; + +/** + * @brief Allocate an Iso15693Signal instance with a set GPIO pin. + * + * @param[in] pin GPIO pin to use during transmission. + * @returns pointer to the allocated instance. + */ +Iso15693Signal* iso15693_signal_alloc(const GpioPin* pin); + +/** + * @brief Delete an Iso15693Signal instance. + * + * @param[in,out] instance pointer to the instance to be deleted. + */ +void iso15693_signal_free(Iso15693Signal* instance); + +/** + * @brief Transmit arbitrary bytes using an Iso15693Signal instance. + * @see Iso15693SignalDataRate + * + * This function will block until the transmisson has been completed. + * + * @param[in] instance pointer to the instance used in transmission. + * @param[in] data_rate data rate to transmit at. + * @param[in] tx_data pointer to the data to be transmitted. + * @param[in] tx_data_size size of the data to be transmitted in bytes. + */ +void iso15693_signal_tx( + Iso15693Signal* instance, + Iso15693SignalDataRate data_rate, + const uint8_t* tx_data, + size_t tx_data_size); + +/** + * @brief Transmit Start of Frame using an Iso15693Signal instance. + * @see Iso15693SignalDataRate + * + * This function will block until the transmisson has been completed. + * + * @param[in] instance pointer to the instance used in transmission. + * @param[in] data_rate data rate to transmit at. + */ +void iso15693_signal_tx_sof(Iso15693Signal* instance, Iso15693SignalDataRate data_rate); + +#ifdef __cplusplus +} +#endif diff --git a/lib/drivers/st25r3916.c b/lib/drivers/st25r3916.c new file mode 100644 index 000000000..477261213 --- /dev/null +++ b/lib/drivers/st25r3916.c @@ -0,0 +1,81 @@ +#include "st25r3916.h" + +#include + +void st25r3916_mask_irq(FuriHalSpiBusHandle* handle, uint32_t mask) { + furi_assert(handle); + + uint8_t irq_mask_regs[4] = { + mask & 0xff, + (mask >> 8) & 0xff, + (mask >> 16) & 0xff, + (mask >> 24) & 0xff, + }; + st25r3916_write_burst_regs(handle, ST25R3916_REG_IRQ_MASK_MAIN, irq_mask_regs, 4); +} + +uint32_t st25r3916_get_irq(FuriHalSpiBusHandle* handle) { + furi_assert(handle); + + uint8_t irq_regs[4] = {}; + uint32_t irq = 0; + st25r3916_read_burst_regs(handle, ST25R3916_REG_IRQ_MASK_MAIN, irq_regs, 4); + // FURI_LOG_I( + // "Mask Irq", "%02X %02X %02X %02X", irq_regs[0], irq_regs[1], irq_regs[2], irq_regs[3]); + st25r3916_read_burst_regs(handle, ST25R3916_REG_IRQ_MAIN, irq_regs, 4); + irq = (uint32_t)irq_regs[0]; + irq |= (uint32_t)irq_regs[1] << 8; + irq |= (uint32_t)irq_regs[2] << 16; + irq |= (uint32_t)irq_regs[3] << 24; + // FURI_LOG_I("iRQ", "%02X %02X %02X %02X", irq_regs[0], irq_regs[1], irq_regs[2], irq_regs[3]); + + return irq; +} + +void st25r3916_write_fifo(FuriHalSpiBusHandle* handle, const uint8_t* buff, size_t bits) { + furi_assert(handle); + furi_assert(buff); + + size_t bytes = (bits + 7) / 8; + + st25r3916_write_reg(handle, ST25R3916_REG_NUM_TX_BYTES2, (uint8_t)(bits & 0xFFU)); + st25r3916_write_reg(handle, ST25R3916_REG_NUM_TX_BYTES1, (uint8_t)((bits >> 8) & 0xFFU)); + + st25r3916_reg_write_fifo(handle, buff, bytes); +} + +bool st25r3916_read_fifo( + FuriHalSpiBusHandle* handle, + uint8_t* buff, + size_t buff_size, + size_t* buff_bits) { + furi_assert(handle); + furi_assert(buff); + + bool read_success = false; + + do { + uint8_t fifo_status[2] = {}; + st25r3916_read_burst_regs(handle, ST25R3916_REG_FIFO_STATUS1, fifo_status, 2); + size_t bytes = ((fifo_status[1] & ST25R3916_REG_FIFO_STATUS2_fifo_b_mask) >> + ST25R3916_REG_FIFO_STATUS2_fifo_b_shift) | + fifo_status[0]; + uint8_t bits = + ((fifo_status[1] & ST25R3916_REG_FIFO_STATUS2_fifo_lb_mask) >> + ST25R3916_REG_FIFO_STATUS2_fifo_lb_shift); + + if(bytes == 0) break; + if(bytes > buff_size) break; + + st25r3916_reg_read_fifo(handle, buff, bytes); + + if(bits) { + *buff_bits = (bytes - 1) * 8 + bits; + } else { + *buff_bits = bytes * 8; + } + read_success = true; + } while(false); + + return read_success; +} diff --git a/lib/drivers/st25r3916.h b/lib/drivers/st25r3916.h new file mode 100644 index 000000000..532239f47 --- /dev/null +++ b/lib/drivers/st25r3916.h @@ -0,0 +1,113 @@ +#pragma once + +#include "st25r3916_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ST25R3916_IRQ_MASK_ALL (uint32_t)(0xFFFFFFFFUL) /** All ST25R3916 interrupt sources */ +#define ST25R3916_IRQ_MASK_NONE (uint32_t)(0x00000000UL) /**No ST25R3916 interrupt source */ + +/** Main interrupt register */ +#define ST25R3916_IRQ_MASK_OSC (uint32_t)(0x00000080U) /** ST25R3916 oscillator stable interrupt */ +#define ST25R3916_IRQ_MASK_FWL (uint32_t)(0x00000040U) /** ST25R3916 FIFO water level interrupt */ +#define ST25R3916_IRQ_MASK_RXS (uint32_t)(0x00000020U) /** ST25R3916 start of receive interrupt */ +#define ST25R3916_IRQ_MASK_RXE (uint32_t)(0x00000010U) /** ST25R3916 end of receive interrupt */ +#define ST25R3916_IRQ_MASK_TXE \ + (uint32_t)(0x00000008U) /** ST25R3916 end of transmission interrupt */ +#define ST25R3916_IRQ_MASK_COL (uint32_t)(0x00000004U) /** ST25R3916 bit collision interrupt */ +#define ST25R3916_IRQ_MASK_RX_REST \ + (uint32_t)(0x00000002U) /** ST25R3916 automatic reception restart interrupt */ +#define ST25R3916_IRQ_MASK_RFU (uint32_t)(0x00000001U) /** ST25R3916 RFU interrupt */ + +/** Timer and NFC interrupt register */ +#define ST25R3916_IRQ_MASK_DCT \ + (uint32_t)(0x00008000U) /** ST25R3916 termination of direct command interrupt. */ +#define ST25R3916_IRQ_MASK_NRE \ + (uint32_t)(0x00004000U) /** ST25R3916 no-response timer expired interrupt */ +#define ST25R3916_IRQ_MASK_GPE \ + (uint32_t)(0x00002000U) /** ST25R3916 general purpose timer expired interrupt */ +#define ST25R3916_IRQ_MASK_EON (uint32_t)(0x00001000U) /** ST25R3916 external field on interrupt */ +#define ST25R3916_IRQ_MASK_EOF \ + (uint32_t)(0x00000800U) /** ST25R3916 external field off interrupt */ +#define ST25R3916_IRQ_MASK_CAC \ + (uint32_t)(0x00000400U) /** ST25R3916 collision during RF collision avoidance */ +#define ST25R3916_IRQ_MASK_CAT \ + (uint32_t)(0x00000200U) /** ST25R3916 minimum guard time expired interrupt */ +#define ST25R3916_IRQ_MASK_NFCT \ + (uint32_t)(0x00000100U) /** ST25R3916 initiator bit rate recognised interrupt */ + +/** Error and wake-up interrupt register */ +#define ST25R3916_IRQ_MASK_CRC (uint32_t)(0x00800000U) /** ST25R3916 CRC error interrupt */ +#define ST25R3916_IRQ_MASK_PAR (uint32_t)(0x00400000U) /** ST25R3916 parity error interrupt */ +#define ST25R3916_IRQ_MASK_ERR2 \ + (uint32_t)(0x00200000U) /** ST25R3916 soft framing error interrupt */ +#define ST25R3916_IRQ_MASK_ERR1 \ + (uint32_t)(0x00100000U) /** ST25R3916 hard framing error interrupt */ +#define ST25R3916_IRQ_MASK_WT (uint32_t)(0x00080000U) /** ST25R3916 wake-up interrupt */ +#define ST25R3916_IRQ_MASK_WAM \ + (uint32_t)(0x00040000U) /** ST25R3916 wake-up due to amplitude interrupt */ +#define ST25R3916_IRQ_MASK_WPH \ + (uint32_t)(0x00020000U) /** ST25R3916 wake-up due to phase interrupt */ +#define ST25R3916_IRQ_MASK_WCAP \ + (uint32_t)(0x00010000U) /** ST25R3916 wake-up due to capacitance measurement */ + +/** Passive Target Interrupt Register */ +#define ST25R3916_IRQ_MASK_PPON2 \ + (uint32_t)(0x80000000U) /** ST25R3916 PPON2 Field on waiting Timer interrupt */ +#define ST25R3916_IRQ_MASK_SL_WL \ + (uint32_t)(0x40000000U) /** ST25R3916 Passive target slot number water level interrupt */ +#define ST25R3916_IRQ_MASK_APON \ + (uint32_t)(0x20000000U) /** ST25R3916 Anticollision done and Field On interrupt */ +#define ST25R3916_IRQ_MASK_RXE_PTA \ + (uint32_t)(0x10000000U) /** ST25R3916 RXE with an automatic response interrupt */ +#define ST25R3916_IRQ_MASK_WU_F \ + (uint32_t)(0x08000000U) /** ST25R3916 212/424b/s Passive target interrupt: Active */ +#define ST25R3916_IRQ_MASK_RFU2 (uint32_t)(0x04000000U) /** ST25R3916 RFU2 interrupt */ +#define ST25R3916_IRQ_MASK_WU_A_X \ + (uint32_t)(0x02000000U) /** ST25R3916 106kb/s Passive target state interrupt: Active* */ +#define ST25R3916_IRQ_MASK_WU_A \ + (uint32_t)(0x01000000U) /** ST25R3916 106kb/s Passive target state interrupt: Active */ + +/** Mask st25r3916 interrupts + * + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param mask - mask of interrupts to be disabled + */ +void st25r3916_mask_irq(FuriHalSpiBusHandle* handle, uint32_t mask); + +/** Get st25r3916 interrupts + * + * @param handle - pointer to FuriHalSpiBusHandle instance + * + * @return received interrupts + */ +uint32_t st25r3916_get_irq(FuriHalSpiBusHandle* handle); + +/** Write FIFO + * + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param buff - buffer to write to FIFO + * @param bits - number of bits to write + */ +void st25r3916_write_fifo(FuriHalSpiBusHandle* handle, const uint8_t* buff, size_t bits); + +/** Read FIFO + * + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param buff - buffer to read from FIFO + * @param buff_size - buffer size n bytes + * @param buff_bits - pointer to number of bits read + * + * @return true if read success, false otherwise +*/ +bool st25r3916_read_fifo( + FuriHalSpiBusHandle* handle, + uint8_t* buff, + size_t buff_size, + size_t* buff_bits); + +#ifdef __cplusplus +} +#endif diff --git a/lib/drivers/st25r3916_reg.c b/lib/drivers/st25r3916_reg.c new file mode 100644 index 000000000..8ac467238 --- /dev/null +++ b/lib/drivers/st25r3916_reg.c @@ -0,0 +1,257 @@ +#include "st25r3916_reg.h" + +#include + +#define ST25R3916_WRITE_MODE \ + (0U << 6) /*!< ST25R3916 Operation Mode: Write */ +#define ST25R3916_READ_MODE \ + (1U << 6) /*!< ST25R3916 Operation Mode: Read */ +#define ST25R3916_CMD_MODE \ + (3U << 6) /*!< ST25R3916 Operation Mode: Direct Command */ +#define ST25R3916_FIFO_LOAD \ + (0x80U) /*!< ST25R3916 Operation Mode: FIFO Load */ +#define ST25R3916_FIFO_READ \ + (0x9FU) /*!< ST25R3916 Operation Mode: FIFO Read */ +#define ST25R3916_PT_A_CONFIG_LOAD \ + (0xA0U) /*!< ST25R3916 Operation Mode: Passive Target Memory A-Config Load */ +#define ST25R3916_PT_F_CONFIG_LOAD \ + (0xA8U) /*!< ST25R3916 Operation Mode: Passive Target Memory F-Config Load */ +#define ST25R3916_PT_TSN_DATA_LOAD \ + (0xACU) /*!< ST25R3916 Operation Mode: Passive Target Memory TSN Load */ +#define ST25R3916_PT_MEM_READ \ + (0xBFU) /*!< ST25R3916 Operation Mode: Passive Target Memory Read */ + +#define ST25R3916_CMD_LEN \ + (1U) /*!< ST25R3916 CMD length */ +#define ST25R3916_FIFO_DEPTH (512U) +#define ST25R3916_BUF_LEN \ + (ST25R3916_CMD_LEN + \ + ST25R3916_FIFO_DEPTH) /*!< ST25R3916 communication buffer: CMD + FIFO length */ + +static void st25r3916_reg_tx_byte(FuriHalSpiBusHandle* handle, uint8_t byte) { + uint8_t val = byte; + furi_hal_spi_bus_tx(handle, &val, 1, 5); +} + +void st25r3916_read_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t* val) { + furi_assert(handle); + st25r3916_read_burst_regs(handle, reg, val, 1); +} + +void st25r3916_read_burst_regs( + FuriHalSpiBusHandle* handle, + uint8_t reg_start, + uint8_t* values, + uint8_t length) { + furi_assert(handle); + furi_assert(values); + furi_assert(length); + + furi_hal_gpio_write(handle->cs, false); + + if(reg_start & ST25R3916_SPACE_B) { + // Send direct command first + st25r3916_reg_tx_byte(handle, ST25R3916_CMD_SPACE_B_ACCESS); + } + st25r3916_reg_tx_byte(handle, (reg_start & ~ST25R3916_SPACE_B) | ST25R3916_READ_MODE); + furi_hal_spi_bus_rx(handle, values, length, 5); + + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_write_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t val) { + furi_assert(handle); + uint8_t reg_val = val; + st25r3916_write_burst_regs(handle, reg, ®_val, 1); +} + +void st25r3916_write_burst_regs( + FuriHalSpiBusHandle* handle, + uint8_t reg_start, + const uint8_t* values, + uint8_t length) { + furi_assert(handle); + furi_assert(values); + furi_assert(length); + + furi_hal_gpio_write(handle->cs, false); + + if(reg_start & ST25R3916_SPACE_B) { + // Send direct command first + st25r3916_reg_tx_byte(handle, ST25R3916_CMD_SPACE_B_ACCESS); + } + st25r3916_reg_tx_byte(handle, (reg_start & ~ST25R3916_SPACE_B) | ST25R3916_WRITE_MODE); + furi_hal_spi_bus_tx(handle, values, length, 5); + + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_reg_write_fifo(FuriHalSpiBusHandle* handle, const uint8_t* buff, size_t length) { + furi_assert(handle); + furi_assert(buff); + furi_assert(length); + furi_assert(length <= ST25R3916_FIFO_DEPTH); + + furi_hal_gpio_write(handle->cs, false); + st25r3916_reg_tx_byte(handle, ST25R3916_FIFO_LOAD); + furi_hal_spi_bus_tx(handle, buff, length, 200); + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_reg_read_fifo(FuriHalSpiBusHandle* handle, uint8_t* buff, size_t length) { + furi_assert(handle); + furi_assert(buff); + furi_assert(length); + furi_assert(length <= ST25R3916_FIFO_DEPTH); + + furi_hal_gpio_write(handle->cs, false); + st25r3916_reg_tx_byte(handle, ST25R3916_FIFO_READ); + furi_hal_spi_bus_rx(handle, buff, length, 200); + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_write_pta_mem(FuriHalSpiBusHandle* handle, const uint8_t* values, size_t length) { + furi_assert(handle); + furi_assert(values); + furi_assert(length); + furi_assert(length <= ST25R3916_PTM_LEN); + + furi_hal_gpio_write(handle->cs, false); + st25r3916_reg_tx_byte(handle, ST25R3916_PT_A_CONFIG_LOAD); + furi_hal_spi_bus_tx(handle, values, length, 200); + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_read_pta_mem(FuriHalSpiBusHandle* handle, uint8_t* buff, size_t length) { + furi_assert(handle); + furi_assert(buff); + furi_assert(length); + furi_assert(length <= ST25R3916_PTM_LEN); + + uint8_t tmp_buff[ST25R3916_PTM_LEN + 1]; + furi_hal_gpio_write(handle->cs, false); + st25r3916_reg_tx_byte(handle, ST25R3916_PT_MEM_READ); + furi_hal_spi_bus_rx(handle, tmp_buff, length + 1, 200); + furi_hal_gpio_write(handle->cs, true); + memcpy(buff, tmp_buff + 1, length); +} + +void st25r3916_write_ptf_mem(FuriHalSpiBusHandle* handle, const uint8_t* values, size_t length) { + furi_assert(handle); + furi_assert(values); + + furi_hal_gpio_write(handle->cs, false); + st25r3916_reg_tx_byte(handle, ST25R3916_PT_F_CONFIG_LOAD); + furi_hal_spi_bus_tx(handle, values, length, 200); + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_write_pttsn_mem(FuriHalSpiBusHandle* handle, uint8_t* buff, size_t length) { + furi_assert(handle); + furi_assert(buff); + + furi_hal_gpio_write(handle->cs, false); + st25r3916_reg_tx_byte(handle, ST25R3916_PT_TSN_DATA_LOAD); + furi_hal_spi_bus_tx(handle, buff, length, 200); + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_direct_cmd(FuriHalSpiBusHandle* handle, uint8_t cmd) { + furi_assert(handle); + + furi_hal_gpio_write(handle->cs, false); + st25r3916_reg_tx_byte(handle, cmd | ST25R3916_CMD_MODE); + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_read_test_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t* val) { + furi_assert(handle); + + furi_hal_gpio_write(handle->cs, false); + st25r3916_reg_tx_byte(handle, ST25R3916_CMD_TEST_ACCESS); + st25r3916_reg_tx_byte(handle, reg | ST25R3916_READ_MODE); + furi_hal_spi_bus_rx(handle, val, 1, 5); + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_write_test_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t val) { + furi_assert(handle); + + furi_hal_gpio_write(handle->cs, false); + st25r3916_reg_tx_byte(handle, ST25R3916_CMD_TEST_ACCESS); + st25r3916_reg_tx_byte(handle, reg | ST25R3916_WRITE_MODE); + furi_hal_spi_bus_tx(handle, &val, 1, 5); + furi_hal_gpio_write(handle->cs, true); +} + +void st25r3916_clear_reg_bits(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t clr_mask) { + furi_assert(handle); + + uint8_t reg_val = 0; + st25r3916_read_reg(handle, reg, ®_val); + if((reg_val & ~clr_mask) != reg_val) { + reg_val &= ~clr_mask; + st25r3916_write_reg(handle, reg, reg_val); + } +} + +void st25r3916_set_reg_bits(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t set_mask) { + furi_assert(handle); + + uint8_t reg_val = 0; + st25r3916_read_reg(handle, reg, ®_val); + if((reg_val | set_mask) != reg_val) { + reg_val |= set_mask; + st25r3916_write_reg(handle, reg, reg_val); + } +} + +void st25r3916_change_reg_bits( + FuriHalSpiBusHandle* handle, + uint8_t reg, + uint8_t mask, + uint8_t value) { + furi_assert(handle); + + st25r3916_modify_reg(handle, reg, mask, (mask & value)); +} + +void st25r3916_modify_reg( + FuriHalSpiBusHandle* handle, + uint8_t reg, + uint8_t clr_mask, + uint8_t set_mask) { + furi_assert(handle); + + uint8_t reg_val = 0; + uint8_t new_val = 0; + st25r3916_read_reg(handle, reg, ®_val); + new_val = (reg_val & ~clr_mask) | set_mask; + if(new_val != reg_val) { + st25r3916_write_reg(handle, reg, new_val); + } +} + +void st25r3916_change_test_reg_bits( + FuriHalSpiBusHandle* handle, + uint8_t reg, + uint8_t mask, + uint8_t value) { + furi_assert(handle); + + uint8_t reg_val = 0; + uint8_t new_val = 0; + st25r3916_read_test_reg(handle, reg, ®_val); + new_val = (reg_val & ~mask) | (mask & value); + if(new_val != reg_val) { + st25r3916_write_test_reg(handle, reg, new_val); + } +} + +bool st25r3916_check_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t mask, uint8_t val) { + furi_assert(handle); + + uint8_t reg_val = 0; + st25r3916_read_reg(handle, reg, ®_val); + return ((reg_val & mask) == val); +} diff --git a/lib/ST25RFAL002/source/st25r3916/st25r3916_com.h b/lib/drivers/st25r3916_reg.h similarity index 62% rename from lib/ST25RFAL002/source/st25r3916/st25r3916_com.h rename to lib/drivers/st25r3916_reg.h index 6a47317e3..8a924fc39 100644 --- a/lib/ST25RFAL002/source/st25r3916/st25r3916_com.h +++ b/lib/drivers/st25r3916_reg.h @@ -1,262 +1,202 @@ +#pragma once -/****************************************************************************** - * \attention - * - *

© COPYRIGHT 2020 STMicroelectronics

- * - * Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (the "License"); - * You may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * www.st.com/myliberty - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. - * See the License for the specific language governing permissions and - * limitations under the License. - * -******************************************************************************/ +#include -/* - * PROJECT: ST25R3916 firmware - * Revision: - * LANGUAGE: ISO C99 - */ +#ifdef __cplusplus +extern "C" { +#endif -/*! \file - * - * \author Gustavo Patricio - * - * \brief ST25R3916 communication declaration file - * - * This driver provides basic abstraction for communication with the ST25R3916 - * - * - * \addtogroup RFAL - * @{ - * - * \addtogroup RFAL-HAL - * \brief RFAL Hardware Abstraction Layer - * @{ - * - * \addtogroup ST25R3916 - * \brief RFAL ST25R3916 Driver - * @{ - * - * \addtogroup ST25R3916_COM - * \brief RFAL ST25R3916 Communications - * @{ - * - */ +/** ST25R3916 direct commands */ +#define ST25R3916_CMD_SET_DEFAULT \ + 0xC1U /** Puts the chip in default state (same as after power-up */ +#define ST25R3916_CMD_STOP 0xC2U /*!< Stops all activities and clears FIFO */ +#define ST25R3916_CMD_TRANSMIT_WITH_CRC 0xC4U /** Transmit with CRC */ +#define ST25R3916_CMD_TRANSMIT_WITHOUT_CRC 0xC5U /** Transmit without CRC */ +#define ST25R3916_CMD_TRANSMIT_REQA 0xC6U /** Transmit REQA */ +#define ST25R3916_CMD_TRANSMIT_WUPA 0xC7U /** Transmit WUPA */ +#define ST25R3916_CMD_INITIAL_RF_COLLISION \ + 0xC8U /** NFC transmit with Initial RF Collision Avoidance */ +#define ST25R3916_CMD_RESPONSE_RF_COLLISION_N \ + 0xC9U /** NFC transmit with Response RF Collision Avoidance */ +#define ST25R3916_CMD_GOTO_SENSE 0xCDU /** Passive target logic to Sense/Idle state */ +#define ST25R3916_CMD_GOTO_SLEEP 0xCEU /** Passive target logic to Sleep/Halt state */ +#define ST25R3916_CMD_MASK_RECEIVE_DATA 0xD0U /** Mask receive data */ +#define ST25R3916_CMD_UNMASK_RECEIVE_DATA 0xD1U /** Unmask receive data */ +#define ST25R3916_CMD_AM_MOD_STATE_CHANGE 0xD2U /** AM Modulation state change */ +#define ST25R3916_CMD_MEASURE_AMPLITUDE 0xD3U /** Measure singal amplitude on RFI inputs */ +#define ST25R3916_CMD_RESET_RXGAIN 0xD5U /** Reset RX Gain */ +#define ST25R3916_CMD_ADJUST_REGULATORS 0xD6U /** Adjust regulators */ +#define ST25R3916_CMD_CALIBRATE_DRIVER_TIMING \ + 0xD8U /** Starts the sequence to adjust the driver timing */ +#define ST25R3916_CMD_MEASURE_PHASE 0xD9U /** Measure phase between RFO and RFI signal */ +#define ST25R3916_CMD_CLEAR_RSSI 0xDAU /** Clear RSSI bits and restart the measurement */ +#define ST25R3916_CMD_CLEAR_FIFO 0xDBU /** Clears FIFO, Collision and IRQ status */ +#define ST25R3916_CMD_TRANSPARENT_MODE 0xDCU /** Transparent mode */ +#define ST25R3916_CMD_CALIBRATE_C_SENSOR 0xDDU /** Calibrate the capacitive sensor */ +#define ST25R3916_CMD_MEASURE_CAPACITANCE 0xDEU /** Measure capacitance */ +#define ST25R3916_CMD_MEASURE_VDD 0xDFU /** Measure power supply voltage */ +#define ST25R3916_CMD_START_GP_TIMER 0xE0U /** Start the general purpose timer */ +#define ST25R3916_CMD_START_WUP_TIMER 0xE1U /** Start the wake-up timer */ +#define ST25R3916_CMD_START_MASK_RECEIVE_TIMER 0xE2U /** Start the mask-receive timer */ +#define ST25R3916_CMD_START_NO_RESPONSE_TIMER 0xE3U /** Start the no-response timer */ +#define ST25R3916_CMD_START_PPON2_TIMER 0xE4U /** Start PPon2 timer */ +#define ST25R3916_CMD_STOP_NRT 0xE8U /** Stop No Response Timer */ +#define ST25R3916_CMD_SPACE_B_ACCESS 0xFBU /** Enable R/W access to the test registers */ +#define ST25R3916_CMD_TEST_ACCESS 0xFCU /** Enable R/W access to the test registers */ -#ifndef ST25R3916_COM_H -#define ST25R3916_COM_H +#define ST25R3916_SPACE_B 0x40U /** ST25R3916 Space-B indicator */ +#define ST25R3916_SPACE_B_REG_LEN 16U /** Number of register in the space B */ -/* -****************************************************************************** -* INCLUDES -****************************************************************************** -*/ -#include "platform.h" -#include "st_errno.h" +#define ST25R3916_FIFO_STATUS_LEN 2 /** Number of FIFO Status Register */ -/* -****************************************************************************** -* GLOBAL DEFINES -****************************************************************************** -*/ -#define ST25R3916_SPACE_B 0x40U /*!< ST25R3916 Space-B indicator */ -#define ST25R3916_SPACE_B_REG_LEN 16U /*!< Number of register in the space B */ +#define ST25R3916_PTM_A_LEN 15U /** Passive target memory A config length */ +#define ST25R3916_PTM_B_LEN 0U /** Passive target memory B config length */ +#define ST25R3916_PTM_F_LEN 21U /** Passive target memory F config length */ +#define ST25R3916_PTM_TSN_LEN 12U /** Passive target memory TSN data length */ -#define ST25R3916_FIFO_STATUS_LEN 2 /*!< Number of FIFO Status Register */ - -#define ST25R3916_PTM_A_LEN 15U /*!< Passive target memory A config length */ -#define ST25R3916_PTM_B_LEN 0U /*!< Passive target memory B config length */ -#define ST25R3916_PTM_F_LEN 21U /*!< Passive target memory F config length */ -#define ST25R3916_PTM_TSN_LEN 12U /*!< Passive target memory TSN data length */ - -/*! Full Passive target memory length */ +/** Full Passive target memory length */ #define ST25R3916_PTM_LEN \ (ST25R3916_PTM_A_LEN + ST25R3916_PTM_B_LEN + ST25R3916_PTM_F_LEN + ST25R3916_PTM_TSN_LEN) -/* IO configuration registers */ -#define ST25R3916_REG_IO_CONF1 0x00U /*!< RW IO Configuration Register 1 */ -#define ST25R3916_REG_IO_CONF2 0x01U /*!< RW IO Configuration Register 2 */ +/** IO configuration registers */ +#define ST25R3916_REG_IO_CONF1 0x00U /** RW IO Configuration Register 1 */ +#define ST25R3916_REG_IO_CONF2 0x01U /** RW IO Configuration Register 2 */ -/* Operation control and mode definition registers */ -#define ST25R3916_REG_OP_CONTROL 0x02U /*!< RW Operation Control Register */ -#define ST25R3916_REG_MODE 0x03U /*!< RW Mode Definition Register */ -#define ST25R3916_REG_BIT_RATE 0x04U /*!< RW Bit Rate Definition Register */ +/** Operation control and mode definition */ +#define ST25R3916_REG_OP_CONTROL 0x02U /** RW Operation Control Register */ +#define ST25R3916_REG_MODE 0x03U /** RW Mode Definition Register */ +#define ST25R3916_REG_BIT_RATE 0x04U /** RW Bit Rate Definition Register */ -/* Protocol Configuration registers */ -#define ST25R3916_REG_ISO14443A_NFC \ - 0x05U /*!< RW ISO14443A and NFC 106 kBit/s Settings Register */ +/** Protocol Configuration registers */ +#define ST25R3916_REG_ISO14443A_NFC 0x05U /** RW ISO14443A and NFC 106 kBit/s Settings Register */ #define ST25R3916_REG_EMD_SUP_CONF \ - (ST25R3916_SPACE_B | 0x05U) /*!< RW EMD Suppression Configuration Register */ -#define ST25R3916_REG_ISO14443B_1 \ - 0x06U /*!< RW ISO14443B Settings Register 1 */ + (ST25R3916_SPACE_B | 0x05U) /*!< RW EMD Suppression Configuration Register */ +#define ST25R3916_REG_ISO14443B_1 0x06U /** RW ISO14443B Settings Register 1 */ #define ST25R3916_REG_SUBC_START_TIME \ - (ST25R3916_SPACE_B | 0x06U) /*!< RW Subcarrier Start Time Register */ -#define ST25R3916_REG_ISO14443B_2 \ - 0x07U /*!< RW ISO14443B Settings Register 2 */ -#define ST25R3916_REG_PASSIVE_TARGET \ - 0x08U /*!< RW Passive Target Definition Register */ -#define ST25R3916_REG_STREAM_MODE \ - 0x09U /*!< RW Stream Mode Definition Register */ -#define ST25R3916_REG_AUX 0x0AU /*!< RW Auxiliary Definition Register */ + (ST25R3916_SPACE_B | 0x06U) /*!< RW Subcarrier Start Time Register */ +#define ST25R3916_REG_ISO14443B_2 0x07U /** RW ISO14443B Settings Register 2 */ +#define ST25R3916_REG_PASSIVE_TARGET 0x08U /** RW Passive Target Definition Register */ +#define ST25R3916_REG_STREAM_MODE 0x09U /** RW Stream Mode Definition Register */ +#define ST25R3916_REG_AUX 0x0AU /** RW Auxiliary Definition Register */ -/* Receiver Configuration registers */ -#define ST25R3916_REG_RX_CONF1 0x0BU /*!< RW Receiver Configuration Register 1 */ -#define ST25R3916_REG_RX_CONF2 0x0CU /*!< RW Receiver Configuration Register 2 */ -#define ST25R3916_REG_RX_CONF3 0x0DU /*!< RW Receiver Configuration Register 3 */ -#define ST25R3916_REG_RX_CONF4 0x0EU /*!< RW Receiver Configuration Register 4 */ +/** Receiver Configuration registers */ +#define ST25R3916_REG_RX_CONF1 0x0BU /** RW Receiver Configuration Register 1 */ +#define ST25R3916_REG_RX_CONF2 0x0CU /** RW Receiver Configuration Register 2 */ +#define ST25R3916_REG_RX_CONF3 0x0DU /** RW Receiver Configuration Register 3 */ +#define ST25R3916_REG_RX_CONF4 0x0EU /** RW Receiver Configuration Register 4 */ #define ST25R3916_REG_P2P_RX_CONF \ - (ST25R3916_SPACE_B | 0x0BU) /*!< RW P2P Receiver Configuration Register 1 */ + (ST25R3916_SPACE_B | 0x0BU) /** RW P2P Receiver Configuration Register 1 */ #define ST25R3916_REG_CORR_CONF1 \ - (ST25R3916_SPACE_B | 0x0CU) /*!< RW Correlator configuration register 1 */ + (ST25R3916_SPACE_B | 0x0CU) /** RW Correlator configuration register 1 */ #define ST25R3916_REG_CORR_CONF2 \ - (ST25R3916_SPACE_B | 0x0DU) /*!< RW Correlator configuration register 2 */ + (ST25R3916_SPACE_B | 0x0DU) /** RW Correlator configuration register 2 */ -/* Timer definition registers */ -#define ST25R3916_REG_MASK_RX_TIMER \ - 0x0FU /*!< RW Mask Receive Timer Register */ -#define ST25R3916_REG_NO_RESPONSE_TIMER1 \ - 0x10U /*!< RW No-response Timer Register 1 */ -#define ST25R3916_REG_NO_RESPONSE_TIMER2 \ - 0x11U /*!< RW No-response Timer Register 2 */ -#define ST25R3916_REG_TIMER_EMV_CONTROL \ - 0x12U /*!< RW Timer and EMV Control */ -#define ST25R3916_REG_GPT1 0x13U /*!< RW General Purpose Timer Register 1 */ -#define ST25R3916_REG_GPT2 0x14U /*!< RW General Purpose Timer Register 2 */ -#define ST25R3916_REG_PPON2 0x15U /*!< RW PPON2 Field waiting Timer Register */ -#define ST25R3916_REG_SQUELCH_TIMER \ - (ST25R3916_SPACE_B | 0x0FU) /*!< RW Squelch timeout Register */ -#define ST25R3916_REG_FIELD_ON_GT \ - (ST25R3916_SPACE_B | 0x15U) /*!< RW NFC Field on guard time */ +/** Timer definition registers */ +#define ST25R3916_REG_MASK_RX_TIMER 0x0FU /** RW Mask Receive Timer Register */ +#define ST25R3916_REG_NO_RESPONSE_TIMER1 0x10U /** RW No-response Timer Register 1 */ +#define ST25R3916_REG_NO_RESPONSE_TIMER2 0x11U /** RW No-response Timer Register 2 */ +#define ST25R3916_REG_TIMER_EMV_CONTROL 0x12U /** RW Timer and EMV Control */ +#define ST25R3916_REG_GPT1 0x13U /** RW General Purpose Timer Register 1 */ +#define ST25R3916_REG_GPT2 0x14U /** RW General Purpose Timer Register 2 */ +#define ST25R3916_REG_PPON2 0x15U /** RW PPON2 Field waiting Timer Register */ +#define ST25R3916_REG_SQUELCH_TIMER (ST25R3916_SPACE_B | 0x0FU) /** RW Squelch timeout Register */ +#define ST25R3916_REG_FIELD_ON_GT (ST25R3916_SPACE_B | 0x15U) /** RW NFC Field on guard time */ -/* Interrupt and associated reporting registers */ -#define ST25R3916_REG_IRQ_MASK_MAIN \ - 0x16U /*!< RW Mask Main Interrupt Register */ -#define ST25R3916_REG_IRQ_MASK_TIMER_NFC \ - 0x17U /*!< RW Mask Timer and NFC Interrupt Register */ -#define ST25R3916_REG_IRQ_MASK_ERROR_WUP \ - 0x18U /*!< RW Mask Error and Wake-up Interrupt Register */ -#define ST25R3916_REG_IRQ_MASK_TARGET \ - 0x19U /*!< RW Mask 3916 Target Interrupt Register */ -#define ST25R3916_REG_IRQ_MAIN 0x1AU /*!< R Main Interrupt Register */ -#define ST25R3916_REG_IRQ_TIMER_NFC \ - 0x1BU /*!< R Timer and NFC Interrupt Register */ -#define ST25R3916_REG_IRQ_ERROR_WUP \ - 0x1CU /*!< R Error and Wake-up Interrupt Register */ -#define ST25R3916_REG_IRQ_TARGET 0x1DU /*!< R ST25R3916 Target Interrupt Register */ -#define ST25R3916_REG_FIFO_STATUS1 \ - 0x1EU /*!< R FIFO Status Register 1 */ -#define ST25R3916_REG_FIFO_STATUS2 \ - 0x1FU /*!< R FIFO Status Register 2 */ -#define ST25R3916_REG_COLLISION_STATUS \ - 0x20U /*!< R Collision Display Register */ -#define ST25R3916_REG_PASSIVE_TARGET_STATUS \ - 0x21U /*!< R Passive target state status */ +/** Interrupt and associated reporting registers */ +#define ST25R3916_REG_IRQ_MASK_MAIN 0x16U /** RW Mask Main Interrupt Register */ +#define ST25R3916_REG_IRQ_MASK_TIMER_NFC 0x17U /** RW Mask Timer and NFC Interrupt Register */ +#define ST25R3916_REG_IRQ_MASK_ERROR_WUP 0x18U /** RW Mask Error and Wake-up Interrupt Register */ +#define ST25R3916_REG_IRQ_MASK_TARGET 0x19U /** RW Mask 3916 Target Interrupt Register */ +#define ST25R3916_REG_IRQ_MAIN 0x1AU /** R Main Interrupt Register */ +#define ST25R3916_REG_IRQ_TIMER_NFC 0x1BU /** R Timer and NFC Interrupt Register */ +#define ST25R3916_REG_IRQ_ERROR_WUP 0x1CU /** R Error and Wake-up Interrupt Register */ +#define ST25R3916_REG_IRQ_TARGET 0x1DU /*!< R ST25R3916 Target Interrupt Register */ +#define ST25R3916_REG_FIFO_STATUS1 0x1EU /** R FIFO Status Register 1 */ +#define ST25R3916_REG_FIFO_STATUS2 0x1FU /** R FIFO Status Register 2 */ +#define ST25R3916_REG_COLLISION_STATUS 0x20U /** R Collision Display Register */ +#define ST25R3916_REG_PASSIVE_TARGET_STATUS 0x21U /** R Passive target state status */ -/* Definition of number of transmitted bytes */ -#define ST25R3916_REG_NUM_TX_BYTES1 \ - 0x22U /*!< RW Number of Transmitted Bytes Register 1 */ -#define ST25R3916_REG_NUM_TX_BYTES2 \ - 0x23U /*!< RW Number of Transmitted Bytes Register 2 */ +/** Definition of number of transmitted bytes */ +#define ST25R3916_REG_NUM_TX_BYTES1 0x22U /** RW Number of Transmitted Bytes Register 1 */ +#define ST25R3916_REG_NUM_TX_BYTES2 0x23U /** RW Number of Transmitted Bytes Register 2 */ -/* NFCIP Bit Rate Display Register */ -#define ST25R3916_REG_NFCIP1_BIT_RATE \ - 0x24U /*!< R NFCIP Bit Rate Detection Display Register */ +/** NFCIP Bit Rate Display Register */ +#define ST25R3916_REG_NFCIP1_BIT_RATE 0x24U /** R NFCIP Bit Rate Detection Display Register */ -/* A/D Converter Output Register */ -#define ST25R3916_REG_AD_RESULT 0x25U /*!< R A/D Converter Output Register */ +/** A/D Converter Output Register */ +#define ST25R3916_REG_AD_RESULT 0x25U /** R A/D Converter Output Register */ -/* Antenna tuning registers */ -#define ST25R3916_REG_ANT_TUNE_A 0x26U /*!< RW Antenna Tuning Control (AAT-A) Register 1 */ -#define ST25R3916_REG_ANT_TUNE_B 0x27U /*!< RW Antenna Tuning Control (AAT-B) Register 2 */ +/** Antenna tuning registers */ +#define ST25R3916_REG_ANT_TUNE_A 0x26U /** RW Antenna Tuning Control (AAT-A) Register 1 */ +#define ST25R3916_REG_ANT_TUNE_B 0x27U /** RW Antenna Tuning Control (AAT-B) Register 2 */ -/* Antenna Driver and Modulation registers */ -#define ST25R3916_REG_TX_DRIVER 0x28U /*!< RW TX driver register */ -#define ST25R3916_REG_PT_MOD 0x29U /*!< RW PT modulation Register */ -#define ST25R3916_REG_AUX_MOD \ - (ST25R3916_SPACE_B | 0x28U) /*!< RW Aux Modulation setting Register */ +/** Antenna Driver and Modulation registers */ +#define ST25R3916_REG_TX_DRIVER 0x28U /** RW TX driver register */ +#define ST25R3916_REG_PT_MOD 0x29U /** RW PT modulation Register */ +#define ST25R3916_REG_AUX_MOD (ST25R3916_SPACE_B | 0x28U) /** RW Aux Modulation setting Register */ #define ST25R3916_REG_TX_DRIVER_TIMING \ - (ST25R3916_SPACE_B | 0x29U) /*!< RW TX driver timing Register */ + (ST25R3916_SPACE_B | 0x29U) /** RW TX driver timing Register */ #define ST25R3916_REG_RES_AM_MOD \ - (ST25R3916_SPACE_B | 0x2AU) /*!< RW Resistive AM modulation register */ + (ST25R3916_SPACE_B | 0x2AU) /** RW Resistive AM modulation register */ #define ST25R3916_REG_TX_DRIVER_STATUS \ - (ST25R3916_SPACE_B | 0x2BU) /*!< R TX driver timing readout Register */ + (ST25R3916_SPACE_B | 0x2BU) /** R TX driver timing readout Register */ -/* External Field Detector Threshold Registers */ +/** External Field Detector Threshold Registers */ #define ST25R3916_REG_FIELD_THRESHOLD_ACTV \ - 0x2AU /*!< RW External Field Detector Activation Threshold Reg */ + 0x2AU /** RW External Field Detector Activation Threshold Reg */ #define ST25R3916_REG_FIELD_THRESHOLD_DEACTV \ - 0x2BU /*!< RW External Field Detector Deactivation Threshold Reg*/ + 0x2BU /** RW External Field Detector Deactivation Threshold Reg */ -/* Regulator registers */ -#define ST25R3916_REG_REGULATOR_CONTROL \ - 0x2CU /*!< RW Regulated Voltage Control Register */ +/** Regulator registers */ +#define ST25R3916_REG_REGULATOR_CONTROL 0x2CU /** RW Regulated Voltage Control Register */ #define ST25R3916_REG_REGULATOR_RESULT \ - (ST25R3916_SPACE_B | 0x2CU) /*!< R Regulator Display Register */ + (ST25R3916_SPACE_B | 0x2CU) /** R Regulator Display Register */ -/* Receiver State Display Register */ -#define ST25R3916_REG_RSSI_RESULT \ - 0x2DU /*!< R RSSI Display Register */ -#define ST25R3916_REG_GAIN_RED_STATE \ - 0x2EU /*!< R Gain Reduction State Register */ -#define ST25R3916_REG_CAP_SENSOR_CONTROL \ - 0x2FU /*!< RW Capacitive Sensor Control Register */ -#define ST25R3916_REG_CAP_SENSOR_RESULT \ - 0x30U /*!< R Capacitive Sensor Display Register */ -#define ST25R3916_REG_AUX_DISPLAY \ - 0x31U /*!< R Auxiliary Display Register */ +/** Receiver State Display Register */ +#define ST25R3916_REG_RSSI_RESULT 0x2DU /** R RSSI Display Register */ +#define ST25R3916_REG_GAIN_RED_STATE 0x2EU /** R Gain Reduction State Register */ +#define ST25R3916_REG_CAP_SENSOR_CONTROL 0x2FU /** RW Capacitive Sensor Control Register */ +#define ST25R3916_REG_CAP_SENSOR_RESULT 0x30U /** R Capacitive Sensor Display Register */ +#define ST25R3916_REG_AUX_DISPLAY 0x31U /** R Auxiliary Display Register */ -/* Over/Undershoot Protection Configuration Registers */ +/** Over/Undershoot Protection Configuration Registers */ #define ST25R3916_REG_OVERSHOOT_CONF1 \ - (ST25R3916_SPACE_B | 0x30U) /*!< RW Overshoot Protection Configuration Register 1 */ + (ST25R3916_SPACE_B | 0x30U) /** RW Overshoot Protection Configuration Register 1 */ #define ST25R3916_REG_OVERSHOOT_CONF2 \ - (ST25R3916_SPACE_B | 0x31U) /*!< RW Overshoot Protection Configuration Register 2 */ + (ST25R3916_SPACE_B | 0x31U) /** RW Overshoot Protection Configuration Register 2 */ #define ST25R3916_REG_UNDERSHOOT_CONF1 \ - (ST25R3916_SPACE_B | 0x32U) /*!< RW Undershoot Protection Configuration Register 1 */ + (ST25R3916_SPACE_B | 0x32U) /** RW Undershoot Protection Configuration Register 1 */ #define ST25R3916_REG_UNDERSHOOT_CONF2 \ - (ST25R3916_SPACE_B | 0x33U) /*!< RW Undershoot Protection Configuration Register 2 */ + (ST25R3916_SPACE_B | 0x33U) /** RW Undershoot Protection Configuration Register 2 */ -/* Detection of card presence */ -#define ST25R3916_REG_WUP_TIMER_CONTROL \ - 0x32U /*!< RW Wake-up Timer Control Register */ +/** Detection of card presence */ +#define ST25R3916_REG_WUP_TIMER_CONTROL 0x32U /** RW Wake-up Timer Control Register */ #define ST25R3916_REG_AMPLITUDE_MEASURE_CONF \ - 0x33U /*!< RW Amplitude Measurement Configuration Register */ + 0x33U /** RW Amplitude Measurement Configuration Register */ #define ST25R3916_REG_AMPLITUDE_MEASURE_REF \ - 0x34U /*!< RW Amplitude Measurement Reference Register */ + 0x34U /** RW Amplitude Measurement Reference Register */ #define ST25R3916_REG_AMPLITUDE_MEASURE_AA_RESULT \ - 0x35U /*!< R Amplitude Measurement Auto Averaging Display Reg */ + 0x35U /** R Amplitude Measurement Auto Averaging Display Reg */ #define ST25R3916_REG_AMPLITUDE_MEASURE_RESULT \ - 0x36U /*!< R Amplitude Measurement Display Register */ -#define ST25R3916_REG_PHASE_MEASURE_CONF \ - 0x37U /*!< RW Phase Measurement Configuration Register */ -#define ST25R3916_REG_PHASE_MEASURE_REF \ - 0x38U /*!< RW Phase Measurement Reference Register */ + 0x36U /** R Amplitude Measurement Display Register */ +#define ST25R3916_REG_PHASE_MEASURE_CONF 0x37U /** RW Phase Measurement Configuration Register */ +#define ST25R3916_REG_PHASE_MEASURE_REF 0x38U /** RW Phase Measurement Reference Register */ #define ST25R3916_REG_PHASE_MEASURE_AA_RESULT \ - 0x39U /*!< R Phase Measurement Auto Averaging Display Register */ -#define ST25R3916_REG_PHASE_MEASURE_RESULT \ - 0x3AU /*!< R Phase Measurement Display Register */ + 0x39U /** R Phase Measurement Auto Averaging Display */ +#define ST25R3916_REG_PHASE_MEASURE_RESULT 0x3AU /** R Phase Measurement Display Register */ #define ST25R3916_REG_CAPACITANCE_MEASURE_CONF \ - 0x3BU /*!< RW Capacitance Measurement Configuration Register */ + 0x3BU /** RW Capacitance Measurement Configuration Register */ #define ST25R3916_REG_CAPACITANCE_MEASURE_REF \ - 0x3CU /*!< RW Capacitance Measurement Reference Register */ + 0x3CU /** RW Capacitance Measurement Reference Register */ #define ST25R3916_REG_CAPACITANCE_MEASURE_AA_RESULT \ - 0x3DU /*!< R Capacitance Measurement Auto Averaging Display Reg*/ + 0x3DU /** R Capacitance Measurement Auto Averaging Display Reg */ #define ST25R3916_REG_CAPACITANCE_MEASURE_RESULT \ - 0x3EU /*!< R Capacitance Measurement Display Register */ + 0x3EU /** R Capacitance Measurement Display Register */ -/* IC identity */ -#define ST25R3916_REG_IC_IDENTITY \ - 0x3FU /*!< R Chip Id: 0 for old silicon, v2 silicon: 0x09 */ +/** IC identity */ +#define ST25R3916_REG_IC_IDENTITY 0x3FU /** R Chip Id: 0 for old silicon, v2 silicon: 0x09 */ -/*! Register bit definitions \cond DOXYGEN_SUPRESS */ +/** Register bit definitions */ #define ST25R3916_REG_IO_CONF1_single (1U << 7) #define ST25R3916_REG_IO_CONF1_rfo2 (1U << 6) @@ -1021,364 +961,184 @@ #define ST25R3916_REG_IC_IDENTITY_ic_rev_mask (7U << 0) #define ST25R3916_REG_IC_IDENTITY_ic_rev_shift (0U) -/*! \endcond DOXYGEN_SUPRESS */ - -/* -****************************************************************************** -* GLOBAL FUNCTION PROTOTYPES -****************************************************************************** -*/ - -/*! - ***************************************************************************** - * \brief Returns the content of a register within the ST25R3916 +/** Read register * - * This function is used to read out the content of ST25R3916 registers. - * - * \param[in] reg: Address of register to read. - * \param[out] val: Returned value. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer t FuriHalSpiBusHandle instance + * @param reg - register address + * @param val - pointer to the variable to store the read value */ -ReturnCode st25r3916ReadRegister(uint8_t reg, uint8_t* val); +void st25r3916_read_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t* val); -/*! - ***************************************************************************** - * \brief Reads from multiple ST25R3916 registers +/** Read multiple registers * - * This function is used to read from multiple registers using the - * auto-increment feature. That is, after each read the address pointer - * inside the ST25R3916 gets incremented automatically. - * - * \param[in] reg: Address of the first register to read from. - * \param[in] values: pointer to a buffer where the result shall be written to. - * \param[in] length: Number of registers to be read out. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg_start - start register address + * @param values - pointer to the buffer to store the read values + * @param length - number of registers to read */ -ReturnCode st25r3916ReadMultipleRegisters(uint8_t reg, uint8_t* values, uint8_t length); +void st25r3916_read_burst_regs( + FuriHalSpiBusHandle* handle, + uint8_t reg_start, + uint8_t* values, + uint8_t length); -/*! - ***************************************************************************** - * \brief Writes a given value to a register within the ST25R3916 +/** Write register * - * This function is used to write \a val to address \a reg within the ST25R3916. - * - * \param[in] reg: Address of the register to write. - * \param[in] val: Value to be written. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg - register address + * @param val - value to write */ -ReturnCode st25r3916WriteRegister(uint8_t reg, uint8_t val); +void st25r3916_write_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t val); -/*! - ***************************************************************************** - * \brief Writes multiple values to ST25R3916 registers +/** Write multiple registers * - * This function is used to write multiple values to the ST25R3916 using the - * auto-increment feature. That is, after each write the address pointer - * inside the ST25R3916 gets incremented automatically. - * - * \param[in] reg: Address of the first register to write. - * \param[in] values: pointer to a buffer containing the values to be written. - * \param[in] length: Number of values to be written. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg_start - start register address + * @param values - pointer to buffer to write + * @param length - number of registers to write */ -ReturnCode st25r3916WriteMultipleRegisters(uint8_t reg, const uint8_t* values, uint8_t length); +void st25r3916_write_burst_regs( + FuriHalSpiBusHandle* handle, + uint8_t reg_start, + const uint8_t* values, + uint8_t length); -/*! - ***************************************************************************** - * \brief Writes values to ST25R3916 FIFO +/** Write fifo register * - * This function needs to be called in order to write to the ST25R3916 FIFO. - * - * \param[in] values: pointer to a buffer containing the values to be written - * to the FIFO. - * \param[in] length: Number of values to be written. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param buff - buffer to write to FIFO + * @param length - number of bytes to write */ -ReturnCode st25r3916WriteFifo(const uint8_t* values, uint16_t length); +void st25r3916_reg_write_fifo(FuriHalSpiBusHandle* handle, const uint8_t* buff, size_t length); -/*! - ***************************************************************************** - * \brief Read values from ST25R3916 FIFO +/** Read fifo register * - * This function needs to be called in order to read from ST25R3916 FIFO. - * - * \param[out] buf: pointer to a buffer where the FIFO content shall be - * written to. - * \param[in] length: Number of bytes to read. - * - * \note: This function doesn't check whether \a length is really the - * number of available bytes in FIFO - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param buff - buffer to store the read values + * @param length - number of bytes to read */ -ReturnCode st25r3916ReadFifo(uint8_t* buf, uint16_t length); +void st25r3916_reg_read_fifo(FuriHalSpiBusHandle* handle, uint8_t* buff, size_t length); -/*! - ***************************************************************************** - * \brief Writes values to ST25R3916 PTM +/** Write PTA memory register * - * Accesses to the begging of ST25R3916 Passive Target Memory (PTM A Config) - * and writes the given values - * - * \param[in] values: pointer to a buffer containing the values to be written - * to the Passive Target Memory. - * \param[in] length: Number of values to be written. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param values - pointer to buffer to write + * @param length - number of bytes to write */ -ReturnCode st25r3916WritePTMem(const uint8_t* values, uint16_t length); +void st25r3916_write_pta_mem(FuriHalSpiBusHandle* handle, const uint8_t* values, size_t length); -/*! - ***************************************************************************** - * \brief Reads the ST25R3916 PTM +/** Read PTA memory register * - * Accesses to the begging of ST25R3916 Passive Target Memory (PTM A Config) - * and reads the memory for the given length - * - * \param[out] values: pointer to a buffer where the PTM content shall be - * written to. - * \param[in] length: Number of bytes to read. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param values - buffer to store the read values + * @param length - number of bytes to read */ -ReturnCode st25r3916ReadPTMem(uint8_t* values, uint16_t length); +void st25r3916_read_pta_mem(FuriHalSpiBusHandle* handle, uint8_t* values, size_t length); -/*! - ***************************************************************************** - * \brief Writes values to ST25R3916 PTM F config +/** Write PTF memory register * - * Accesses ST25R3916 Passive Target Memory F config and writes the given values - * - * \param[in] values: pointer to a buffer containing the values to be written - * to the Passive Target Memory - * \param[in] length: Number of values to be written. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param values - pointer to buffer to write + * @param length - number of bytes to write */ -ReturnCode st25r3916WritePTMemF(const uint8_t* values, uint16_t length); +void st25r3916_write_ptf_mem(FuriHalSpiBusHandle* handle, const uint8_t* values, size_t length); -/*! - ***************************************************************************** - * \brief Writes values to ST25R3916 PTM TSN Data +/** Read PTTSN memory register * - * Accesses ST25R3916 Passive Target Memory TSN data and writes the given values - * - * \param[in] values: pointer to a buffer containing the values to be written - * to the Passive Target Memory. - * \param[in] length: Number of values to be written. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param values - pointer to buffer to write + * @param length - number of bytes to write */ -ReturnCode st25r3916WritePTMemTSN(const uint8_t* values, uint16_t length); +void st25r3916_write_pttsn_mem(FuriHalSpiBusHandle* handle, uint8_t* values, size_t length); -/*! - ***************************************************************************** - * \brief Execute a direct command +/** Send Direct command * - * This function is used to start so-called direct command. These commands - * are implemented inside the chip and each command has unique code (see - * datasheet). - * - * \param[in] cmd : code of the direct command to be executed. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param cmd - direct command */ -ReturnCode st25r3916ExecuteCommand(uint8_t cmd); +void st25r3916_direct_cmd(FuriHalSpiBusHandle* handle, uint8_t cmd); -/*! - ***************************************************************************** - * \brief Read a test register within the ST25R3916 - * - * This function is used to read the content of test address \a reg within the ST25R3916 - * - * \param[in] reg: Address of the register to read - * \param[out] val: Returned read value - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** +/** Read test register + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg - register address + * @param val - pointer to the variable to store the read value */ -ReturnCode st25r3916ReadTestRegister(uint8_t reg, uint8_t* val); +void st25r3916_read_test_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t* val); -/*! - ***************************************************************************** - * \brief Writes a given value to a test register within the ST25R3916 +/** Write test register * - * This function is used to write \a val to test address \a reg within the ST25R3916 - * - * \param[in] reg: Address of the register to write - * \param[in] val: Value to be written - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg - register address + * @param val - value to write */ -ReturnCode st25r3916WriteTestRegister(uint8_t reg, uint8_t val); +void st25r3916_write_test_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t val); -/*! - ***************************************************************************** - * \brief Cleart bits on Register +/** Clear register bits * - * This function clears the given bitmask on the register - * - * \param[in] reg: Address of the register clear - * \param[in] clr_mask: Bitmask of bit to be cleared - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg - register address + * @param clr_mask - bit mask to clear */ -ReturnCode st25r3916ClrRegisterBits(uint8_t reg, uint8_t clr_mask); +void st25r3916_clear_reg_bits(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t clr_mask); -/*! - ***************************************************************************** - * \brief Set bits on Register +/** Set register bits * - * This function sets the given bitmask on the register - * - * \param[in] reg: Address of the register clear - * \param[in] set_mask: Bitmask of bit to be cleared - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg - register address + * @param set_mask - bit mask to set */ -ReturnCode st25r3916SetRegisterBits(uint8_t reg, uint8_t set_mask); +void st25r3916_set_reg_bits(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t set_mask); -/*! - ***************************************************************************** - * \brief Changes the given bits on a ST25R3916 register +/** Change register bits * - * This function is used if only a particular bits should be changed within - * an ST25R3916 register. - * - * \param[in] reg: Address of the register to change. - * \param[in] valueMask: bitmask of bits to be changed - * \param[in] value: the bits to be written on the enabled valueMask bits - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg - register address + * @param mask - bit mask to change + * @param value - new register value to write */ -ReturnCode st25r3916ChangeRegisterBits(uint8_t reg, uint8_t valueMask, uint8_t value); +void st25r3916_change_reg_bits( + FuriHalSpiBusHandle* handle, + uint8_t reg, + uint8_t mask, + uint8_t value); -/*! - ***************************************************************************** - * \brief Modifies a value within a ST25R3916 register +/** Modify register * - * This function is used if only a particular bits should be changed within - * an ST25R3916 register. - * - * \param[in] reg: Address of the register to write. - * \param[in] clr_mask: bitmask of bits to be cleared to 0. - * \param[in] set_mask: bitmask of bits to be set to 1. - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg - register address + * @param clr_mask - bit mask to clear + * @param set_mask - bit mask to set */ -ReturnCode st25r3916ModifyRegister(uint8_t reg, uint8_t clr_mask, uint8_t set_mask); +void st25r3916_modify_reg( + FuriHalSpiBusHandle* handle, + uint8_t reg, + uint8_t clr_mask, + uint8_t set_mask); -/*! - ***************************************************************************** - * \brief Changes the given bits on a ST25R3916 Test register +/** Change test register bits * - * This function is used if only a particular bits should be changed within - * an ST25R3916 register. - * - * \param[in] reg: Address of the Test register to change. - * \param[in] valueMask: bitmask of bits to be changed - * \param[in] value: the bits to be written on the enabled valueMask bits - * - * \return ERR_NONE : Operation successful - * \return ERR_PARAM : Invalid parameter - * \return ERR_SEND : Transmission error or acknowledge not received - ***************************************************************************** + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg - register address + * @param mask - bit mask to change + * @param value - new register value to write */ -ReturnCode st25r3916ChangeTestRegisterBits(uint8_t reg, uint8_t valueMask, uint8_t value); +void st25r3916_change_test_reg_bits( + FuriHalSpiBusHandle* handle, + uint8_t reg, + uint8_t mask, + uint8_t value); -/*! - ***************************************************************************** - * \brief Checks if register contains a expected value +/** Check register * - * This function checks if the given reg contains a value that once masked - * equals the expected value + * @param handle - pointer to FuriHalSpiBusHandle instance + * @param reg - register address + * @param mask - bit mask to check + * @param val - expected register value * - * \param reg : the register to check the value - * \param mask : the mask apply on register value - * \param val : expected value to be compared to - * - * \return true when reg contains the expected value | false otherwise + * @return true if register value matches the expected value, false otherwise */ -bool st25r3916CheckReg(uint8_t reg, uint8_t mask, uint8_t val); +bool st25r3916_check_reg(FuriHalSpiBusHandle* handle, uint8_t reg, uint8_t mask, uint8_t val); -/*! - ***************************************************************************** - * \brief Check if register ID is valid - * - * Checks if the given register ID a valid ST25R3916 register - * - * \param[in] reg: Address of register to check - * - * \return true if is a valid register ID - * \return false otherwise - * - ***************************************************************************** - */ -bool st25r3916IsRegValid(uint8_t reg); - -#endif /* ST25R3916_COM_H */ - -/** - * @} - * - * @} - * - * @} - * - * @} - */ +#ifdef __cplusplus +} +#endif diff --git a/lib/flipper_application/plugins/plugin_manager.c b/lib/flipper_application/plugins/plugin_manager.c index e2a7b83f4..8f30ed13e 100644 --- a/lib/flipper_application/plugins/plugin_manager.c +++ b/lib/flipper_application/plugins/plugin_manager.c @@ -66,7 +66,8 @@ PluginManagerError plugin_manager_load_single(PluginManager* manager, const char FlipperApplicationLoadStatus load_status = flipper_application_map_to_memory(lib); if(load_status != FlipperApplicationLoadStatusSuccess) { - FURI_LOG_E(TAG, "Failed to load module_demo_plugin1.fal"); + FURI_LOG_E(TAG, "Failed to load %s", path); + error = PluginManagerErrorLoaderError; break; } diff --git a/lib/ibutton/ibutton_protocols.c b/lib/ibutton/ibutton_protocols.c index 75aa225ef..df7412670 100644 --- a/lib/ibutton/ibutton_protocols.c +++ b/lib/ibutton/ibutton_protocols.c @@ -48,7 +48,7 @@ static void ibutton_protocols_get_group_by_id( local_id -= ibutton_protocol_groups[i]->protocol_count; } } - furi_crash(NULL); + furi_crash(); } iButtonProtocols* ibutton_protocols_alloc() { diff --git a/lib/infrared/encoder_decoder/nec/infrared_encoder_nec.c b/lib/infrared/encoder_decoder/nec/infrared_encoder_nec.c index 87f815142..47d8c3c64 100644 --- a/lib/infrared/encoder_decoder/nec/infrared_encoder_nec.c +++ b/lib/infrared/encoder_decoder/nec/infrared_encoder_nec.c @@ -48,7 +48,7 @@ void infrared_encoder_nec_reset(void* encoder_ptr, const InfraredMessage* messag *data2 = (message->command & 0xFFC0) >> 6; encoder->bits_to_encode = 42; } else { - furi_assert(0); + furi_crash(); } } diff --git a/lib/infrared/encoder_decoder/sirc/infrared_encoder_sirc.c b/lib/infrared/encoder_decoder/sirc/infrared_encoder_sirc.c index 6adf2235c..39c2eb166 100644 --- a/lib/infrared/encoder_decoder/sirc/infrared_encoder_sirc.c +++ b/lib/infrared/encoder_decoder/sirc/infrared_encoder_sirc.c @@ -23,7 +23,7 @@ void infrared_encoder_sirc_reset(void* encoder_ptr, const InfraredMessage* messa *data |= (message->address & 0x1FFF) << 7; encoder->bits_to_encode = 20; } else { - furi_assert(0); + furi_crash(); } } diff --git a/lib/infrared/worker/infrared_transmit.c b/lib/infrared/worker/infrared_transmit.c index 113fb6324..8f99c0066 100644 --- a/lib/infrared/worker/infrared_transmit.c +++ b/lib/infrared/worker/infrared_transmit.c @@ -88,7 +88,7 @@ FuriHalInfraredTxGetDataState state = FuriHalInfraredTxGetDataStateDone; } } else { - furi_crash(NULL); + furi_crash(); } return state; diff --git a/lib/infrared/worker/infrared_worker.c b/lib/infrared/worker/infrared_worker.c index 46effd420..38392fc06 100644 --- a/lib/infrared/worker/infrared_worker.c +++ b/lib/infrared/worker/infrared_worker.c @@ -165,7 +165,7 @@ static int32_t infrared_worker_rx_thread(void* thread_context) { InfraredWorker* instance = thread_context; uint32_t events = 0; LevelDuration level_duration; - TickType_t last_blink_time = 0; + uint32_t last_blink_time = 0; while(1) { events = furi_thread_flags_wait(INFRARED_WORKER_ALL_RX_EVENTS, 0, FuriWaitForever); @@ -173,8 +173,8 @@ static int32_t infrared_worker_rx_thread(void* thread_context) { if(events & INFRARED_WORKER_RX_RECEIVED) { if(!instance->rx.overrun && instance->blink_enable && - ((xTaskGetTickCount() - last_blink_time) > 80)) { - last_blink_time = xTaskGetTickCount(); + ((furi_get_tick() - last_blink_time) > 80)) { + last_blink_time = furi_get_tick(); notification_message(instance->notification, &sequence_blink_blue_10); } if(instance->signal.timings_cnt == 0) @@ -367,10 +367,11 @@ static FuriHalInfraredTxGetDataState *duration = timing.duration; state = timing.state; } else { - furi_assert(0); + // Why bother if we crash anyway?.. *level = 0; *duration = 100; state = FuriHalInfraredTxGetDataStateDone; + furi_crash(); } uint32_t flags_set = furi_thread_flags_set( @@ -414,7 +415,7 @@ static bool infrared_get_new_signal(InfraredWorker* instance) { } else if(response == InfraredWorkerGetSignalResponseStop) { new_signal_obtained = false; } else { - furi_assert(0); + furi_crash(); } return new_signal_obtained; @@ -443,9 +444,8 @@ static bool infrared_worker_tx_fill_buffer(InfraredWorker* instance) { } if(status == InfraredStatusError) { - furi_assert(0); new_data_available = false; - break; + furi_crash(); } else if(status == InfraredStatusOk) { timing.state = FuriHalInfraredTxGetDataStateOk; } else if(status == InfraredStatusDone) { @@ -456,7 +456,7 @@ static bool infrared_worker_tx_fill_buffer(InfraredWorker* instance) { timing.state = FuriHalInfraredTxGetDataStateLastDone; } } else { - furi_assert(0); + furi_crash(); } uint32_t written_size = furi_stream_buffer_send(instance->stream, &timing, sizeof(InfraredWorkerTiming), 0); @@ -548,7 +548,7 @@ static int32_t infrared_worker_tx_thread(void* thread_context) { break; default: - furi_assert(0); + furi_crash(); break; } } diff --git a/lib/lfrfid/lfrfid_worker.c b/lib/lfrfid/lfrfid_worker.c index cbc7b02e3..ffaa8ee92 100644 --- a/lib/lfrfid/lfrfid_worker.c +++ b/lib/lfrfid/lfrfid_worker.c @@ -1,7 +1,7 @@ +#include "lfrfid_worker_i.h" + #include #include -#include -#include "lfrfid_worker_i.h" typedef enum { LFRFIDEventStopThread = (1 << 0), diff --git a/lib/misc.scons b/lib/misc.scons index 10aa3f9d5..92fa5a106 100644 --- a/lib/misc.scons +++ b/lib/misc.scons @@ -15,6 +15,9 @@ env.Append( ], SDK_HEADERS=[ File("micro-ecc/uECC.h"), + File("nanopb/pb.h"), + File("nanopb/pb_decode.h"), + File("nanopb/pb_encode.h"), ], ) diff --git a/lib/nfc/SConscript b/lib/nfc/SConscript index 7a0859ee4..6c55cf5d2 100644 --- a/lib/nfc/SConscript +++ b/lib/nfc/SConscript @@ -5,13 +5,46 @@ env.Append( "#/lib/nfc", ], SDK_HEADERS=[ + # Main + File("nfc.h"), File("nfc_device.h"), - File("nfc_worker.h"), - File("nfc_types.h"), - File("helpers/mfkey32.h"), - File("parsers/nfc_supported_card.h"), - File("helpers/nfc_generators.h"), - File("protocols/nfc_util.h"), + File("nfc_listener.h"), + File("nfc_poller.h"), + File("nfc_scanner.h"), + # Protocols + File("protocols/iso14443_3a/iso14443_3a.h"), + File("protocols/iso14443_3b/iso14443_3b.h"), + File("protocols/iso14443_4a/iso14443_4a.h"), + File("protocols/iso14443_4b/iso14443_4b.h"), + File("protocols/mf_ultralight/mf_ultralight.h"), + File("protocols/mf_classic/mf_classic.h"), + File("protocols/mf_desfire/mf_desfire.h"), + File("protocols/slix/slix.h"), + File("protocols/st25tb/st25tb.h"), + # Pollers + File("protocols/iso14443_3a/iso14443_3a_poller.h"), + File("protocols/iso14443_3b/iso14443_3b_poller.h"), + File("protocols/iso14443_4a/iso14443_4a_poller.h"), + File("protocols/iso14443_4b/iso14443_4b_poller.h"), + File("protocols/mf_ultralight/mf_ultralight_poller.h"), + File("protocols/mf_classic/mf_classic_poller.h"), + File("protocols/mf_desfire/mf_desfire_poller.h"), + File("protocols/st25tb/st25tb_poller.h"), + # Listeners + File("protocols/iso14443_3a/iso14443_3a_listener.h"), + File("protocols/iso14443_4a/iso14443_4a_listener.h"), + File("protocols/mf_ultralight/mf_ultralight_listener.h"), + File("protocols/mf_classic/mf_classic_listener.h"), + # Sync API + File("protocols/iso14443_3a/iso14443_3a_poller_sync_api.h"), + File("protocols/mf_ultralight/mf_ultralight_poller_sync_api.h"), + File("protocols/mf_classic/mf_classic_poller_sync_api.h"), + # Misc + File("helpers/nfc_util.h"), + File("helpers/iso14443_crc.h"), + File("helpers/iso13239_crc.h"), + File("helpers/nfc_data_generator.h"), + File("helpers/nfc_dict.h"), ], ) diff --git a/lib/nfc/helpers/felica_crc.c b/lib/nfc/helpers/felica_crc.c new file mode 100644 index 000000000..d5e0853a1 --- /dev/null +++ b/lib/nfc/helpers/felica_crc.c @@ -0,0 +1,52 @@ +#include "felica_crc.h" + +#include + +#define FELICA_CRC_POLY (0x1021U) // Polynomial: x^16 + x^12 + x^5 + 1 +#define FELICA_CRC_INIT (0x0000U) + +uint16_t felica_crc_calculate(const uint8_t* data, size_t length) { + uint16_t crc = FELICA_CRC_INIT; + + for(size_t i = 0; i < length; i++) { + crc ^= ((uint16_t)data[i] << 8); + for(size_t j = 0; j < 8; j++) { + if(crc & 0x8000) { + crc <<= 1; + crc ^= FELICA_CRC_POLY; + } else { + crc <<= 1; + } + } + } + + return (crc << 8) | (crc >> 8); +} + +void felica_crc_append(BitBuffer* buf) { + const uint8_t* data = bit_buffer_get_data(buf); + const size_t data_size = bit_buffer_get_size_bytes(buf); + + const uint16_t crc = felica_crc_calculate(data, data_size); + bit_buffer_append_bytes(buf, (const uint8_t*)&crc, FELICA_CRC_SIZE); +} + +bool felica_crc_check(const BitBuffer* buf) { + const size_t data_size = bit_buffer_get_size_bytes(buf); + if(data_size <= FELICA_CRC_SIZE) return false; + + uint16_t crc_received; + bit_buffer_write_bytes_mid(buf, &crc_received, data_size - FELICA_CRC_SIZE, FELICA_CRC_SIZE); + + const uint8_t* data = bit_buffer_get_data(buf); + const uint16_t crc_calc = felica_crc_calculate(data, data_size - FELICA_CRC_SIZE); + + return (crc_calc == crc_received); +} + +void felica_crc_trim(BitBuffer* buf) { + const size_t data_size = bit_buffer_get_size_bytes(buf); + furi_assert(data_size > FELICA_CRC_SIZE); + + bit_buffer_set_size_bytes(buf, data_size - FELICA_CRC_SIZE); +} diff --git a/lib/nfc/helpers/felica_crc.h b/lib/nfc/helpers/felica_crc.h new file mode 100644 index 000000000..d1dc29e74 --- /dev/null +++ b/lib/nfc/helpers/felica_crc.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include + +#include "bit_buffer.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define FELICA_CRC_SIZE sizeof(uint16_t) + +void felica_crc_append(BitBuffer* buf); + +bool felica_crc_check(const BitBuffer* buf); + +void felica_crc_trim(BitBuffer* buf); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/helpers/iso13239_crc.c b/lib/nfc/helpers/iso13239_crc.c new file mode 100644 index 000000000..c54fbcfb2 --- /dev/null +++ b/lib/nfc/helpers/iso13239_crc.c @@ -0,0 +1,62 @@ +#include "iso13239_crc.h" + +#include + +#define ISO13239_CRC_INIT_DEFAULT (0xFFFFU) +#define ISO13239_CRC_INIT_PICOPASS (0xE012U) +#define ISO13239_CRC_POLY (0x8408U) + +static uint16_t + iso13239_crc_calculate(Iso13239CrcType type, const uint8_t* data, size_t data_size) { + uint16_t crc; + + if(type == Iso13239CrcTypeDefault) { + crc = ISO13239_CRC_INIT_DEFAULT; + } else if(type == Iso13239CrcTypePicopass) { + crc = ISO13239_CRC_INIT_PICOPASS; + } else { + furi_crash("Wrong ISO13239 CRC type"); + } + + for(size_t i = 0; i < data_size; ++i) { + crc ^= (uint16_t)data[i]; + for(size_t j = 0; j < 8; ++j) { + if(crc & 1U) { + crc = (crc >> 1) ^ ISO13239_CRC_POLY; + } else { + crc >>= 1; + } + } + } + + return type == Iso13239CrcTypePicopass ? crc : ~crc; +} + +void iso13239_crc_append(Iso13239CrcType type, BitBuffer* buf) { + const uint8_t* data = bit_buffer_get_data(buf); + const size_t data_size = bit_buffer_get_size_bytes(buf); + + const uint16_t crc = iso13239_crc_calculate(type, data, data_size); + bit_buffer_append_bytes(buf, (const uint8_t*)&crc, ISO13239_CRC_SIZE); +} + +bool iso13239_crc_check(Iso13239CrcType type, const BitBuffer* buf) { + const size_t data_size = bit_buffer_get_size_bytes(buf); + if(data_size <= ISO13239_CRC_SIZE) return false; + + uint16_t crc_received; + bit_buffer_write_bytes_mid( + buf, &crc_received, data_size - ISO13239_CRC_SIZE, ISO13239_CRC_SIZE); + + const uint8_t* data = bit_buffer_get_data(buf); + const uint16_t crc_calc = iso13239_crc_calculate(type, data, data_size - ISO13239_CRC_SIZE); + + return (crc_calc == crc_received); +} + +void iso13239_crc_trim(BitBuffer* buf) { + const size_t data_size = bit_buffer_get_size_bytes(buf); + furi_assert(data_size > ISO13239_CRC_SIZE); + + bit_buffer_set_size_bytes(buf, data_size - ISO13239_CRC_SIZE); +} diff --git a/lib/nfc/helpers/iso13239_crc.h b/lib/nfc/helpers/iso13239_crc.h new file mode 100644 index 000000000..c71ec6bef --- /dev/null +++ b/lib/nfc/helpers/iso13239_crc.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ISO13239_CRC_SIZE sizeof(uint16_t) + +typedef enum { + Iso13239CrcTypeDefault, + Iso13239CrcTypePicopass, +} Iso13239CrcType; + +void iso13239_crc_append(Iso13239CrcType type, BitBuffer* buf); + +bool iso13239_crc_check(Iso13239CrcType type, const BitBuffer* buf); + +void iso13239_crc_trim(BitBuffer* buf); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/helpers/iso14443_4_layer.c b/lib/nfc/helpers/iso14443_4_layer.c new file mode 100644 index 000000000..26f4dc3b7 --- /dev/null +++ b/lib/nfc/helpers/iso14443_4_layer.c @@ -0,0 +1,64 @@ +#include "iso14443_4_layer.h" + +#include + +#define ISO14443_4_BLOCK_PCB (1U << 1) +#define ISO14443_4_BLOCK_PCB_I (0U) +#define ISO14443_4_BLOCK_PCB_R (5U << 5) +#define ISO14443_4_BLOCK_PCB_S (3U << 6) + +struct Iso14443_4Layer { + uint8_t pcb; + uint8_t pcb_prev; +}; + +static inline void iso14443_4_layer_update_pcb(Iso14443_4Layer* instance) { + instance->pcb_prev = instance->pcb; + instance->pcb ^= (uint8_t)0x01; +} + +Iso14443_4Layer* iso14443_4_layer_alloc() { + Iso14443_4Layer* instance = malloc(sizeof(Iso14443_4Layer)); + + iso14443_4_layer_reset(instance); + return instance; +} + +void iso14443_4_layer_free(Iso14443_4Layer* instance) { + furi_assert(instance); + free(instance); +} + +void iso14443_4_layer_reset(Iso14443_4Layer* instance) { + furi_assert(instance); + instance->pcb = ISO14443_4_BLOCK_PCB_I | ISO14443_4_BLOCK_PCB; +} + +void iso14443_4_layer_encode_block( + Iso14443_4Layer* instance, + const BitBuffer* input_data, + BitBuffer* block_data) { + furi_assert(instance); + + bit_buffer_append_byte(block_data, instance->pcb); + bit_buffer_append(block_data, input_data); + + iso14443_4_layer_update_pcb(instance); +} + +bool iso14443_4_layer_decode_block( + Iso14443_4Layer* instance, + BitBuffer* output_data, + const BitBuffer* block_data) { + furi_assert(instance); + + bool ret = false; + + do { + if(!bit_buffer_starts_with_byte(block_data, instance->pcb_prev)) break; + bit_buffer_copy_right(output_data, block_data, 1); + ret = true; + } while(false); + + return ret; +} diff --git a/lib/nfc/helpers/iso14443_4_layer.h b/lib/nfc/helpers/iso14443_4_layer.h new file mode 100644 index 000000000..712173ce1 --- /dev/null +++ b/lib/nfc/helpers/iso14443_4_layer.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso14443_4Layer Iso14443_4Layer; + +Iso14443_4Layer* iso14443_4_layer_alloc(); + +void iso14443_4_layer_free(Iso14443_4Layer* instance); + +void iso14443_4_layer_reset(Iso14443_4Layer* instance); + +void iso14443_4_layer_encode_block( + Iso14443_4Layer* instance, + const BitBuffer* input_data, + BitBuffer* block_data); + +bool iso14443_4_layer_decode_block( + Iso14443_4Layer* instance, + BitBuffer* output_data, + const BitBuffer* block_data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/helpers/iso14443_crc.c b/lib/nfc/helpers/iso14443_crc.c new file mode 100644 index 000000000..fda9871aa --- /dev/null +++ b/lib/nfc/helpers/iso14443_crc.c @@ -0,0 +1,57 @@ +#include "iso14443_crc.h" + +#include + +#define ISO14443_3A_CRC_INIT (0x6363U) +#define ISO14443_3B_CRC_INIT (0xFFFFU) + +static uint16_t + iso14443_crc_calculate(Iso14443CrcType type, const uint8_t* data, size_t data_size) { + uint16_t crc; + + if(type == Iso14443CrcTypeA) { + crc = ISO14443_3A_CRC_INIT; + } else if(type == Iso14443CrcTypeB) { + crc = ISO14443_3B_CRC_INIT; + } else { + furi_crash("Wrong ISO14443 CRC type"); + } + + for(size_t i = 0; i < data_size; i++) { + uint8_t byte = data[i]; + byte ^= (uint8_t)(crc & 0xff); + byte ^= byte << 4; + crc = (crc >> 8) ^ (((uint16_t)byte) << 8) ^ (((uint16_t)byte) << 3) ^ (byte >> 4); + } + + return type == Iso14443CrcTypeA ? crc : ~crc; +} + +void iso14443_crc_append(Iso14443CrcType type, BitBuffer* buf) { + const uint8_t* data = bit_buffer_get_data(buf); + const size_t data_size = bit_buffer_get_size_bytes(buf); + + const uint16_t crc = iso14443_crc_calculate(type, data, data_size); + bit_buffer_append_bytes(buf, (const uint8_t*)&crc, ISO14443_CRC_SIZE); +} + +bool iso14443_crc_check(Iso14443CrcType type, const BitBuffer* buf) { + const size_t data_size = bit_buffer_get_size_bytes(buf); + if(data_size <= ISO14443_CRC_SIZE) return false; + + uint16_t crc_received; + bit_buffer_write_bytes_mid( + buf, &crc_received, data_size - ISO14443_CRC_SIZE, ISO14443_CRC_SIZE); + + const uint8_t* data = bit_buffer_get_data(buf); + const uint16_t crc_calc = iso14443_crc_calculate(type, data, data_size - ISO14443_CRC_SIZE); + + return (crc_calc == crc_received); +} + +void iso14443_crc_trim(BitBuffer* buf) { + const size_t data_size = bit_buffer_get_size_bytes(buf); + furi_assert(data_size > ISO14443_CRC_SIZE); + + bit_buffer_set_size_bytes(buf, data_size - ISO14443_CRC_SIZE); +} diff --git a/lib/nfc/helpers/iso14443_crc.h b/lib/nfc/helpers/iso14443_crc.h new file mode 100644 index 000000000..14a63841e --- /dev/null +++ b/lib/nfc/helpers/iso14443_crc.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ISO14443_CRC_SIZE sizeof(uint16_t) + +typedef enum { + Iso14443CrcTypeA, + Iso14443CrcTypeB, +} Iso14443CrcType; + +void iso14443_crc_append(Iso14443CrcType type, BitBuffer* buf); + +bool iso14443_crc_check(Iso14443CrcType type, const BitBuffer* buf); + +void iso14443_crc_trim(BitBuffer* buf); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/helpers/mf_classic_dict.c b/lib/nfc/helpers/mf_classic_dict.c deleted file mode 100644 index 937addb46..000000000 --- a/lib/nfc/helpers/mf_classic_dict.c +++ /dev/null @@ -1,349 +0,0 @@ -#include "mf_classic_dict.h" - -#include -#include - -#define MF_CLASSIC_DICT_FLIPPER_PATH EXT_PATH("nfc/assets/mf_classic_dict.nfc") -#define MF_CLASSIC_DICT_USER_PATH EXT_PATH("nfc/assets/mf_classic_dict_user.nfc") -#define MF_CLASSIC_DICT_UNIT_TEST_PATH EXT_PATH("unit_tests/mf_classic_dict.nfc") - -#define TAG "MfClassicDict" - -#define NFC_MF_CLASSIC_KEY_LEN (13) - -struct MfClassicDict { - Stream* stream; - uint32_t total_keys; -}; - -bool mf_classic_dict_check_presence(MfClassicDictType dict_type) { - Storage* storage = furi_record_open(RECORD_STORAGE); - - bool dict_present = false; - if(dict_type == MfClassicDictTypeSystem) { - dict_present = storage_common_stat(storage, MF_CLASSIC_DICT_FLIPPER_PATH, NULL) == FSE_OK; - } else if(dict_type == MfClassicDictTypeUser) { - dict_present = storage_common_stat(storage, MF_CLASSIC_DICT_USER_PATH, NULL) == FSE_OK; - } else if(dict_type == MfClassicDictTypeUnitTest) { - dict_present = storage_common_stat(storage, MF_CLASSIC_DICT_UNIT_TEST_PATH, NULL) == - FSE_OK; - } - - furi_record_close(RECORD_STORAGE); - - return dict_present; -} - -MfClassicDict* mf_classic_dict_alloc(MfClassicDictType dict_type) { - MfClassicDict* dict = malloc(sizeof(MfClassicDict)); - Storage* storage = furi_record_open(RECORD_STORAGE); - dict->stream = buffered_file_stream_alloc(storage); - furi_record_close(RECORD_STORAGE); - - bool dict_loaded = false; - do { - if(dict_type == MfClassicDictTypeSystem) { - if(!buffered_file_stream_open( - dict->stream, - MF_CLASSIC_DICT_FLIPPER_PATH, - FSAM_READ_WRITE, - FSOM_OPEN_EXISTING)) { - buffered_file_stream_close(dict->stream); - break; - } - } else if(dict_type == MfClassicDictTypeUser) { - if(!buffered_file_stream_open( - dict->stream, MF_CLASSIC_DICT_USER_PATH, FSAM_READ_WRITE, FSOM_OPEN_ALWAYS)) { - buffered_file_stream_close(dict->stream); - break; - } - } else if(dict_type == MfClassicDictTypeUnitTest) { - if(!buffered_file_stream_open( - dict->stream, - MF_CLASSIC_DICT_UNIT_TEST_PATH, - FSAM_READ_WRITE, - FSOM_OPEN_ALWAYS)) { - buffered_file_stream_close(dict->stream); - break; - } - } - - // Check for new line ending - if(!stream_eof(dict->stream)) { - if(!stream_seek(dict->stream, -1, StreamOffsetFromEnd)) break; - uint8_t last_char = 0; - if(stream_read(dict->stream, &last_char, 1) != 1) break; - if(last_char != '\n') { - FURI_LOG_D(TAG, "Adding new line ending"); - if(stream_write_char(dict->stream, '\n') != 1) break; - } - if(!stream_rewind(dict->stream)) break; - } - - // Read total amount of keys - FuriString* next_line; - next_line = furi_string_alloc(); - while(true) { - if(!stream_read_line(dict->stream, next_line)) { - FURI_LOG_T(TAG, "No keys left in dict"); - break; - } - FURI_LOG_T( - TAG, - "Read line: %s, len: %zu", - furi_string_get_cstr(next_line), - furi_string_size(next_line)); - if(furi_string_get_char(next_line, 0) == '#') continue; - if(furi_string_size(next_line) != NFC_MF_CLASSIC_KEY_LEN) continue; - dict->total_keys++; - } - furi_string_free(next_line); - stream_rewind(dict->stream); - - dict_loaded = true; - FURI_LOG_I(TAG, "Loaded dictionary with %lu keys", dict->total_keys); - } while(false); - - if(!dict_loaded) { - buffered_file_stream_close(dict->stream); - free(dict); - dict = NULL; - } - - return dict; -} - -void mf_classic_dict_free(MfClassicDict* dict) { - furi_assert(dict); - furi_assert(dict->stream); - - buffered_file_stream_close(dict->stream); - stream_free(dict->stream); - free(dict); -} - -static void mf_classic_dict_int_to_str(uint8_t* key_int, FuriString* key_str) { - furi_string_reset(key_str); - for(size_t i = 0; i < 6; i++) { - furi_string_cat_printf(key_str, "%02X", key_int[i]); - } -} - -static void mf_classic_dict_str_to_int(FuriString* key_str, uint64_t* key_int) { - uint8_t key_byte_tmp; - - *key_int = 0ULL; - for(uint8_t i = 0; i < 12; i += 2) { - args_char_to_hex( - furi_string_get_char(key_str, i), furi_string_get_char(key_str, i + 1), &key_byte_tmp); - *key_int |= (uint64_t)key_byte_tmp << (8 * (5 - i / 2)); - } -} - -uint32_t mf_classic_dict_get_total_keys(MfClassicDict* dict) { - furi_assert(dict); - - return dict->total_keys; -} - -bool mf_classic_dict_rewind(MfClassicDict* dict) { - furi_assert(dict); - furi_assert(dict->stream); - - return stream_rewind(dict->stream); -} - -bool mf_classic_dict_get_next_key_str(MfClassicDict* dict, FuriString* key) { - furi_assert(dict); - furi_assert(dict->stream); - - bool key_read = false; - furi_string_reset(key); - while(!key_read) { - if(!stream_read_line(dict->stream, key)) break; - if(furi_string_get_char(key, 0) == '#') continue; - if(furi_string_size(key) != NFC_MF_CLASSIC_KEY_LEN) continue; - furi_string_left(key, 12); - key_read = true; - } - - return key_read; -} - -bool mf_classic_dict_get_next_key(MfClassicDict* dict, uint64_t* key) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* temp_key; - temp_key = furi_string_alloc(); - bool key_read = mf_classic_dict_get_next_key_str(dict, temp_key); - if(key_read) { - mf_classic_dict_str_to_int(temp_key, key); - } - furi_string_free(temp_key); - return key_read; -} - -bool mf_classic_dict_is_key_present_str(MfClassicDict* dict, FuriString* key) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* next_line; - next_line = furi_string_alloc(); - - bool key_found = false; - stream_rewind(dict->stream); - while(!key_found) { //-V654 - if(!stream_read_line(dict->stream, next_line)) break; - if(furi_string_get_char(next_line, 0) == '#') continue; - if(furi_string_size(next_line) != NFC_MF_CLASSIC_KEY_LEN) continue; - furi_string_left(next_line, 12); - if(!furi_string_equal(key, next_line)) continue; - key_found = true; - } - - furi_string_free(next_line); - return key_found; -} - -bool mf_classic_dict_is_key_present(MfClassicDict* dict, uint8_t* key) { - FuriString* temp_key; - - temp_key = furi_string_alloc(); - mf_classic_dict_int_to_str(key, temp_key); - bool key_found = mf_classic_dict_is_key_present_str(dict, temp_key); - furi_string_free(temp_key); - return key_found; -} - -bool mf_classic_dict_add_key_str(MfClassicDict* dict, FuriString* key) { - furi_assert(dict); - furi_assert(dict->stream); - - furi_string_cat_printf(key, "\n"); - - bool key_added = false; - do { - if(!stream_seek(dict->stream, 0, StreamOffsetFromEnd)) break; - if(!stream_insert_string(dict->stream, key)) break; - dict->total_keys++; - key_added = true; - } while(false); - - furi_string_left(key, 12); - return key_added; -} - -bool mf_classic_dict_add_key(MfClassicDict* dict, uint8_t* key) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* temp_key; - temp_key = furi_string_alloc(); - mf_classic_dict_int_to_str(key, temp_key); - bool key_added = mf_classic_dict_add_key_str(dict, temp_key); - - furi_string_free(temp_key); - return key_added; -} - -bool mf_classic_dict_get_key_at_index_str(MfClassicDict* dict, FuriString* key, uint32_t target) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* next_line; - uint32_t index = 0; - next_line = furi_string_alloc(); - furi_string_reset(key); - - bool key_found = false; - while(!key_found) { - if(!stream_read_line(dict->stream, next_line)) break; - if(furi_string_get_char(next_line, 0) == '#') continue; - if(furi_string_size(next_line) != NFC_MF_CLASSIC_KEY_LEN) continue; - if(index++ != target) continue; - furi_string_set_n(key, next_line, 0, 12); - key_found = true; - } - - furi_string_free(next_line); - return key_found; -} - -bool mf_classic_dict_get_key_at_index(MfClassicDict* dict, uint64_t* key, uint32_t target) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* temp_key; - temp_key = furi_string_alloc(); - bool key_found = mf_classic_dict_get_key_at_index_str(dict, temp_key, target); - if(key_found) { - mf_classic_dict_str_to_int(temp_key, key); - } - furi_string_free(temp_key); - return key_found; -} - -bool mf_classic_dict_find_index_str(MfClassicDict* dict, FuriString* key, uint32_t* target) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* next_line; - next_line = furi_string_alloc(); - - bool key_found = false; - uint32_t index = 0; - stream_rewind(dict->stream); - while(!key_found) { //-V654 - if(!stream_read_line(dict->stream, next_line)) break; - if(furi_string_get_char(next_line, 0) == '#') continue; - if(furi_string_size(next_line) != NFC_MF_CLASSIC_KEY_LEN) continue; - furi_string_left(next_line, 12); - if(!furi_string_equal(key, next_line)) continue; - key_found = true; - *target = index; - } - - furi_string_free(next_line); - return key_found; -} - -bool mf_classic_dict_find_index(MfClassicDict* dict, uint8_t* key, uint32_t* target) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* temp_key; - temp_key = furi_string_alloc(); - mf_classic_dict_int_to_str(key, temp_key); - bool key_found = mf_classic_dict_find_index_str(dict, temp_key, target); - - furi_string_free(temp_key); - return key_found; -} - -bool mf_classic_dict_delete_index(MfClassicDict* dict, uint32_t target) { - furi_assert(dict); - furi_assert(dict->stream); - - FuriString* next_line; - next_line = furi_string_alloc(); - uint32_t index = 0; - - bool key_removed = false; - stream_rewind(dict->stream); - while(!key_removed) { - if(!stream_read_line(dict->stream, next_line)) break; - if(furi_string_get_char(next_line, 0) == '#') continue; - if(furi_string_size(next_line) != NFC_MF_CLASSIC_KEY_LEN) continue; - if(index++ != target) continue; - stream_seek(dict->stream, -NFC_MF_CLASSIC_KEY_LEN, StreamOffsetFromCurrent); - if(!stream_delete(dict->stream, NFC_MF_CLASSIC_KEY_LEN)) break; - dict->total_keys--; - key_removed = true; - } - - stream_rewind(dict->stream); - - furi_string_free(next_line); - return key_removed; -} diff --git a/lib/nfc/helpers/mf_classic_dict.h b/lib/nfc/helpers/mf_classic_dict.h deleted file mode 100644 index 71002664a..000000000 --- a/lib/nfc/helpers/mf_classic_dict.h +++ /dev/null @@ -1,107 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - MfClassicDictTypeUser, - MfClassicDictTypeSystem, - MfClassicDictTypeUnitTest, -} MfClassicDictType; - -typedef struct MfClassicDict MfClassicDict; - -bool mf_classic_dict_check_presence(MfClassicDictType dict_type); - -/** Allocate MfClassicDict instance - * - * @param[in] dict_type The dictionary type - * - * @return MfClassicDict instance - */ -MfClassicDict* mf_classic_dict_alloc(MfClassicDictType dict_type); - -/** Free MfClassicDict instance - * - * @param dict MfClassicDict instance - */ -void mf_classic_dict_free(MfClassicDict* dict); - -/** Get total keys count - * - * @param dict MfClassicDict instance - * - * @return total keys count - */ -uint32_t mf_classic_dict_get_total_keys(MfClassicDict* dict); - -/** Rewind to the beginning - * - * @param dict MfClassicDict instance - * - * @return true on success - */ -bool mf_classic_dict_rewind(MfClassicDict* dict); - -bool mf_classic_dict_is_key_present(MfClassicDict* dict, uint8_t* key); - -bool mf_classic_dict_is_key_present_str(MfClassicDict* dict, FuriString* key); - -bool mf_classic_dict_get_next_key(MfClassicDict* dict, uint64_t* key); - -bool mf_classic_dict_get_next_key_str(MfClassicDict* dict, FuriString* key); - -/** Get key at target offset as uint64_t - * - * @param dict MfClassicDict instance - * @param[out] key Pointer to the uint64_t key - * @param[in] target Target offset from current position - * - * @return true on success - */ -bool mf_classic_dict_get_key_at_index(MfClassicDict* dict, uint64_t* key, uint32_t target); - -/** Get key at target offset as FuriString* - * - * @param dict MfClassicDict instance - * @param[out] key Found key destination buffer - * @param[in] target Target offset from current position - * - * @return true on success - */ -bool mf_classic_dict_get_key_at_index_str(MfClassicDict* dict, FuriString* key, uint32_t target); - -bool mf_classic_dict_add_key(MfClassicDict* dict, uint8_t* key); - -/** Add string representation of the key - * - * @param dict MfClassicDict instance - * @param[in] key String representation of the key - * - * @return true on success - */ -bool mf_classic_dict_add_key_str(MfClassicDict* dict, FuriString* key); - -bool mf_classic_dict_find_index(MfClassicDict* dict, uint8_t* key, uint32_t* target); - -bool mf_classic_dict_find_index_str(MfClassicDict* dict, FuriString* key, uint32_t* target); - -/** Delete key at target offset - * - * @param dict MfClassicDict instance - * @param[in] target Target offset from current position - * - * @return true on success - */ -bool mf_classic_dict_delete_index(MfClassicDict* dict, uint32_t target); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/lib/nfc/helpers/mfkey32.c b/lib/nfc/helpers/mfkey32.c deleted file mode 100644 index 47e7e9f6b..000000000 --- a/lib/nfc/helpers/mfkey32.c +++ /dev/null @@ -1,228 +0,0 @@ -#include "mfkey32.h" - -#include -#include -#include -#include -#include - -#include -#include - -#define TAG "Mfkey32" - -#define MFKEY32_LOGS_PATH EXT_PATH("nfc/.mfkey32.log") - -typedef enum { - Mfkey32StateIdle, - Mfkey32StateAuthReceived, - Mfkey32StateAuthNtSent, - Mfkey32StateAuthArNrReceived, -} Mfkey32State; - -typedef struct { - uint32_t cuid; - uint8_t sector; - MfClassicKey key; - uint32_t nt0; - uint32_t nr0; - uint32_t ar0; - uint32_t nt1; - uint32_t nr1; - uint32_t ar1; -} Mfkey32Params; - -ARRAY_DEF(Mfkey32Params, Mfkey32Params, M_POD_OPLIST); - -typedef struct { - uint8_t sector; - MfClassicKey key; - uint32_t nt; - uint32_t nr; - uint32_t ar; -} Mfkey32Nonce; - -struct Mfkey32 { - Mfkey32State state; - Stream* file_stream; - Mfkey32Params_t params_arr; - Mfkey32Nonce nonce; - uint32_t cuid; - Mfkey32ParseDataCallback callback; - void* context; -}; - -Mfkey32* mfkey32_alloc(uint32_t cuid) { - Mfkey32* instance = malloc(sizeof(Mfkey32)); - instance->cuid = cuid; - instance->state = Mfkey32StateIdle; - Storage* storage = furi_record_open(RECORD_STORAGE); - instance->file_stream = buffered_file_stream_alloc(storage); - if(!buffered_file_stream_open( - instance->file_stream, MFKEY32_LOGS_PATH, FSAM_WRITE, FSOM_OPEN_APPEND)) { - buffered_file_stream_close(instance->file_stream); - stream_free(instance->file_stream); - free(instance); - instance = NULL; - } else { - Mfkey32Params_init(instance->params_arr); - } - - furi_record_close(RECORD_STORAGE); - - return instance; -} - -void mfkey32_free(Mfkey32* instance) { - furi_assert(instance != NULL); - - Mfkey32Params_clear(instance->params_arr); - buffered_file_stream_close(instance->file_stream); - stream_free(instance->file_stream); - free(instance); -} - -void mfkey32_set_callback(Mfkey32* instance, Mfkey32ParseDataCallback callback, void* context) { - furi_assert(instance); - furi_assert(callback); - - instance->callback = callback; - instance->context = context; -} - -static bool mfkey32_write_params(Mfkey32* instance, Mfkey32Params* params) { - FuriString* str = furi_string_alloc_printf( - "Sec %d key %c cuid %08lx nt0 %08lx nr0 %08lx ar0 %08lx nt1 %08lx nr1 %08lx ar1 %08lx\n", - params->sector, - params->key == MfClassicKeyA ? 'A' : 'B', - params->cuid, - params->nt0, - params->nr0, - params->ar0, - params->nt1, - params->nr1, - params->ar1); - bool write_success = stream_write_string(instance->file_stream, str); - furi_string_free(str); - return write_success; -} - -static void mfkey32_add_params(Mfkey32* instance) { - Mfkey32Nonce* nonce = &instance->nonce; - bool nonce_added = false; - // Search if we partially collected params - if(Mfkey32Params_size(instance->params_arr)) { - Mfkey32Params_it_t it; - for(Mfkey32Params_it(it, instance->params_arr); !Mfkey32Params_end_p(it); - Mfkey32Params_next(it)) { - Mfkey32Params* params = Mfkey32Params_ref(it); - if((params->sector == nonce->sector) && (params->key == nonce->key)) { - params->nt1 = nonce->nt; - params->nr1 = nonce->nr; - params->ar1 = nonce->ar; - nonce_added = true; - FURI_LOG_I( - TAG, - "Params for sector %d key %c collected", - params->sector, - params->key == MfClassicKeyA ? 'A' : 'B'); - // Write on sd card - if(mfkey32_write_params(instance, params)) { - Mfkey32Params_remove(instance->params_arr, it); - if(instance->callback) { - instance->callback(Mfkey32EventParamCollected, instance->context); - } - } - } - } - } - if(!nonce_added) { - Mfkey32Params params = { - .sector = nonce->sector, - .key = nonce->key, - .cuid = instance->cuid, - .nt0 = nonce->nt, - .nr0 = nonce->nr, - .ar0 = nonce->ar, - }; - Mfkey32Params_push_back(instance->params_arr, params); - } -} - -void mfkey32_process_data( - Mfkey32* instance, - uint8_t* data, - uint16_t len, - bool reader_to_tag, - bool crc_dropped) { - furi_assert(instance); - furi_assert(data); - - Mfkey32Nonce* nonce = &instance->nonce; - uint16_t data_len = len; - if((data_len > 3) && !crc_dropped) { - data_len -= 2; - } - - bool data_processed = false; - if(instance->state == Mfkey32StateIdle) { - if(reader_to_tag) { - if((data[0] == 0x60) || (data[0] == 0x61)) { - nonce->key = data[0] == 0x60 ? MfClassicKeyA : MfClassicKeyB; - nonce->sector = mf_classic_get_sector_by_block(data[1]); - instance->state = Mfkey32StateAuthReceived; - data_processed = true; - } - } - } else if(instance->state == Mfkey32StateAuthReceived) { - if(!reader_to_tag) { - if(len == 4) { - nonce->nt = nfc_util_bytes2num(data, 4); - instance->state = Mfkey32StateAuthNtSent; - data_processed = true; - } - } - } else if(instance->state == Mfkey32StateAuthNtSent) { - if(reader_to_tag) { - if(len == 8) { - nonce->nr = nfc_util_bytes2num(data, 4); - nonce->ar = nfc_util_bytes2num(&data[4], 4); - mfkey32_add_params(instance); - instance->state = Mfkey32StateIdle; - } - } - } - if(!data_processed) { - instance->state = Mfkey32StateIdle; - } -} - -uint16_t mfkey32_get_auth_sectors(FuriString* data_str) { - furi_assert(data_str); - - uint16_t nonces_num = 0; - Storage* storage = furi_record_open(RECORD_STORAGE); - Stream* file_stream = buffered_file_stream_alloc(storage); - FuriString* temp_str; - temp_str = furi_string_alloc(); - - do { - if(!buffered_file_stream_open( - file_stream, MFKEY32_LOGS_PATH, FSAM_READ, FSOM_OPEN_EXISTING)) - break; - while(true) { - if(!stream_read_line(file_stream, temp_str)) break; - size_t uid_pos = furi_string_search(temp_str, "cuid"); - furi_string_left(temp_str, uid_pos); - furi_string_push_back(temp_str, '\n'); - furi_string_cat(data_str, temp_str); - nonces_num++; - } - } while(false); - - buffered_file_stream_close(file_stream); - stream_free(file_stream); - furi_string_free(temp_str); - - return nonces_num; -} diff --git a/lib/nfc/helpers/mfkey32.h b/lib/nfc/helpers/mfkey32.h deleted file mode 100644 index e29043224..000000000 --- a/lib/nfc/helpers/mfkey32.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct Mfkey32 Mfkey32; - -typedef enum { - Mfkey32EventParamCollected, -} Mfkey32Event; - -typedef void (*Mfkey32ParseDataCallback)(Mfkey32Event event, void* context); - -Mfkey32* mfkey32_alloc(uint32_t cuid); - -void mfkey32_free(Mfkey32* instance); - -void mfkey32_process_data( - Mfkey32* instance, - uint8_t* data, - uint16_t len, - bool reader_to_tag, - bool crc_dropped); - -void mfkey32_set_callback(Mfkey32* instance, Mfkey32ParseDataCallback callback, void* context); - -uint16_t mfkey32_get_auth_sectors(FuriString* string); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/lib/nfc/helpers/nfc_data_generator.c b/lib/nfc/helpers/nfc_data_generator.c new file mode 100644 index 000000000..011f9f6db --- /dev/null +++ b/lib/nfc/helpers/nfc_data_generator.c @@ -0,0 +1,568 @@ +#include "nfc_data_generator.h" + +#include +#include +#include +#include +#include + +#define NXP_MANUFACTURER_ID (0x04) + +typedef void (*NfcDataGeneratorHandler)(NfcDevice* nfc_device); + +typedef struct { + const char* name; + NfcDataGeneratorHandler handler; +} NfcDataGenerator; + +static const uint8_t version_bytes_mf0ulx1[] = {0x00, 0x04, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03}; +static const uint8_t version_bytes_ntag21x[] = {0x00, 0x04, 0x04, 0x02, 0x01, 0x00, 0x00, 0x03}; +static const uint8_t version_bytes_ntag_i2c[] = {0x00, 0x04, 0x04, 0x05, 0x02, 0x00, 0x00, 0x03}; +static const uint8_t default_data_ntag203[] = + {0xE1, 0x10, 0x12, 0x00, 0x01, 0x03, 0xA0, 0x10, 0x44, 0x03, 0x00, 0xFE}; +static const uint8_t default_data_ntag213[] = {0x01, 0x03, 0xA0, 0x0C, 0x34, 0x03, 0x00, 0xFE}; +static const uint8_t default_data_ntag215_216[] = {0x03, 0x00, 0xFE}; +static const uint8_t default_data_ntag_i2c[] = {0xE1, 0x10, 0x00, 0x00, 0x03, 0x00, 0xFE}; +static const uint8_t default_config_ntag_i2c[] = {0x01, 0x00, 0xF8, 0x48, 0x08, 0x01, 0x00, 0x00}; + +static void nfc_generate_mf_ul_uid(uint8_t* uid) { + uid[0] = NXP_MANUFACTURER_ID; + furi_hal_random_fill_buf(&uid[1], 6); + uid[3] |= 0x01; // To avoid forbidden 0x88 value + // I'm not sure how this is generated, but the upper nybble always seems to be 8 + uid[6] &= 0x0F; + uid[6] |= 0x80; +} + +static void nfc_generate_mf_ul_common(MfUltralightData* mfu_data) { + mfu_data->iso14443_3a_data->uid_len = 7; + nfc_generate_mf_ul_uid(mfu_data->iso14443_3a_data->uid); + mfu_data->iso14443_3a_data->atqa[0] = 0x44; + mfu_data->iso14443_3a_data->atqa[1] = 0x00; + mfu_data->iso14443_3a_data->sak = 0x00; +} + +static void nfc_generate_calc_bcc(uint8_t* uid, uint8_t* bcc0, uint8_t* bcc1) { + *bcc0 = 0x88 ^ uid[0] ^ uid[1] ^ uid[2]; + *bcc1 = uid[3] ^ uid[4] ^ uid[5] ^ uid[6]; +} + +static void nfc_generate_mf_ul_copy_uid_with_bcc(MfUltralightData* mfu_data) { + memcpy(mfu_data->page[0].data, mfu_data->iso14443_3a_data->uid, 3); + memcpy(mfu_data->page[1].data, &mfu_data->iso14443_3a_data->uid[3], 4); + + nfc_generate_calc_bcc( + mfu_data->iso14443_3a_data->uid, &mfu_data->page[0].data[3], &mfu_data->page[2].data[0]); +} + +static void nfc_generate_mf_ul_orig(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + nfc_generate_mf_ul_common(mfu_data); + + mfu_data->type = MfUltralightTypeUnknown; + mfu_data->pages_total = 16; + mfu_data->pages_read = 16; + nfc_generate_mf_ul_copy_uid_with_bcc(mfu_data); + memset(&mfu_data->page[4], 0xff, sizeof(MfUltralightPage)); + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_mf_ul_with_config_common(MfUltralightData* mfu_data, uint8_t num_pages) { + nfc_generate_mf_ul_common(mfu_data); + + mfu_data->pages_total = num_pages; + mfu_data->pages_read = num_pages; + nfc_generate_mf_ul_copy_uid_with_bcc(mfu_data); + uint16_t config_index = (num_pages - 4); + mfu_data->page[config_index].data[0] = 0x04; // STRG_MOD_EN + mfu_data->page[config_index].data[3] = 0xff; // AUTH0 + mfu_data->page[config_index + 1].data[1] = 0x05; // VCTID + memset(&mfu_data->page[config_index + 2], 0xff, sizeof(MfUltralightPage)); // Default PWD + if(num_pages > 20) { + mfu_data->page[config_index - 1].data[3] = MF_ULTRALIGHT_TEARING_FLAG_DEFAULT; + } +} + +static void nfc_generate_mf_ul_ev1_common(MfUltralightData* mfu_data, uint8_t num_pages) { + nfc_generate_mf_ul_with_config_common(mfu_data, num_pages); + memcpy(&mfu_data->version, version_bytes_mf0ulx1, sizeof(MfUltralightVersion)); + for(size_t i = 0; i < 3; ++i) { + mfu_data->tearing_flag[i].data = MF_ULTRALIGHT_TEARING_FLAG_DEFAULT; + } +} + +static void nfc_generate_mf_ul_11(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_mf_ul_ev1_common(mfu_data, 20); + mfu_data->type = MfUltralightTypeUL11; + mfu_data->version.prod_subtype = 0x01; + mfu_data->version.storage_size = 0x0B; + mfu_data->page[16].data[0] = 0x00; // Low capacitance version does not have STRG_MOD_EN + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_mf_ul_h11(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_mf_ul_ev1_common(mfu_data, 20); + mfu_data->type = MfUltralightTypeUL11; + mfu_data->version.prod_subtype = 0x02; + mfu_data->version.storage_size = 0x0B; + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_mf_ul_21(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_mf_ul_ev1_common(mfu_data, 41); + mfu_data->type = MfUltralightTypeUL21; + mfu_data->version.prod_subtype = 0x01; + mfu_data->version.storage_size = 0x0E; + mfu_data->page[37].data[0] = 0x00; // Low capacitance version does not have STRG_MOD_EN + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_mf_ul_h21(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_mf_ul_ev1_common(mfu_data, 41); + mfu_data->type = MfUltralightTypeUL21; + mfu_data->version.prod_subtype = 0x02; + mfu_data->version.storage_size = 0x0E; + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_ntag203(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_mf_ul_common(mfu_data); + mfu_data->type = MfUltralightTypeNTAG203; + mfu_data->pages_total = 42; + mfu_data->pages_read = 42; + nfc_generate_mf_ul_copy_uid_with_bcc(mfu_data); + mfu_data->page[2].data[1] = 0x48; // Internal byte + memcpy(&mfu_data->page[3], default_data_ntag203, sizeof(MfUltralightPage)); //-V1086 + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_ntag21x_common(MfUltralightData* mfu_data, uint8_t num_pages) { + nfc_generate_mf_ul_with_config_common(mfu_data, num_pages); + memcpy(&mfu_data->version, version_bytes_ntag21x, sizeof(MfUltralightVersion)); + mfu_data->page[2].data[1] = 0x48; // Internal byte + // Capability container + mfu_data->page[3].data[0] = 0xE1; + mfu_data->page[3].data[1] = 0x10; +} + +static void nfc_generate_ntag213(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_ntag21x_common(mfu_data, 45); + mfu_data->type = MfUltralightTypeNTAG213; + mfu_data->version.storage_size = 0x0F; + mfu_data->page[3].data[2] = 0x12; + // Default contents + memcpy(&mfu_data->page[4], default_data_ntag213, sizeof(default_data_ntag213)); + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_ntag215(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_ntag21x_common(mfu_data, 135); + mfu_data->type = MfUltralightTypeNTAG215; + mfu_data->version.storage_size = 0x11; + mfu_data->page[3].data[2] = 0x3E; + // Default contents + memcpy(&mfu_data->page[4], default_data_ntag215_216, sizeof(default_data_ntag215_216)); + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_ntag216(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_ntag21x_common(mfu_data, 231); + mfu_data->type = MfUltralightTypeNTAG216; + mfu_data->version.storage_size = 0x13; + mfu_data->page[3].data[2] = 0x6D; + // Default contents + memcpy(&mfu_data->page[4], default_data_ntag215_216, sizeof(default_data_ntag215_216)); + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_ntag_i2c_common( + MfUltralightData* mfu_data, + MfUltralightType type, + uint16_t num_pages) { + nfc_generate_mf_ul_common(mfu_data); + + mfu_data->type = type; + memcpy(&mfu_data->version, version_bytes_ntag_i2c, sizeof(version_bytes_ntag_i2c)); + mfu_data->pages_total = num_pages; + mfu_data->pages_read = num_pages; + memcpy( + mfu_data->page[0].data, + mfu_data->iso14443_3a_data->uid, + mfu_data->iso14443_3a_data->uid_len); + mfu_data->page[1].data[3] = mfu_data->iso14443_3a_data->sak; + mfu_data->page[2].data[0] = mfu_data->iso14443_3a_data->atqa[0]; + mfu_data->page[2].data[1] = mfu_data->iso14443_3a_data->atqa[1]; + + uint16_t config_register_page = 0; + uint16_t session_register_page = 0; + + // Sync with mifare_ultralight.c + switch(type) { + case MfUltralightTypeNTAGI2C1K: + config_register_page = 227; + session_register_page = 229; + break; + case MfUltralightTypeNTAGI2C2K: + config_register_page = 481; + session_register_page = 483; + break; + case MfUltralightTypeNTAGI2CPlus1K: + case MfUltralightTypeNTAGI2CPlus2K: + config_register_page = 232; + session_register_page = 234; + break; + default: + furi_crash("Unknown MFUL"); + break; + } + + memcpy( + &mfu_data->page[config_register_page], + default_config_ntag_i2c, + sizeof(default_config_ntag_i2c)); + memcpy( + &mfu_data->page[session_register_page], + default_config_ntag_i2c, + sizeof(default_config_ntag_i2c)); +} + +static void nfc_generate_ntag_i2c_1k(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_ntag_i2c_common(mfu_data, MfUltralightTypeNTAGI2C1K, 231); + mfu_data->version.prod_ver_minor = 0x01; + mfu_data->version.storage_size = 0x13; + memcpy(&mfu_data->page[3], default_data_ntag_i2c, sizeof(default_data_ntag_i2c)); + mfu_data->page[3].data[2] = 0x6D; // Size of tag in CC + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_ntag_i2c_2k(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_ntag_i2c_common(mfu_data, MfUltralightTypeNTAGI2C2K, 485); + mfu_data->version.prod_ver_minor = 0x01; + mfu_data->version.storage_size = 0x15; + memcpy(&mfu_data->page[3], default_data_ntag_i2c, sizeof(default_data_ntag_i2c)); + mfu_data->page[3].data[2] = 0xEA; // Size of tag in CC + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_ntag_i2c_plus_common( + MfUltralightData* mfu_data, + MfUltralightType type, + uint16_t num_pages) { + nfc_generate_ntag_i2c_common(mfu_data, type, num_pages); + + uint16_t config_index = 227; + mfu_data->page[config_index].data[3] = 0xff; // AUTH0 + + memset(&mfu_data->page[config_index + 2], 0xFF, sizeof(MfUltralightPage)); // Default PWD +} + +static void nfc_generate_ntag_i2c_plus_1k(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_ntag_i2c_plus_common(mfu_data, MfUltralightTypeNTAGI2CPlus1K, 236); + mfu_data->version.prod_ver_minor = 0x02; + mfu_data->version.storage_size = 0x13; + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_ntag_i2c_plus_2k(NfcDevice* nfc_device) { + MfUltralightData* mfu_data = mf_ultralight_alloc(); + + nfc_generate_ntag_i2c_plus_common(mfu_data, MfUltralightTypeNTAGI2CPlus2K, 492); + mfu_data->version.prod_ver_minor = 0x02; + mfu_data->version.storage_size = 0x15; + + nfc_device_set_data(nfc_device, NfcProtocolMfUltralight, mfu_data); + mf_ultralight_free(mfu_data); +} + +static void nfc_generate_mf_classic_uid(uint8_t* uid, uint8_t length) { + uid[0] = NXP_MANUFACTURER_ID; + furi_hal_random_fill_buf(&uid[1], length - 1); + uid[3] |= 0x01; // To avoid forbidden 0x88 value +} + +static void + nfc_generate_mf_classic_common(MfClassicData* data, uint8_t uid_len, MfClassicType type) { + data->iso14443_3a_data->uid_len = uid_len; + data->iso14443_3a_data->atqa[0] = 0x44; + data->iso14443_3a_data->atqa[1] = 0x00; + data->iso14443_3a_data->sak = 0x08; + data->type = type; +} + +static void nfc_generate_mf_classic_sector_trailer(MfClassicData* data, uint8_t block) { + // All keys are set to FFFF FFFF FFFFh at chip delivery and the bytes 6, 7 and 8 are set to FF0780h. + MfClassicSectorTrailer* sec_tr = (MfClassicSectorTrailer*)data->block[block].data; + sec_tr->access_bits.data[0] = 0xFF; + sec_tr->access_bits.data[1] = 0x07; + sec_tr->access_bits.data[2] = 0x80; + sec_tr->access_bits.data[3] = 0x69; // Nice + + mf_classic_set_block_read(data, block, &data->block[block]); + mf_classic_set_key_found( + data, mf_classic_get_sector_by_block(block), MfClassicKeyTypeA, 0xFFFFFFFFFFFF); + mf_classic_set_key_found( + data, mf_classic_get_sector_by_block(block), MfClassicKeyTypeB, 0xFFFFFFFFFFFF); +} + +static void nfc_generate_mf_classic_block_0( + uint8_t* block, + uint8_t uid_len, + uint8_t sak, + uint8_t atqa0, + uint8_t atqa1) { + // Block length is always 16 bytes, and the UID can be either 4 or 7 bytes + furi_assert(uid_len == 4 || uid_len == 7); + furi_assert(block); + + if(uid_len == 4) { + // Calculate BCC + block[uid_len] = 0; + + for(int i = 0; i < uid_len; i++) { + block[uid_len] ^= block[i]; + } + } else { + uid_len -= 1; + } + + block[uid_len + 1] = sak; + block[uid_len + 2] = atqa0; + block[uid_len + 3] = atqa1; + + for(int i = uid_len + 4; i < 16; i++) { + block[i] = 0xFF; + } +} + +static void nfc_generate_mf_classic(NfcDevice* nfc_device, uint8_t uid_len, MfClassicType type) { + MfClassicData* mfc_data = mf_classic_alloc(); + + nfc_generate_mf_classic_uid(mfc_data->block[0].data, uid_len); + nfc_generate_mf_classic_common(mfc_data, uid_len, type); + + // Set the UID + mfc_data->iso14443_3a_data->uid[0] = NXP_MANUFACTURER_ID; + for(int i = 1; i < uid_len; i++) { + mfc_data->iso14443_3a_data->uid[i] = mfc_data->block[0].data[i]; + } + + mf_classic_set_block_read(mfc_data, 0, &mfc_data->block[0]); + + uint16_t block_num = mf_classic_get_total_block_num(type); + if(type == MfClassicType4k) { + // Set every block to 0xFF + for(uint16_t i = 1; i < block_num; i++) { + if(mf_classic_is_sector_trailer(i)) { + nfc_generate_mf_classic_sector_trailer(mfc_data, i); + } else { + memset(&mfc_data->block[i].data, 0xFF, 16); + } + mf_classic_set_block_read(mfc_data, i, &mfc_data->block[i]); + } + // Set SAK to 18 + mfc_data->iso14443_3a_data->sak = 0x18; + } else if(type == MfClassicType1k) { + // Set every block to 0xFF + for(uint16_t i = 1; i < block_num; i++) { + if(mf_classic_is_sector_trailer(i)) { + nfc_generate_mf_classic_sector_trailer(mfc_data, i); + } else { + memset(&mfc_data->block[i].data, 0xFF, 16); + } + mf_classic_set_block_read(mfc_data, i, &mfc_data->block[i]); + } + // Set SAK to 08 + mfc_data->iso14443_3a_data->sak = 0x08; + } else if(type == MfClassicTypeMini) { + // Set every block to 0xFF + for(uint16_t i = 1; i < block_num; i++) { + if(mf_classic_is_sector_trailer(i)) { + nfc_generate_mf_classic_sector_trailer(mfc_data, i); + } else { + memset(&mfc_data->block[i].data, 0xFF, 16); + } + mf_classic_set_block_read(mfc_data, i, &mfc_data->block[i]); + } + // Set SAK to 09 + mfc_data->iso14443_3a_data->sak = 0x09; + } + + nfc_generate_mf_classic_block_0( + mfc_data->block[0].data, + uid_len, + mfc_data->iso14443_3a_data->sak, + mfc_data->iso14443_3a_data->atqa[0], + mfc_data->iso14443_3a_data->atqa[1]); + + mfc_data->type = type; + + nfc_device_set_data(nfc_device, NfcProtocolMfClassic, mfc_data); + mf_classic_free(mfc_data); +} + +static void nfc_generate_mf_classic_mini(NfcDevice* nfc_device) { + nfc_generate_mf_classic(nfc_device, 4, MfClassicTypeMini); +} + +static void nfc_generate_mf_classic_1k_4b_uid(NfcDevice* nfc_device) { + nfc_generate_mf_classic(nfc_device, 4, MfClassicType1k); +} + +static void nfc_generate_mf_classic_1k_7b_uid(NfcDevice* nfc_device) { + nfc_generate_mf_classic(nfc_device, 7, MfClassicType1k); +} + +static void nfc_generate_mf_classic_4k_4b_uid(NfcDevice* nfc_device) { + nfc_generate_mf_classic(nfc_device, 4, MfClassicType4k); +} + +static void nfc_generate_mf_classic_4k_7b_uid(NfcDevice* nfc_device) { + nfc_generate_mf_classic(nfc_device, 7, MfClassicType4k); +} + +static const NfcDataGenerator nfc_data_generator[NfcDataGeneratorTypeNum] = { + [NfcDataGeneratorTypeMfUltralight] = + { + .name = "Mifare Ultralight", + .handler = nfc_generate_mf_ul_orig, + }, + [NfcDataGeneratorTypeMfUltralightEV1_11] = + { + .name = "Mifare Ultralight EV1 11", + .handler = nfc_generate_mf_ul_11, + }, + [NfcDataGeneratorTypeMfUltralightEV1_H11] = + { + .name = "Mifare Ultralight EV1 H11", + .handler = nfc_generate_mf_ul_h11, + }, + [NfcDataGeneratorTypeMfUltralightEV1_21] = + { + .name = "Mifare Ultralight EV1 21", + .handler = nfc_generate_mf_ul_21, + }, + [NfcDataGeneratorTypeMfUltralightEV1_H21] = + { + .name = "Mifare Ultralight EV1 H21", + .handler = nfc_generate_mf_ul_h21, + }, + [NfcDataGeneratorTypeNTAG203] = + { + .name = "NTAG203", + .handler = nfc_generate_ntag203, + }, + [NfcDataGeneratorTypeNTAG213] = + { + .name = "NTAG213", + .handler = nfc_generate_ntag213, + }, + [NfcDataGeneratorTypeNTAG215] = + { + .name = "NTAG215", + .handler = nfc_generate_ntag215, + }, + [NfcDataGeneratorTypeNTAG216] = + { + .name = "NTAG216", + .handler = nfc_generate_ntag216, + }, + [NfcDataGeneratorTypeNTAGI2C1k] = + { + .name = "NTAG I2C 1k", + .handler = nfc_generate_ntag_i2c_1k, + }, + [NfcDataGeneratorTypeNTAGI2C2k] = + { + .name = "NTAG I2C 2k", + .handler = nfc_generate_ntag_i2c_2k, + }, + [NfcDataGeneratorTypeNTAGI2CPlus1k] = + { + .name = "NTAG I2C Plus 1k", + .handler = nfc_generate_ntag_i2c_plus_1k, + }, + [NfcDataGeneratorTypeNTAGI2CPlus2k] = + { + .name = "NTAG I2C Plus 2k", + .handler = nfc_generate_ntag_i2c_plus_2k, + }, + [NfcDataGeneratorTypeMfClassicMini] = + { + .name = "Mifare Mini", + .handler = nfc_generate_mf_classic_mini, + }, + [NfcDataGeneratorTypeMfClassic1k_4b] = + { + .name = "Mifare Classic 1k 4byte UID", + .handler = nfc_generate_mf_classic_1k_4b_uid, + }, + [NfcDataGeneratorTypeMfClassic1k_7b] = + { + .name = "Mifare Classic 1k 7byte UID", + .handler = nfc_generate_mf_classic_1k_7b_uid, + }, + [NfcDataGeneratorTypeMfClassic4k_4b] = + { + .name = "Mifare Classic 4k 4byte UID", + .handler = nfc_generate_mf_classic_4k_4b_uid, + }, + [NfcDataGeneratorTypeMfClassic4k_7b] = + { + .name = "Mifare Classic 4k 7byte UID", + .handler = nfc_generate_mf_classic_4k_7b_uid, + }, +}; + +const char* nfc_data_generator_get_name(NfcDataGeneratorType type) { + return nfc_data_generator[type].name; +} + +void nfc_data_generator_fill_data(NfcDataGeneratorType type, NfcDevice* nfc_device) { + nfc_data_generator[type].handler(nfc_device); +} diff --git a/lib/nfc/helpers/nfc_data_generator.h b/lib/nfc/helpers/nfc_data_generator.h new file mode 100644 index 000000000..01f5dac16 --- /dev/null +++ b/lib/nfc/helpers/nfc_data_generator.h @@ -0,0 +1,40 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + NfcDataGeneratorTypeMfUltralight, + NfcDataGeneratorTypeMfUltralightEV1_11, + NfcDataGeneratorTypeMfUltralightEV1_H11, + NfcDataGeneratorTypeMfUltralightEV1_21, + NfcDataGeneratorTypeMfUltralightEV1_H21, + NfcDataGeneratorTypeNTAG203, + NfcDataGeneratorTypeNTAG213, + NfcDataGeneratorTypeNTAG215, + NfcDataGeneratorTypeNTAG216, + NfcDataGeneratorTypeNTAGI2C1k, + NfcDataGeneratorTypeNTAGI2C2k, + NfcDataGeneratorTypeNTAGI2CPlus1k, + NfcDataGeneratorTypeNTAGI2CPlus2k, + + NfcDataGeneratorTypeMfClassicMini, + NfcDataGeneratorTypeMfClassic1k_4b, + NfcDataGeneratorTypeMfClassic1k_7b, + NfcDataGeneratorTypeMfClassic4k_4b, + NfcDataGeneratorTypeMfClassic4k_7b, + + NfcDataGeneratorTypeNum, + +} NfcDataGeneratorType; + +const char* nfc_data_generator_get_name(NfcDataGeneratorType type); + +void nfc_data_generator_fill_data(NfcDataGeneratorType type, NfcDevice* nfc_device); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/helpers/nfc_debug_log.c b/lib/nfc/helpers/nfc_debug_log.c deleted file mode 100644 index 0bfbc2c62..000000000 --- a/lib/nfc/helpers/nfc_debug_log.c +++ /dev/null @@ -1,71 +0,0 @@ -#include "nfc_debug_log.h" - -#include -#include - -#define TAG "NfcDebugLog" - -#define NFC_DEBUG_PCAP_FILENAME EXT_PATH("nfc/debug.txt") - -struct NfcDebugLog { - Stream* file_stream; - FuriString* data_str; -}; - -NfcDebugLog* nfc_debug_log_alloc() { - NfcDebugLog* instance = malloc(sizeof(NfcDebugLog)); - - Storage* storage = furi_record_open(RECORD_STORAGE); - instance->file_stream = buffered_file_stream_alloc(storage); - - if(!buffered_file_stream_open( - instance->file_stream, NFC_DEBUG_PCAP_FILENAME, FSAM_WRITE, FSOM_OPEN_APPEND)) { - buffered_file_stream_close(instance->file_stream); - stream_free(instance->file_stream); - instance->file_stream = NULL; - } - - if(!instance->file_stream) { - free(instance); - instance = NULL; - } else { - instance->data_str = furi_string_alloc(); - } - furi_record_close(RECORD_STORAGE); - - return instance; -} - -void nfc_debug_log_free(NfcDebugLog* instance) { - furi_assert(instance); - furi_assert(instance->file_stream); - furi_assert(instance->data_str); - - buffered_file_stream_close(instance->file_stream); - stream_free(instance->file_stream); - furi_string_free(instance->data_str); - - free(instance); -} - -void nfc_debug_log_process_data( - NfcDebugLog* instance, - uint8_t* data, - uint16_t len, - bool reader_to_tag, - bool crc_dropped) { - furi_assert(instance); - furi_assert(instance->file_stream); - furi_assert(instance->data_str); - furi_assert(data); - UNUSED(crc_dropped); - - furi_string_printf(instance->data_str, "%lu %c:", furi_get_tick(), reader_to_tag ? 'R' : 'T'); - uint16_t data_len = len; - for(size_t i = 0; i < data_len; i++) { - furi_string_cat_printf(instance->data_str, " %02x", data[i]); - } - furi_string_push_back(instance->data_str, '\n'); - - stream_write_string(instance->file_stream, instance->data_str); -} diff --git a/lib/nfc/helpers/nfc_debug_log.h b/lib/nfc/helpers/nfc_debug_log.h deleted file mode 100644 index 261b8008b..000000000 --- a/lib/nfc/helpers/nfc_debug_log.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include -#include - -typedef struct NfcDebugLog NfcDebugLog; - -NfcDebugLog* nfc_debug_log_alloc(); - -void nfc_debug_log_free(NfcDebugLog* instance); - -void nfc_debug_log_process_data( - NfcDebugLog* instance, - uint8_t* data, - uint16_t len, - bool reader_to_tag, - bool crc_dropped); diff --git a/lib/nfc/helpers/nfc_debug_pcap.c b/lib/nfc/helpers/nfc_debug_pcap.c deleted file mode 100644 index 6c7654ad5..000000000 --- a/lib/nfc/helpers/nfc_debug_pcap.c +++ /dev/null @@ -1,130 +0,0 @@ -#include "nfc_debug_pcap.h" - -#include -#include -#include -#include - -#define TAG "NfcDebugPcap" - -#define PCAP_MAGIC 0xa1b2c3d4 -#define PCAP_MAJOR 2 -#define PCAP_MINOR 4 -#define DLT_ISO_14443 264 - -#define DATA_PICC_TO_PCD 0xFF -#define DATA_PCD_TO_PICC 0xFE -#define DATA_PICC_TO_PCD_CRC_DROPPED 0xFB -#define DATA_PCD_TO_PICC_CRC_DROPPED 0xFA - -#define NFC_DEBUG_PCAP_FILENAME EXT_PATH("nfc/debug.pcap") - -struct NfcDebugPcap { - Stream* file_stream; -}; - -static Stream* nfc_debug_pcap_open(Storage* storage) { - Stream* stream = NULL; - stream = buffered_file_stream_alloc(storage); - if(!buffered_file_stream_open(stream, NFC_DEBUG_PCAP_FILENAME, FSAM_WRITE, FSOM_OPEN_APPEND)) { - buffered_file_stream_close(stream); - stream_free(stream); - stream = NULL; - } else { - if(!stream_tell(stream)) { - struct { - uint32_t magic; - uint16_t major, minor; - uint32_t reserved[2]; - uint32_t snaplen; - uint32_t link_type; - } __attribute__((__packed__)) pcap_hdr = { - .magic = PCAP_MAGIC, - .major = PCAP_MAJOR, - .minor = PCAP_MINOR, - .snaplen = FURI_HAL_NFC_DATA_BUFF_SIZE, - .link_type = DLT_ISO_14443, - }; - if(stream_write(stream, (uint8_t*)&pcap_hdr, sizeof(pcap_hdr)) != sizeof(pcap_hdr)) { - FURI_LOG_E(TAG, "Failed to write pcap header"); - buffered_file_stream_close(stream); - stream_free(stream); - stream = NULL; - } - } - } - return stream; -} - -NfcDebugPcap* nfc_debug_pcap_alloc() { - NfcDebugPcap* instance = malloc(sizeof(NfcDebugPcap)); - - Storage* storage = furi_record_open(RECORD_STORAGE); - instance->file_stream = nfc_debug_pcap_open(storage); - if(!instance->file_stream) { - free(instance); - instance = NULL; - } - furi_record_close(RECORD_STORAGE); - - return instance; -} - -void nfc_debug_pcap_free(NfcDebugPcap* instance) { - furi_assert(instance); - furi_assert(instance->file_stream); - - buffered_file_stream_close(instance->file_stream); - stream_free(instance->file_stream); - - free(instance); -} - -void nfc_debug_pcap_process_data( - NfcDebugPcap* instance, - uint8_t* data, - uint16_t len, - bool reader_to_tag, - bool crc_dropped) { - furi_assert(instance); - furi_assert(data); - FuriHalRtcDateTime datetime; - furi_hal_rtc_get_datetime(&datetime); - - uint8_t event = 0; - if(reader_to_tag) { - if(crc_dropped) { - event = DATA_PCD_TO_PICC_CRC_DROPPED; - } else { - event = DATA_PCD_TO_PICC; - } - } else { - if(crc_dropped) { - event = DATA_PICC_TO_PCD_CRC_DROPPED; - } else { - event = DATA_PICC_TO_PCD; - } - } - - struct { - // https://wiki.wireshark.org/Development/LibpcapFileFormat#record-packet-header - uint32_t ts_sec; - uint32_t ts_usec; - uint32_t incl_len; - uint32_t orig_len; - // https://www.kaiser.cx/posts/pcap-iso14443/#_packet_data - uint8_t version; - uint8_t event; - uint16_t len; - } __attribute__((__packed__)) pkt_hdr = { - .ts_sec = furi_hal_rtc_datetime_to_timestamp(&datetime), - .ts_usec = 0, - .incl_len = len + 4, - .orig_len = len + 4, - .version = 0, - .event = event, - .len = len << 8 | len >> 8, - }; - stream_write(instance->file_stream, (uint8_t*)&pkt_hdr, sizeof(pkt_hdr)); - stream_write(instance->file_stream, data, len); -} diff --git a/lib/nfc/helpers/nfc_debug_pcap.h b/lib/nfc/helpers/nfc_debug_pcap.h deleted file mode 100644 index eeddc5611..000000000 --- a/lib/nfc/helpers/nfc_debug_pcap.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include -#include - -typedef struct NfcDebugPcap NfcDebugPcap; - -NfcDebugPcap* nfc_debug_pcap_alloc(); - -void nfc_debug_pcap_free(NfcDebugPcap* instance); - -void nfc_debug_pcap_process_data( - NfcDebugPcap* instance, - uint8_t* data, - uint16_t len, - bool reader_to_tag, - bool crc_dropped); diff --git a/lib/nfc/helpers/nfc_dict.c b/lib/nfc/helpers/nfc_dict.c new file mode 100644 index 000000000..d4572a3d6 --- /dev/null +++ b/lib/nfc/helpers/nfc_dict.c @@ -0,0 +1,270 @@ +#include "nfc_dict.h" + +#include +#include +#include +#include +#include + +#include + +#define TAG "NfcDict" + +struct NfcDict { + Stream* stream; + size_t key_size; + size_t key_size_symbols; + uint32_t total_keys; +}; + +typedef struct { + const char* path; + FS_OpenMode open_mode; +} NfcDictFile; + +bool nfc_dict_check_presence(const char* path) { + furi_assert(path); + + Storage* storage = furi_record_open(RECORD_STORAGE); + + bool dict_present = storage_common_stat(storage, path, NULL) == FSE_OK; + + furi_record_close(RECORD_STORAGE); + + return dict_present; +} + +NfcDict* nfc_dict_alloc(const char* path, NfcDictMode mode, size_t key_size) { + furi_assert(path); + + NfcDict* instance = malloc(sizeof(NfcDict)); + Storage* storage = furi_record_open(RECORD_STORAGE); + instance->stream = buffered_file_stream_alloc(storage); + furi_record_close(RECORD_STORAGE); + + FS_OpenMode open_mode = FSOM_OPEN_EXISTING; + if(mode == NfcDictModeOpenAlways) { + open_mode = FSOM_OPEN_ALWAYS; + } + instance->key_size = key_size; + // Byte = 2 symbols + 1 end of line + instance->key_size_symbols = key_size * 2 + 1; + + bool dict_loaded = false; + do { + if(!buffered_file_stream_open(instance->stream, path, FSAM_READ_WRITE, open_mode)) { + buffered_file_stream_close(instance->stream); + break; + } + + // Check for new line ending + if(!stream_eof(instance->stream)) { + if(!stream_seek(instance->stream, -1, StreamOffsetFromEnd)) break; + uint8_t last_char = 0; + if(stream_read(instance->stream, &last_char, 1) != 1) break; + if(last_char != '\n') { + FURI_LOG_D(TAG, "Adding new line ending"); + if(stream_write_char(instance->stream, '\n') != 1) break; + } + if(!stream_rewind(instance->stream)) break; + } + + // Read total amount of keys + FuriString* next_line; + next_line = furi_string_alloc(); + while(true) { + if(!stream_read_line(instance->stream, next_line)) { + FURI_LOG_T(TAG, "No keys left in dict"); + break; + } + FURI_LOG_T( + TAG, + "Read line: %s, len: %zu", + furi_string_get_cstr(next_line), + furi_string_size(next_line)); + if(furi_string_get_char(next_line, 0) == '#') continue; + if(furi_string_size(next_line) != instance->key_size_symbols) continue; + instance->total_keys++; + } + furi_string_free(next_line); + stream_rewind(instance->stream); + + dict_loaded = true; + FURI_LOG_I(TAG, "Loaded dictionary with %lu keys", instance->total_keys); + } while(false); + + if(!dict_loaded) { + buffered_file_stream_close(instance->stream); + free(instance); + instance = NULL; + } + + return instance; +} + +void nfc_dict_free(NfcDict* instance) { + furi_assert(instance); + furi_assert(instance->stream); + + buffered_file_stream_close(instance->stream); + stream_free(instance->stream); + free(instance); +} + +static void nfc_dict_int_to_str(NfcDict* instance, const uint8_t* key_int, FuriString* key_str) { + furi_string_reset(key_str); + for(size_t i = 0; i < instance->key_size; i++) { + furi_string_cat_printf(key_str, "%02X", key_int[i]); + } +} + +static void nfc_dict_str_to_int(NfcDict* instance, FuriString* key_str, uint64_t* key_int) { + uint8_t key_byte_tmp; + + *key_int = 0ULL; + for(uint8_t i = 0; i < instance->key_size * 2; i += 2) { + args_char_to_hex( + furi_string_get_char(key_str, i), furi_string_get_char(key_str, i + 1), &key_byte_tmp); + *key_int |= (uint64_t)key_byte_tmp << (8 * (instance->key_size - 1 - i / 2)); + } +} + +uint32_t nfc_dict_get_total_keys(NfcDict* instance) { + furi_assert(instance); + + return instance->total_keys; +} + +bool nfc_dict_rewind(NfcDict* instance) { + furi_assert(instance); + furi_assert(instance->stream); + + return stream_rewind(instance->stream); +} + +static bool nfc_dict_get_next_key_str(NfcDict* instance, FuriString* key) { + furi_assert(instance); + furi_assert(instance->stream); + + bool key_read = false; + furi_string_reset(key); + while(!key_read) { + if(!stream_read_line(instance->stream, key)) break; + if(furi_string_get_char(key, 0) == '#') continue; + if(furi_string_size(key) != instance->key_size_symbols) continue; + furi_string_left(key, instance->key_size_symbols - 1); + key_read = true; + } + + return key_read; +} + +bool nfc_dict_get_next_key(NfcDict* instance, uint8_t* key, size_t key_size) { + furi_assert(instance); + furi_assert(instance->stream); + furi_assert(instance->key_size == key_size); + + FuriString* temp_key = furi_string_alloc(); + uint64_t key_int = 0; + bool key_read = nfc_dict_get_next_key_str(instance, temp_key); + if(key_read) { + nfc_dict_str_to_int(instance, temp_key, &key_int); + nfc_util_num2bytes(key_int, key_size, key); + } + furi_string_free(temp_key); + return key_read; +} + +static bool nfc_dict_is_key_present_str(NfcDict* instance, FuriString* key) { + furi_assert(instance); + furi_assert(instance->stream); + + FuriString* next_line; + next_line = furi_string_alloc(); + + bool key_found = false; + stream_rewind(instance->stream); + while(!key_found) { //-V654 + if(!stream_read_line(instance->stream, next_line)) break; + if(furi_string_get_char(next_line, 0) == '#') continue; + if(furi_string_size(next_line) != instance->key_size_symbols) continue; + furi_string_left(next_line, instance->key_size_symbols - 1); + if(!furi_string_equal(key, next_line)) continue; + key_found = true; + } + + furi_string_free(next_line); + return key_found; +} + +bool nfc_dict_is_key_present(NfcDict* instance, const uint8_t* key, size_t key_size) { + furi_assert(instance); + furi_assert(key); + furi_assert(instance->stream); + furi_assert(instance->key_size == key_size); + + FuriString* temp_key = furi_string_alloc(); + nfc_dict_int_to_str(instance, key, temp_key); + bool key_found = nfc_dict_is_key_present_str(instance, temp_key); + furi_string_free(temp_key); + + return key_found; +} + +static bool nfc_dict_add_key_str(NfcDict* instance, FuriString* key) { + furi_assert(instance); + furi_assert(instance->stream); + + furi_string_cat_printf(key, "\n"); + + bool key_added = false; + do { + if(!stream_seek(instance->stream, 0, StreamOffsetFromEnd)) break; + if(!stream_insert_string(instance->stream, key)) break; + instance->total_keys++; + key_added = true; + } while(false); + + furi_string_left(key, instance->key_size_symbols - 1); + return key_added; +} + +bool nfc_dict_add_key(NfcDict* instance, const uint8_t* key, size_t key_size) { + furi_assert(instance); + furi_assert(key); + furi_assert(instance->stream); + furi_assert(instance->key_size == key_size); + + FuriString* temp_key = furi_string_alloc(); + nfc_dict_int_to_str(instance, key, temp_key); + bool key_added = nfc_dict_add_key_str(instance, temp_key); + furi_string_free(temp_key); + + return key_added; +} + +bool nfc_dict_delete_key(NfcDict* instance, const uint8_t* key, size_t key_size) { + furi_assert(instance); + furi_assert(instance->stream); + furi_assert(key); + furi_assert(instance->key_size == key_size); + + bool key_removed = false; + uint8_t* temp_key = malloc(key_size); + + nfc_dict_rewind(instance); + while(!key_removed) { + if(!nfc_dict_get_next_key(instance, temp_key, key_size)) break; + if(memcmp(temp_key, key, key_size) == 0) { + int32_t offset = (-1) * (instance->key_size_symbols); + stream_seek(instance->stream, offset, StreamOffsetFromCurrent); + if(!stream_delete(instance->stream, instance->key_size_symbols)) break; + instance->total_keys--; + key_removed = true; + } + } + nfc_dict_rewind(instance); + free(temp_key); + + return key_removed; +} diff --git a/lib/nfc/helpers/nfc_dict.h b/lib/nfc/helpers/nfc_dict.h new file mode 100644 index 000000000..80f3ff680 --- /dev/null +++ b/lib/nfc/helpers/nfc_dict.h @@ -0,0 +1,103 @@ +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + NfcDictModeOpenExisting, + NfcDictModeOpenAlways, +} NfcDictMode; + +typedef struct NfcDict NfcDict; + +/** Check dictionary presence + * + * @param path - dictionary path + * + * @return true if dictionary exists, false otherwise +*/ +bool nfc_dict_check_presence(const char* path); + +/** Open or create dictionary + * Depending on mode, dictionary will be opened or created. + * + * @param path - dictionary path + * @param mode - NfcDictMode value + * @param key_size - size of dictionary keys in bytes + * + * @return NfcDict dictionary instance +*/ +NfcDict* nfc_dict_alloc(const char* path, NfcDictMode mode, size_t key_size); + +/** Close dictionary + * + * @param instance - NfcDict dictionary instance +*/ +void nfc_dict_free(NfcDict* instance); + +/** Get total number of keys in dictionary + * + * @param instance - NfcDict dictionary instance + * + * @return total number of keys in dictionary +*/ +uint32_t nfc_dict_get_total_keys(NfcDict* instance); + +/** Rewind dictionary + * + * @param instance - NfcDict dictionary instance + * + * @return true if rewind was successful, false otherwise +*/ +bool nfc_dict_rewind(NfcDict* instance); + +/** Check if key is present in dictionary + * + * @param instance - NfcDict dictionary instance + * @param key - key to check + * @param key_size - size of key in bytes + * + * @return true if key is present, false otherwise +*/ +bool nfc_dict_is_key_present(NfcDict* instance, const uint8_t* key, size_t key_size); + +/** Get next key from dictionary + * This function will return next key from dictionary. If there are no more + * keys, it will return false, and nfc_dict_rewind() should be called. + * + * @param instance - NfcDict dictionary instance + * @param key - buffer to store key + * @param key_size - size of key in bytes + * + * @return true if key was successfully retrieved, false otherwise +*/ +bool nfc_dict_get_next_key(NfcDict* instance, uint8_t* key, size_t key_size); + +/** Add key to dictionary + * + * @param instance - NfcDict dictionary instance + * @param key - key to add + * @param key_size - size of key in bytes + * + * @return true if key was successfully added, false otherwise +*/ +bool nfc_dict_add_key(NfcDict* instance, const uint8_t* key, size_t key_size); + +/** Delete key from dictionary + * + * @param instance - NfcDict dictionary instance + * @param key - key to delete + * @param key_size - size of key in bytes + * + * @return true if key was successfully deleted, false otherwise +*/ +bool nfc_dict_delete_key(NfcDict* instance, const uint8_t* key, size_t key_size); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/helpers/nfc_generators.c b/lib/nfc/helpers/nfc_generators.c deleted file mode 100644 index 11148577c..000000000 --- a/lib/nfc/helpers/nfc_generators.c +++ /dev/null @@ -1,548 +0,0 @@ -#include -#include "nfc_generators.h" - -#define NXP_MANUFACTURER_ID (0x04) - -static const uint8_t version_bytes_mf0ulx1[] = {0x00, 0x04, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03}; -static const uint8_t version_bytes_ntag21x[] = {0x00, 0x04, 0x04, 0x02, 0x01, 0x00, 0x00, 0x03}; -static const uint8_t version_bytes_ntag_i2c[] = {0x00, 0x04, 0x04, 0x05, 0x02, 0x00, 0x00, 0x03}; -static const uint8_t default_data_ntag203[] = - {0xE1, 0x10, 0x12, 0x00, 0x01, 0x03, 0xA0, 0x10, 0x44, 0x03, 0x00, 0xFE}; -static const uint8_t default_data_ntag213[] = {0x01, 0x03, 0xA0, 0x0C, 0x34, 0x03, 0x00, 0xFE}; -static const uint8_t default_data_ntag215_216[] = {0x03, 0x00, 0xFE}; -static const uint8_t default_data_ntag_i2c[] = {0xE1, 0x10, 0x00, 0x00, 0x03, 0x00, 0xFE}; -static const uint8_t default_config_ntag_i2c[] = {0x01, 0x00, 0xF8, 0x48, 0x08, 0x01, 0x00, 0x00}; - -static void nfc_generate_common_start(NfcDeviceData* data) { - nfc_device_data_clear(data); -} - -static void nfc_generate_mf_ul_uid(uint8_t* uid) { - uid[0] = NXP_MANUFACTURER_ID; - furi_hal_random_fill_buf(&uid[1], 6); - // I'm not sure how this is generated, but the upper nybble always seems to be 8 - uid[6] &= 0x0F; - uid[6] |= 0x80; -} - -static void nfc_generate_mf_classic_uid(uint8_t* uid, uint8_t length) { - uid[0] = NXP_MANUFACTURER_ID; - furi_hal_random_fill_buf(&uid[1], length - 1); -} - -static void nfc_generate_mf_classic_block_0( - uint8_t* block, - uint8_t uid_len, - uint8_t sak, - uint8_t atqa0, - uint8_t atqa1) { - // Block length is always 16 bytes, and the UID can be either 4 or 7 bytes - furi_assert(uid_len == 4 || uid_len == 7); - furi_assert(block); - - if(uid_len == 4) { - // Calculate BCC - block[uid_len] = 0; - - for(int i = 0; i < uid_len; i++) { - block[uid_len] ^= block[i]; - } - } else { - uid_len -= 1; - } - - block[uid_len + 1] = sak; - block[uid_len + 2] = atqa0; - block[uid_len + 3] = atqa1; - - for(int i = uid_len + 4; i < 16; i++) { - block[i] = 0xFF; - } -} - -static void nfc_generate_mf_classic_sector_trailer(MfClassicData* data, uint8_t block) { - // All keys are set to FFFF FFFF FFFFh at chip delivery and the bytes 6, 7 and 8 are set to FF0780h. - MfClassicSectorTrailer* sec_tr = (MfClassicSectorTrailer*)data->block[block].value; - sec_tr->access_bits[0] = 0xFF; - sec_tr->access_bits[1] = 0x07; - sec_tr->access_bits[2] = 0x80; - sec_tr->access_bits[3] = 0x69; // Nice - - memset(sec_tr->key_a, 0xff, sizeof(sec_tr->key_a)); - memset(sec_tr->key_b, 0xff, sizeof(sec_tr->key_b)); - - mf_classic_set_block_read(data, block, &data->block[block]); - mf_classic_set_key_found( - data, mf_classic_get_sector_by_block(block), MfClassicKeyA, 0xFFFFFFFFFFFF); - mf_classic_set_key_found( - data, mf_classic_get_sector_by_block(block), MfClassicKeyB, 0xFFFFFFFFFFFF); -} - -static void nfc_generate_mf_ul_common(NfcDeviceData* data) { - data->nfc_data.type = FuriHalNfcTypeA; - data->nfc_data.interface = FuriHalNfcInterfaceRf; - data->nfc_data.uid_len = 7; - nfc_generate_mf_ul_uid(data->nfc_data.uid); - data->nfc_data.atqa[0] = 0x44; - data->nfc_data.atqa[1] = 0x00; - data->nfc_data.sak = 0x00; - data->protocol = NfcDeviceProtocolMifareUl; -} - -static void - nfc_generate_mf_classic_common(NfcDeviceData* data, uint8_t uid_len, MfClassicType type) { - data->nfc_data.type = FuriHalNfcTypeA; - data->nfc_data.interface = FuriHalNfcInterfaceRf; - data->nfc_data.uid_len = uid_len; - data->nfc_data.atqa[0] = 0x44; - data->nfc_data.atqa[1] = 0x00; - data->nfc_data.sak = 0x08; - data->protocol = NfcDeviceProtocolMifareClassic; - data->mf_classic_data.type = type; -} - -static void nfc_generate_calc_bcc(uint8_t* uid, uint8_t* bcc0, uint8_t* bcc1) { - *bcc0 = 0x88 ^ uid[0] ^ uid[1] ^ uid[2]; - *bcc1 = uid[3] ^ uid[4] ^ uid[5] ^ uid[6]; -} - -static void nfc_generate_mf_ul_copy_uid_with_bcc(NfcDeviceData* data) { - MfUltralightData* mful = &data->mf_ul_data; - memcpy(mful->data, data->nfc_data.uid, 3); - memcpy(&mful->data[4], &data->nfc_data.uid[3], 4); - nfc_generate_calc_bcc(data->nfc_data.uid, &mful->data[3], &mful->data[8]); -} - -static void nfc_generate_mf_ul_orig(NfcDeviceData* data) { - nfc_generate_common_start(data); - nfc_generate_mf_ul_common(data); - - MfUltralightData* mful = &data->mf_ul_data; - mful->type = MfUltralightTypeUnknown; - mful->data_size = 16 * 4; - mful->data_read = mful->data_size; - nfc_generate_mf_ul_copy_uid_with_bcc(data); - // TODO: what's internal byte on page 2? - memset(&mful->data[4 * 4], 0xFF, 4); -} - -static void nfc_generate_mf_ul_ntag203(NfcDeviceData* data) { - nfc_generate_common_start(data); - nfc_generate_mf_ul_common(data); - - MfUltralightData* mful = &data->mf_ul_data; - mful->type = MfUltralightTypeNTAG203; - mful->data_size = 42 * 4; - mful->data_read = mful->data_size; - nfc_generate_mf_ul_copy_uid_with_bcc(data); - mful->data[9] = 0x48; // Internal byte - memcpy(&mful->data[3 * 4], default_data_ntag203, sizeof(default_data_ntag203)); -} - -static void nfc_generate_mf_ul_with_config_common(NfcDeviceData* data, uint8_t num_pages) { - nfc_generate_common_start(data); - nfc_generate_mf_ul_common(data); - - MfUltralightData* mful = &data->mf_ul_data; - mful->data_size = num_pages * 4; - mful->data_read = mful->data_size; - nfc_generate_mf_ul_copy_uid_with_bcc(data); - uint16_t config_index = (num_pages - 4) * 4; - mful->data[config_index] = 0x04; // STRG_MOD_EN - mful->data[config_index + 3] = 0xFF; // AUTH0 - mful->data[config_index + 5] = 0x05; // VCTID - memset(&mful->data[config_index + 8], 0xFF, 4); // Default PWD - if(num_pages > 20) mful->data[config_index - 1] = MF_UL_TEARING_FLAG_DEFAULT; -} - -static void nfc_generate_mf_ul_ev1_common(NfcDeviceData* data, uint8_t num_pages) { - nfc_generate_mf_ul_with_config_common(data, num_pages); - MfUltralightData* mful = &data->mf_ul_data; - memcpy(&mful->version, version_bytes_mf0ulx1, sizeof(version_bytes_mf0ulx1)); - for(size_t i = 0; i < 3; ++i) { - mful->tearing[i] = MF_UL_TEARING_FLAG_DEFAULT; - } - // TODO: what's internal byte on page 2? -} - -static void nfc_generate_mf_ul_11(NfcDeviceData* data) { - nfc_generate_mf_ul_ev1_common(data, 20); - MfUltralightData* mful = &data->mf_ul_data; - mful->type = MfUltralightTypeUL11; - mful->version.prod_subtype = 0x01; - mful->version.storage_size = 0x0B; - mful->data[16 * 4] = 0x00; // Low capacitance version does not have STRG_MOD_EN -} - -static void nfc_generate_mf_ul_h11(NfcDeviceData* data) { - nfc_generate_mf_ul_ev1_common(data, 20); - MfUltralightData* mful = &data->mf_ul_data; - mful->type = MfUltralightTypeUL11; - mful->version.prod_subtype = 0x02; - mful->version.storage_size = 0x0B; -} - -static void nfc_generate_mf_ul_21(NfcDeviceData* data) { - nfc_generate_mf_ul_ev1_common(data, 41); - MfUltralightData* mful = &data->mf_ul_data; - mful->type = MfUltralightTypeUL21; - mful->version.prod_subtype = 0x01; - mful->version.storage_size = 0x0E; - mful->data[37 * 4] = 0x00; // Low capacitance version does not have STRG_MOD_EN -} - -static void nfc_generate_mf_ul_h21(NfcDeviceData* data) { - nfc_generate_mf_ul_ev1_common(data, 41); - MfUltralightData* mful = &data->mf_ul_data; - mful->type = MfUltralightTypeUL21; - mful->version.prod_subtype = 0x02; - mful->version.storage_size = 0x0E; -} - -static void nfc_generate_ntag21x_common(NfcDeviceData* data, uint8_t num_pages) { - nfc_generate_mf_ul_with_config_common(data, num_pages); - MfUltralightData* mful = &data->mf_ul_data; - memcpy(&mful->version, version_bytes_ntag21x, sizeof(version_bytes_mf0ulx1)); - mful->data[9] = 0x48; // Internal byte - // Capability container - mful->data[12] = 0xE1; - mful->data[13] = 0x10; -} - -static void nfc_generate_ntag213(NfcDeviceData* data) { - nfc_generate_ntag21x_common(data, 45); - MfUltralightData* mful = &data->mf_ul_data; - mful->type = MfUltralightTypeNTAG213; - mful->version.storage_size = 0x0F; - mful->data[14] = 0x12; - // Default contents - memcpy(&mful->data[16], default_data_ntag213, sizeof(default_data_ntag213)); -} - -static void nfc_generate_ntag215(NfcDeviceData* data) { - nfc_generate_ntag21x_common(data, 135); - MfUltralightData* mful = &data->mf_ul_data; - mful->type = MfUltralightTypeNTAG215; - mful->version.storage_size = 0x11; - mful->data[14] = 0x3E; - // Default contents - memcpy(&mful->data[16], default_data_ntag215_216, sizeof(default_data_ntag215_216)); -} - -static void nfc_generate_ntag216(NfcDeviceData* data) { - nfc_generate_ntag21x_common(data, 231); - MfUltralightData* mful = &data->mf_ul_data; - mful->type = MfUltralightTypeNTAG216; - mful->version.storage_size = 0x13; - mful->data[14] = 0x6D; - // Default contents - memcpy(&mful->data[16], default_data_ntag215_216, sizeof(default_data_ntag215_216)); -} - -static void - nfc_generate_ntag_i2c_common(NfcDeviceData* data, MfUltralightType type, uint16_t num_pages) { - nfc_generate_common_start(data); - nfc_generate_mf_ul_common(data); - - MfUltralightData* mful = &data->mf_ul_data; - mful->type = type; - memcpy(&mful->version, version_bytes_ntag_i2c, sizeof(version_bytes_ntag_i2c)); - mful->data_size = num_pages * 4; - mful->data_read = mful->data_size; - memcpy(mful->data, data->nfc_data.uid, data->nfc_data.uid_len); - mful->data[7] = data->nfc_data.sak; - mful->data[8] = data->nfc_data.atqa[0]; - mful->data[9] = data->nfc_data.atqa[1]; - - uint16_t config_register_page; - uint16_t session_register_page; - - // Sync with mifare_ultralight.c - switch(type) { - case MfUltralightTypeNTAGI2C1K: - config_register_page = 227; - session_register_page = 229; - break; - case MfUltralightTypeNTAGI2C2K: - config_register_page = 481; - session_register_page = 483; - break; - case MfUltralightTypeNTAGI2CPlus1K: - case MfUltralightTypeNTAGI2CPlus2K: - config_register_page = 232; - session_register_page = 234; - break; - default: - furi_crash("Unknown MFUL"); - break; - } - - memcpy( - &mful->data[config_register_page * 4], - default_config_ntag_i2c, - sizeof(default_config_ntag_i2c)); - memcpy( - &mful->data[session_register_page * 4], - default_config_ntag_i2c, - sizeof(default_config_ntag_i2c)); -} - -static void nfc_generate_ntag_i2c_1k(NfcDeviceData* data) { - nfc_generate_ntag_i2c_common(data, MfUltralightTypeNTAGI2C1K, 231); - MfUltralightData* mful = &data->mf_ul_data; - mful->version.prod_ver_minor = 0x01; - mful->version.storage_size = 0x13; - - memcpy(&mful->data[12], default_data_ntag_i2c, sizeof(default_data_ntag_i2c)); - mful->data[14] = 0x6D; // Size of tag in CC -} - -static void nfc_generate_ntag_i2c_2k(NfcDeviceData* data) { - nfc_generate_ntag_i2c_common(data, MfUltralightTypeNTAGI2C2K, 485); - MfUltralightData* mful = &data->mf_ul_data; - mful->version.prod_ver_minor = 0x01; - mful->version.storage_size = 0x15; - - memcpy(&mful->data[12], default_data_ntag_i2c, sizeof(default_data_ntag_i2c)); - mful->data[14] = 0xEA; // Size of tag in CC -} - -static void nfc_generate_ntag_i2c_plus_common( - NfcDeviceData* data, - MfUltralightType type, - uint16_t num_pages) { - nfc_generate_ntag_i2c_common(data, type, num_pages); - - MfUltralightData* mful = &data->mf_ul_data; - uint16_t config_index = 227 * 4; - mful->data[config_index + 3] = 0xFF; // AUTH0 - memset(&mful->data[config_index + 8], 0xFF, 4); // Default PWD -} - -static void nfc_generate_ntag_i2c_plus_1k(NfcDeviceData* data) { - nfc_generate_ntag_i2c_plus_common(data, MfUltralightTypeNTAGI2CPlus1K, 236); - MfUltralightData* mful = &data->mf_ul_data; - mful->version.prod_ver_minor = 0x02; - mful->version.storage_size = 0x13; -} - -static void nfc_generate_ntag_i2c_plus_2k(NfcDeviceData* data) { - nfc_generate_ntag_i2c_plus_common(data, MfUltralightTypeNTAGI2CPlus2K, 492); - MfUltralightData* mful = &data->mf_ul_data; - mful->version.prod_ver_minor = 0x02; - mful->version.storage_size = 0x15; -} - -void nfc_generate_mf_classic_ext( - NfcDeviceData* data, - uint8_t uid_len, - MfClassicType type, - bool random_uid, - uint8_t* uid) { - nfc_generate_common_start(data); - if(random_uid) { - nfc_generate_mf_classic_uid(data->mf_classic_data.block[0].value, uid_len); - } else { - memcpy(data->mf_classic_data.block[0].value, uid, uid_len); - } - nfc_generate_mf_classic_common(data, uid_len, type); - - // Set the UID - if(random_uid) { - data->nfc_data.uid[0] = NXP_MANUFACTURER_ID; - for(int i = 1; i < uid_len; i++) { - data->nfc_data.uid[i] = data->mf_classic_data.block[0].value[i]; - } - } else { - for(int i = 0; i < uid_len; i++) { - data->nfc_data.uid[i] = data->mf_classic_data.block[0].value[i]; - } - } - - MfClassicData* mfc = &data->mf_classic_data; - mf_classic_set_block_read(mfc, 0, &mfc->block[0]); - - if(type == MfClassicType4k) { - // Set every block to 0xFF - for(uint16_t i = 1; i < 256; i += 1) { - if(mf_classic_is_sector_trailer(i)) { - nfc_generate_mf_classic_sector_trailer(mfc, i); - } else { - memset(&mfc->block[i].value, 0xFF, 16); - } - mf_classic_set_block_read(mfc, i, &mfc->block[i]); - } - // Set SAK to 18 - data->nfc_data.sak = 0x18; - } else if(type == MfClassicType1k) { - // Set every block to 0xFF - for(uint16_t i = 1; i < MF_CLASSIC_1K_TOTAL_SECTORS_NUM * 4; i += 1) { - if(mf_classic_is_sector_trailer(i)) { - nfc_generate_mf_classic_sector_trailer(mfc, i); - } else { - memset(&mfc->block[i].value, 0xFF, 16); - } - mf_classic_set_block_read(mfc, i, &mfc->block[i]); - } - // Set SAK to 08 - data->nfc_data.sak = 0x08; - } else if(type == MfClassicTypeMini) { - // Set every block to 0xFF - for(uint16_t i = 1; i < MF_MINI_TOTAL_SECTORS_NUM * 4; i += 1) { - if(mf_classic_is_sector_trailer(i)) { - nfc_generate_mf_classic_sector_trailer(mfc, i); - } else { - memset(&mfc->block[i].value, 0xFF, 16); - } - mf_classic_set_block_read(mfc, i, &mfc->block[i]); - } - // Set SAK to 09 - data->nfc_data.sak = 0x09; - } - - nfc_generate_mf_classic_block_0( - data->mf_classic_data.block[0].value, - uid_len, - data->nfc_data.sak, - data->nfc_data.atqa[0], - data->nfc_data.atqa[1]); - - mfc->type = type; -} - -void nfc_generate_mf_classic(NfcDeviceData* data, uint8_t uid_len, MfClassicType type) { - uint8_t uid = 0; - nfc_generate_mf_classic_ext(data, uid_len, type, true, &uid); -} - -static void nfc_generate_mf_mini(NfcDeviceData* data) { - nfc_generate_mf_classic(data, 4, MfClassicTypeMini); -} - -static void nfc_generate_mf_classic_1k_4b_uid(NfcDeviceData* data) { - nfc_generate_mf_classic(data, 4, MfClassicType1k); -} - -static void nfc_generate_mf_classic_1k_7b_uid(NfcDeviceData* data) { - nfc_generate_mf_classic(data, 7, MfClassicType1k); -} - -static void nfc_generate_mf_classic_4k_4b_uid(NfcDeviceData* data) { - nfc_generate_mf_classic(data, 4, MfClassicType4k); -} - -static void nfc_generate_mf_classic_4k_7b_uid(NfcDeviceData* data) { - nfc_generate_mf_classic(data, 7, MfClassicType4k); -} - -static const NfcGenerator mf_ul_generator = { - .name = "Mifare Ultralight", - .generator_func = nfc_generate_mf_ul_orig, -}; - -static const NfcGenerator mf_ul_11_generator = { - .name = "Mifare Ultralight EV1 11", - .generator_func = nfc_generate_mf_ul_11, -}; - -static const NfcGenerator mf_ul_h11_generator = { - .name = "Mifare Ultralight EV1 H11", - .generator_func = nfc_generate_mf_ul_h11, -}; - -static const NfcGenerator mf_ul_21_generator = { - .name = "Mifare Ultralight EV1 21", - .generator_func = nfc_generate_mf_ul_21, -}; - -static const NfcGenerator mf_ul_h21_generator = { - .name = "Mifare Ultralight EV1 H21", - .generator_func = nfc_generate_mf_ul_h21, -}; - -static const NfcGenerator ntag203_generator = { - .name = "NTAG203", - .generator_func = nfc_generate_mf_ul_ntag203, -}; - -static const NfcGenerator ntag213_generator = { - .name = "NTAG213", - .generator_func = nfc_generate_ntag213, -}; - -static const NfcGenerator ntag215_generator = { - .name = "NTAG215", - .generator_func = nfc_generate_ntag215, -}; - -static const NfcGenerator ntag216_generator = { - .name = "NTAG216", - .generator_func = nfc_generate_ntag216, -}; - -static const NfcGenerator ntag_i2c_1k_generator = { - .name = "NTAG I2C 1k", - .generator_func = nfc_generate_ntag_i2c_1k, -}; - -static const NfcGenerator ntag_i2c_2k_generator = { - .name = "NTAG I2C 2k", - .generator_func = nfc_generate_ntag_i2c_2k, -}; - -static const NfcGenerator ntag_i2c_plus_1k_generator = { - .name = "NTAG I2C Plus 1k", - .generator_func = nfc_generate_ntag_i2c_plus_1k, -}; - -static const NfcGenerator ntag_i2c_plus_2k_generator = { - .name = "NTAG I2C Plus 2k", - .generator_func = nfc_generate_ntag_i2c_plus_2k, -}; - -static const NfcGenerator mifare_mini_generator = { - .name = "Mifare Mini", - .generator_func = nfc_generate_mf_mini, -}; - -static const NfcGenerator mifare_classic_1k_4b_uid_generator = { - .name = "Mifare Classic 1k 4byte UID", - .generator_func = nfc_generate_mf_classic_1k_4b_uid, -}; - -static const NfcGenerator mifare_classic_1k_7b_uid_generator = { - .name = "Mifare Classic 1k 7byte UID", - .generator_func = nfc_generate_mf_classic_1k_7b_uid, -}; - -static const NfcGenerator mifare_classic_4k_4b_uid_generator = { - .name = "Mifare Classic 4k 4byte UID", - .generator_func = nfc_generate_mf_classic_4k_4b_uid, -}; - -static const NfcGenerator mifare_classic_4k_7b_uid_generator = { - .name = "Mifare Classic 4k 7byte UID", - .generator_func = nfc_generate_mf_classic_4k_7b_uid, -}; - -const NfcGenerator* const nfc_generators[] = { - &mf_ul_generator, - &mf_ul_11_generator, - &mf_ul_h11_generator, - &mf_ul_21_generator, - &mf_ul_h21_generator, - &ntag203_generator, - &ntag213_generator, - &ntag215_generator, - &ntag216_generator, - &ntag_i2c_1k_generator, - &ntag_i2c_2k_generator, - &ntag_i2c_plus_1k_generator, - &ntag_i2c_plus_2k_generator, - &mifare_mini_generator, - &mifare_classic_1k_4b_uid_generator, - &mifare_classic_1k_7b_uid_generator, - &mifare_classic_4k_4b_uid_generator, - &mifare_classic_4k_7b_uid_generator, - NULL, -}; diff --git a/lib/nfc/helpers/nfc_generators.h b/lib/nfc/helpers/nfc_generators.h deleted file mode 100644 index 5102d0bc3..000000000 --- a/lib/nfc/helpers/nfc_generators.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include "../nfc_device.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void (*NfcGeneratorFunc)(NfcDeviceData* data); - -typedef struct { - const char* name; - NfcGeneratorFunc generator_func; -} NfcGenerator; - -extern const NfcGenerator* const nfc_generators[]; - -void nfc_generate_mf_classic(NfcDeviceData* data, uint8_t uid_len, MfClassicType type); - -void nfc_generate_mf_classic_ext( - NfcDeviceData* data, - uint8_t uid_len, - MfClassicType type, - bool random_uid, - uint8_t* uid); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/lib/nfc/protocols/nfc_util.c b/lib/nfc/helpers/nfc_util.c similarity index 100% rename from lib/nfc/protocols/nfc_util.c rename to lib/nfc/helpers/nfc_util.c diff --git a/lib/nfc/protocols/nfc_util.h b/lib/nfc/helpers/nfc_util.h similarity index 100% rename from lib/nfc/protocols/nfc_util.h rename to lib/nfc/helpers/nfc_util.h diff --git a/lib/nfc/helpers/reader_analyzer.c b/lib/nfc/helpers/reader_analyzer.c deleted file mode 100644 index 9bf37a60d..000000000 --- a/lib/nfc/helpers/reader_analyzer.c +++ /dev/null @@ -1,265 +0,0 @@ -#include "reader_analyzer.h" -#include -#include -#include - -#include "mfkey32.h" -#include "nfc_debug_pcap.h" -#include "nfc_debug_log.h" - -#define TAG "ReaderAnalyzer" - -#define READER_ANALYZER_MAX_BUFF_SIZE (1024) - -typedef struct { - bool reader_to_tag; - bool crc_dropped; - uint16_t len; -} ReaderAnalyzerHeader; - -typedef enum { - ReaderAnalyzerNfcDataMfClassic, -} ReaderAnalyzerNfcData; - -struct ReaderAnalyzer { - FuriHalNfcDevData nfc_data; - - bool alive; - FuriStreamBuffer* stream; - FuriThread* thread; - - ReaderAnalyzerParseDataCallback callback; - void* context; - - ReaderAnalyzerMode mode; - Mfkey32* mfkey32; - NfcDebugLog* debug_log; - NfcDebugPcap* pcap; -}; - -const FuriHalNfcDevData reader_analyzer_nfc_data[] = { - [ReaderAnalyzerNfcDataMfClassic] = - {.sak = 0x08, - .atqa = {0x44, 0x00}, - .interface = FuriHalNfcInterfaceRf, - .type = FuriHalNfcTypeA, - .uid_len = 7, - .uid = {0x04, 0x77, 0x70, 0x2A, 0x23, 0x4F, 0x80}, - .cuid = 0x2A234F80}, -}; - -void reader_analyzer_parse(ReaderAnalyzer* instance, uint8_t* buffer, size_t size) { - if(size < sizeof(ReaderAnalyzerHeader)) return; - - size_t bytes_i = 0; - while(bytes_i < size) { - ReaderAnalyzerHeader* header = (ReaderAnalyzerHeader*)&buffer[bytes_i]; - uint16_t len = header->len; - if(bytes_i + len > size) break; - bytes_i += sizeof(ReaderAnalyzerHeader); - if(instance->mfkey32) { - mfkey32_process_data( - instance->mfkey32, - &buffer[bytes_i], - len, - header->reader_to_tag, - header->crc_dropped); - } - if(instance->pcap) { - nfc_debug_pcap_process_data( - instance->pcap, &buffer[bytes_i], len, header->reader_to_tag, header->crc_dropped); - } - if(instance->debug_log) { - nfc_debug_log_process_data( - instance->debug_log, - &buffer[bytes_i], - len, - header->reader_to_tag, - header->crc_dropped); - } - bytes_i += len; - } -} - -int32_t reader_analyzer_thread(void* context) { - ReaderAnalyzer* reader_analyzer = context; - uint8_t buffer[READER_ANALYZER_MAX_BUFF_SIZE] = {}; - - while(reader_analyzer->alive || !furi_stream_buffer_is_empty(reader_analyzer->stream)) { - size_t ret = furi_stream_buffer_receive( - reader_analyzer->stream, buffer, READER_ANALYZER_MAX_BUFF_SIZE, 50); - if(ret) { - reader_analyzer_parse(reader_analyzer, buffer, ret); - } - } - - return 0; -} - -ReaderAnalyzer* reader_analyzer_alloc() { - ReaderAnalyzer* instance = malloc(sizeof(ReaderAnalyzer)); - - instance->nfc_data = reader_analyzer_nfc_data[ReaderAnalyzerNfcDataMfClassic]; - instance->alive = false; - instance->stream = - furi_stream_buffer_alloc(READER_ANALYZER_MAX_BUFF_SIZE, sizeof(ReaderAnalyzerHeader)); - - instance->thread = - furi_thread_alloc_ex("ReaderAnalyzerWorker", 2048, reader_analyzer_thread, instance); - furi_thread_set_priority(instance->thread, FuriThreadPriorityLow); - - return instance; -} - -static void reader_analyzer_mfkey_callback(Mfkey32Event event, void* context) { - furi_assert(context); - ReaderAnalyzer* instance = context; - - if(event == Mfkey32EventParamCollected) { - if(instance->callback) { - instance->callback(ReaderAnalyzerEventMfkeyCollected, instance->context); - } - } -} - -void reader_analyzer_start(ReaderAnalyzer* instance, ReaderAnalyzerMode mode) { - furi_assert(instance); - - furi_stream_buffer_reset(instance->stream); - if(mode & ReaderAnalyzerModeDebugLog) { - instance->debug_log = nfc_debug_log_alloc(); - } - if(mode & ReaderAnalyzerModeMfkey) { - instance->mfkey32 = mfkey32_alloc(instance->nfc_data.cuid); - if(instance->mfkey32) { - mfkey32_set_callback(instance->mfkey32, reader_analyzer_mfkey_callback, instance); - } - } - if(mode & ReaderAnalyzerModeDebugPcap) { - instance->pcap = nfc_debug_pcap_alloc(); - } - - instance->alive = true; - furi_thread_start(instance->thread); -} - -void reader_analyzer_stop(ReaderAnalyzer* instance) { - furi_assert(instance); - - instance->alive = false; - furi_thread_join(instance->thread); - - if(instance->debug_log) { - nfc_debug_log_free(instance->debug_log); - instance->debug_log = NULL; - } - if(instance->mfkey32) { - mfkey32_free(instance->mfkey32); - instance->mfkey32 = NULL; - } - if(instance->pcap) { - nfc_debug_pcap_free(instance->pcap); - instance->pcap = NULL; - } -} - -void reader_analyzer_free(ReaderAnalyzer* instance) { - furi_assert(instance); - - reader_analyzer_stop(instance); - furi_thread_free(instance->thread); - furi_stream_buffer_free(instance->stream); - free(instance); -} - -void reader_analyzer_set_callback( - ReaderAnalyzer* instance, - ReaderAnalyzerParseDataCallback callback, - void* context) { - furi_assert(instance); - furi_assert(callback); - - instance->callback = callback; - instance->context = context; -} - -NfcProtocol - reader_analyzer_guess_protocol(ReaderAnalyzer* instance, uint8_t* buff_rx, uint16_t len) { - furi_assert(instance); - furi_assert(buff_rx); - UNUSED(len); - NfcProtocol protocol = NfcDeviceProtocolUnknown; - - if((buff_rx[0] == 0x60) || (buff_rx[0] == 0x61)) { - protocol = NfcDeviceProtocolMifareClassic; - } - - return protocol; -} - -FuriHalNfcDevData* reader_analyzer_get_nfc_data(ReaderAnalyzer* instance) { - furi_assert(instance); - instance->nfc_data = reader_analyzer_nfc_data[ReaderAnalyzerNfcDataMfClassic]; - return &instance->nfc_data; -} - -void reader_analyzer_set_nfc_data(ReaderAnalyzer* instance, FuriHalNfcDevData* nfc_data) { - furi_assert(instance); - furi_assert(nfc_data); - - memcpy(&instance->nfc_data, nfc_data, sizeof(FuriHalNfcDevData)); -} - -static void reader_analyzer_write( - ReaderAnalyzer* instance, - uint8_t* data, - uint16_t len, - bool reader_to_tag, - bool crc_dropped) { - ReaderAnalyzerHeader header = { - .reader_to_tag = reader_to_tag, .crc_dropped = crc_dropped, .len = len}; - size_t data_sent = 0; - data_sent = furi_stream_buffer_send( - instance->stream, &header, sizeof(ReaderAnalyzerHeader), FuriWaitForever); - if(data_sent != sizeof(ReaderAnalyzerHeader)) { - FURI_LOG_W(TAG, "Sent %zu out of %zu bytes", data_sent, sizeof(ReaderAnalyzerHeader)); - } - data_sent = furi_stream_buffer_send(instance->stream, data, len, FuriWaitForever); - if(data_sent != len) { - FURI_LOG_W(TAG, "Sent %zu out of %u bytes", data_sent, len); - } -} - -static void - reader_analyzer_write_rx(uint8_t* data, uint16_t bits, bool crc_dropped, void* context) { - UNUSED(crc_dropped); - ReaderAnalyzer* reader_analyzer = context; - uint16_t bytes = bits < 8 ? 1 : bits / 8; - reader_analyzer_write(reader_analyzer, data, bytes, false, crc_dropped); -} - -static void - reader_analyzer_write_tx(uint8_t* data, uint16_t bits, bool crc_dropped, void* context) { - UNUSED(crc_dropped); - ReaderAnalyzer* reader_analyzer = context; - uint16_t bytes = bits < 8 ? 1 : bits / 8; - reader_analyzer_write(reader_analyzer, data, bytes, true, crc_dropped); -} - -void reader_analyzer_prepare_tx_rx( - ReaderAnalyzer* instance, - FuriHalNfcTxRxContext* tx_rx, - bool is_picc) { - furi_assert(instance); - furi_assert(tx_rx); - - if(is_picc) { - tx_rx->sniff_tx = reader_analyzer_write_rx; - tx_rx->sniff_rx = reader_analyzer_write_tx; - } else { - tx_rx->sniff_rx = reader_analyzer_write_rx; - tx_rx->sniff_tx = reader_analyzer_write_tx; - } - - tx_rx->sniff_context = instance; -} diff --git a/lib/nfc/helpers/reader_analyzer.h b/lib/nfc/helpers/reader_analyzer.h deleted file mode 100644 index 13bf4d77c..000000000 --- a/lib/nfc/helpers/reader_analyzer.h +++ /dev/null @@ -1,43 +0,0 @@ -#pragma once - -#include -#include - -typedef enum { - ReaderAnalyzerModeDebugLog = 0x01, - ReaderAnalyzerModeMfkey = 0x02, - ReaderAnalyzerModeDebugPcap = 0x04, -} ReaderAnalyzerMode; - -typedef enum { - ReaderAnalyzerEventMfkeyCollected, -} ReaderAnalyzerEvent; - -typedef struct ReaderAnalyzer ReaderAnalyzer; - -typedef void (*ReaderAnalyzerParseDataCallback)(ReaderAnalyzerEvent event, void* context); - -ReaderAnalyzer* reader_analyzer_alloc(); - -void reader_analyzer_free(ReaderAnalyzer* instance); - -void reader_analyzer_set_callback( - ReaderAnalyzer* instance, - ReaderAnalyzerParseDataCallback callback, - void* context); - -void reader_analyzer_start(ReaderAnalyzer* instance, ReaderAnalyzerMode mode); - -void reader_analyzer_stop(ReaderAnalyzer* instance); - -NfcProtocol - reader_analyzer_guess_protocol(ReaderAnalyzer* instance, uint8_t* buff_rx, uint16_t len); - -FuriHalNfcDevData* reader_analyzer_get_nfc_data(ReaderAnalyzer* instance); - -void reader_analyzer_set_nfc_data(ReaderAnalyzer* instance, FuriHalNfcDevData* nfc_data); - -void reader_analyzer_prepare_tx_rx( - ReaderAnalyzer* instance, - FuriHalNfcTxRxContext* tx_rx, - bool is_picc); diff --git a/lib/nfc/nfc.c b/lib/nfc/nfc.c new file mode 100644 index 000000000..a7c4fe1a6 --- /dev/null +++ b/lib/nfc/nfc.c @@ -0,0 +1,649 @@ +#ifndef FW_CFG_unit_tests + +#include "nfc.h" + +#include +#include + +#define TAG "Nfc" + +#define NFC_MAX_BUFFER_SIZE (256) + +typedef enum { + NfcStateIdle, + NfcStateRunning, +} NfcState; + +typedef enum { + NfcPollerStateStart, + NfcPollerStateReady, + NfcPollerStateReset, + NfcPollerStateStop, + + NfcPollerStateNum, +} NfcPollerState; + +typedef enum { + NfcCommStateIdle, + NfcCommStateWaitBlockTxTimer, + NfcCommStateReadyTx, + NfcCommStateWaitTxEnd, + NfcCommStateWaitRxStart, + NfcCommStateWaitRxEnd, + NfcCommStateFailed, +} NfcCommState; + +typedef enum { + NfcConfigurationStateIdle, + NfcConfigurationStateDone, +} NfcConfigurationState; + +struct Nfc { + NfcState state; + NfcPollerState poller_state; + NfcCommState comm_state; + NfcConfigurationState config_state; + NfcMode mode; + + uint32_t fdt_listen_fc; + uint32_t mask_rx_time_fc; + uint32_t fdt_poll_fc; + uint32_t fdt_poll_poll_us; + uint32_t guard_time_us; + NfcEventCallback callback; + void* context; + + uint8_t tx_buffer[NFC_MAX_BUFFER_SIZE]; + size_t tx_bits; + uint8_t rx_buffer[NFC_MAX_BUFFER_SIZE]; + size_t rx_bits; + + FuriThread* worker_thread; +}; + +typedef bool (*NfcWorkerPollerStateHandler)(Nfc* instance); + +static const FuriHalNfcTech nfc_tech_table[NfcModeNum][NfcTechNum] = { + [NfcModePoller] = + { + [NfcTechIso14443a] = FuriHalNfcTechIso14443a, + [NfcTechIso14443b] = FuriHalNfcTechIso14443b, + [NfcTechIso15693] = FuriHalNfcTechIso15693, + [NfcTechFelica] = FuriHalNfcTechFelica, + }, + [NfcModeListener] = + { + [NfcTechIso14443a] = FuriHalNfcTechIso14443a, + [NfcTechIso14443b] = FuriHalNfcTechInvalid, + [NfcTechIso15693] = FuriHalNfcTechIso15693, + [NfcTechFelica] = FuriHalNfcTechInvalid, + }, +}; + +static NfcError nfc_process_hal_error(FuriHalNfcError error) { + NfcError ret = NfcErrorNone; + + switch(error) { + case FuriHalNfcErrorNone: + ret = NfcErrorNone; + break; + case FuriHalNfcErrorIncompleteFrame: + ret = NfcErrorIncompleteFrame; + break; + case FuriHalNfcErrorDataFormat: + ret = NfcErrorDataFormat; + break; + + default: + ret = NfcErrorInternal; + } + + return ret; +} + +static int32_t nfc_worker_listener(void* context) { + furi_assert(context); + + Nfc* instance = context; + furi_assert(instance->callback); + furi_assert(instance->config_state == NfcConfigurationStateDone); + + instance->state = NfcStateRunning; + + furi_hal_nfc_event_start(); + + NfcEventData event_data = {}; + event_data.buffer = bit_buffer_alloc(NFC_MAX_BUFFER_SIZE); + NfcEvent nfc_event = {.data = event_data}; + NfcCommand command = NfcCommandContinue; + + while(true) { + FuriHalNfcEvent event = furi_hal_nfc_listener_wait_event(FURI_HAL_NFC_EVENT_WAIT_FOREVER); + if(event & FuriHalNfcEventAbortRequest) { + nfc_event.type = NfcEventTypeUserAbort; + instance->callback(nfc_event, instance->context); + break; + } + if(event & FuriHalNfcEventFieldOn) { + nfc_event.type = NfcEventTypeFieldOn; + instance->callback(nfc_event, instance->context); + } + if(event & FuriHalNfcEventFieldOff) { + nfc_event.type = NfcEventTypeFieldOff; + instance->callback(nfc_event, instance->context); + furi_hal_nfc_listener_idle(); + } + if(event & FuriHalNfcEventListenerActive) { + nfc_event.type = NfcEventTypeListenerActivated; + instance->callback(nfc_event, instance->context); + } + if(event & FuriHalNfcEventRxEnd) { + furi_hal_nfc_timer_block_tx_start(instance->fdt_listen_fc); + + nfc_event.type = NfcEventTypeRxEnd; + furi_hal_nfc_listener_rx( + instance->rx_buffer, sizeof(instance->rx_buffer), &instance->rx_bits); + bit_buffer_copy_bits(event_data.buffer, instance->rx_buffer, instance->rx_bits); + command = instance->callback(nfc_event, instance->context); + if(command == NfcCommandStop) { + break; + } else if(command == NfcCommandReset) { + furi_hal_nfc_listener_enable_rx(); + } else if(command == NfcCommandSleep) { + furi_hal_nfc_listener_sleep(); + } + } + } + + furi_hal_nfc_reset_mode(); + instance->config_state = NfcConfigurationStateIdle; + + bit_buffer_free(event_data.buffer); + furi_hal_nfc_low_power_mode_start(); + return 0; +} + +bool nfc_worker_poller_start_handler(Nfc* instance) { + furi_hal_nfc_poller_field_on(); + if(instance->guard_time_us) { + furi_hal_nfc_timer_block_tx_start_us(instance->guard_time_us); + FuriHalNfcEvent event = furi_hal_nfc_poller_wait_event(FURI_HAL_NFC_EVENT_WAIT_FOREVER); + furi_assert(event & FuriHalNfcEventTimerBlockTxExpired); + } + instance->poller_state = NfcPollerStateReady; + + return false; +} + +bool nfc_worker_poller_ready_handler(Nfc* instance) { + NfcCommand command = NfcCommandContinue; + + NfcEvent event = {.type = NfcEventTypePollerReady}; + command = instance->callback(event, instance->context); + if(command == NfcCommandReset) { + instance->poller_state = NfcPollerStateReset; + } else if(command == NfcCommandStop) { + instance->poller_state = NfcPollerStateStop; + } + + return false; +} + +bool nfc_worker_poller_reset_handler(Nfc* instance) { + furi_hal_nfc_low_power_mode_start(); + furi_delay_ms(100); + furi_hal_nfc_low_power_mode_stop(); + instance->poller_state = NfcPollerStateStart; + + return false; +} + +bool nfc_worker_poller_stop_handler(Nfc* instance) { + furi_hal_nfc_reset_mode(); + instance->config_state = NfcConfigurationStateIdle; + + furi_hal_nfc_low_power_mode_start(); + // Wait after field is off some time to reset tag power + furi_delay_ms(10); + instance->poller_state = NfcPollerStateStart; + + return true; +} + +static const NfcWorkerPollerStateHandler nfc_worker_poller_state_handlers[NfcPollerStateNum] = { + [NfcPollerStateStart] = nfc_worker_poller_start_handler, + [NfcPollerStateReady] = nfc_worker_poller_ready_handler, + [NfcPollerStateReset] = nfc_worker_poller_reset_handler, + [NfcPollerStateStop] = nfc_worker_poller_stop_handler, +}; + +static int32_t nfc_worker_poller(void* context) { + furi_assert(context); + + Nfc* instance = context; + furi_assert(instance->callback); + instance->state = NfcStateRunning; + instance->poller_state = NfcPollerStateStart; + + furi_hal_nfc_event_start(); + + bool exit = false; + while(!exit) { + exit = nfc_worker_poller_state_handlers[instance->poller_state](instance); + } + + return 0; +} + +Nfc* nfc_alloc() { + furi_check(furi_hal_nfc_acquire() == FuriHalNfcErrorNone); + + Nfc* instance = malloc(sizeof(Nfc)); + instance->state = NfcStateIdle; + instance->comm_state = NfcCommStateIdle; + instance->config_state = NfcConfigurationStateIdle; + + instance->worker_thread = furi_thread_alloc(); + furi_thread_set_name(instance->worker_thread, "NfcWorker"); + furi_thread_set_context(instance->worker_thread, instance); + furi_thread_set_priority(instance->worker_thread, FuriThreadPriorityHighest); + furi_thread_set_stack_size(instance->worker_thread, 8 * 1024); + + return instance; +} + +void nfc_free(Nfc* instance) { + furi_assert(instance); + furi_assert(instance->state == NfcStateIdle); + + furi_thread_free(instance->worker_thread); + free(instance); + + furi_hal_nfc_release(); +} + +void nfc_config(Nfc* instance, NfcMode mode, NfcTech tech) { + furi_assert(instance); + furi_assert(mode < NfcModeNum); + furi_assert(tech < NfcTechNum); + furi_assert(instance->config_state == NfcConfigurationStateIdle); + + FuriHalNfcTech hal_tech = nfc_tech_table[mode][tech]; + if(hal_tech == FuriHalNfcTechInvalid) { + furi_crash("Unsupported mode for given tech"); + } + FuriHalNfcMode hal_mode = (mode == NfcModePoller) ? FuriHalNfcModePoller : + FuriHalNfcModeListener; + furi_hal_nfc_low_power_mode_stop(); + furi_hal_nfc_set_mode(hal_mode, hal_tech); + + instance->mode = mode; + instance->config_state = NfcConfigurationStateDone; +} + +void nfc_set_fdt_poll_fc(Nfc* instance, uint32_t fdt_poll_fc) { + furi_assert(instance); + instance->fdt_poll_fc = fdt_poll_fc; +} + +void nfc_set_fdt_listen_fc(Nfc* instance, uint32_t fdt_listen_fc) { + furi_assert(instance); + instance->fdt_listen_fc = fdt_listen_fc; +} + +void nfc_set_fdt_poll_poll_us(Nfc* instance, uint32_t fdt_poll_poll_us) { + furi_assert(instance); + instance->fdt_poll_poll_us = fdt_poll_poll_us; +} + +void nfc_set_guard_time_us(Nfc* instance, uint32_t guard_time_us) { + furi_assert(instance); + instance->guard_time_us = guard_time_us; +} + +void nfc_set_mask_receive_time_fc(Nfc* instance, uint32_t mask_rx_time_fc) { + furi_assert(instance); + instance->mask_rx_time_fc = mask_rx_time_fc; +} + +void nfc_start(Nfc* instance, NfcEventCallback callback, void* context) { + furi_assert(instance); + furi_assert(instance->worker_thread); + furi_assert(callback); + furi_assert(instance->config_state == NfcConfigurationStateDone); + + instance->callback = callback; + instance->context = context; + if(instance->mode == NfcModePoller) { + furi_thread_set_callback(instance->worker_thread, nfc_worker_poller); + } else { + furi_thread_set_callback(instance->worker_thread, nfc_worker_listener); + } + instance->comm_state = NfcCommStateIdle; + furi_thread_start(instance->worker_thread); +} + +void nfc_stop(Nfc* instance) { + furi_assert(instance); + furi_assert(instance->state == NfcStateRunning); + + if(instance->mode == NfcModeListener) { + furi_hal_nfc_abort(); + } + furi_thread_join(instance->worker_thread); + + instance->state = NfcStateIdle; +} + +NfcError nfc_listener_tx(Nfc* instance, const BitBuffer* tx_buffer) { + furi_assert(instance); + furi_assert(tx_buffer); + + NfcError ret = NfcErrorNone; + + while(furi_hal_nfc_timer_block_tx_is_running()) { + } + + FuriHalNfcError error = + furi_hal_nfc_listener_tx(bit_buffer_get_data(tx_buffer), bit_buffer_get_size(tx_buffer)); + if(error != FuriHalNfcErrorNone) { + FURI_LOG_D(TAG, "Failed in listener TX"); + ret = nfc_process_hal_error(error); + } + + return ret; +} + +static NfcError nfc_poller_trx_state_machine(Nfc* instance, uint32_t fwt_fc) { + FuriHalNfcEvent event = 0; + NfcError error = NfcErrorNone; + + while(true) { + event = furi_hal_nfc_poller_wait_event(FURI_HAL_NFC_EVENT_WAIT_FOREVER); + if(event & FuriHalNfcEventTimerBlockTxExpired) { + if(instance->comm_state == NfcCommStateWaitBlockTxTimer) { + instance->comm_state = NfcCommStateReadyTx; + } + } + if(event & FuriHalNfcEventTxEnd) { + if(instance->comm_state == NfcCommStateWaitTxEnd) { + if(fwt_fc) { + furi_hal_nfc_timer_fwt_start(fwt_fc); + } + furi_hal_nfc_timer_block_tx_start_us(instance->fdt_poll_poll_us); + instance->comm_state = NfcCommStateWaitRxStart; + } + } + if(event & FuriHalNfcEventRxStart) { + if(instance->comm_state == NfcCommStateWaitRxStart) { + furi_hal_nfc_timer_block_tx_stop(); + furi_hal_nfc_timer_fwt_stop(); + instance->comm_state = NfcCommStateWaitRxEnd; + } + } + if(event & FuriHalNfcEventRxEnd) { + furi_hal_nfc_timer_block_tx_start(instance->fdt_poll_fc); + furi_hal_nfc_timer_fwt_stop(); + instance->comm_state = NfcCommStateWaitBlockTxTimer; + break; + } + if(event & FuriHalNfcEventTimerFwtExpired) { + if(instance->comm_state == NfcCommStateWaitRxStart) { + error = NfcErrorTimeout; + FURI_LOG_D(TAG, "FWT Timeout"); + if(furi_hal_nfc_timer_block_tx_is_running()) { + instance->comm_state = NfcCommStateWaitBlockTxTimer; + } else { + instance->comm_state = NfcCommStateReadyTx; + } + break; + } + } + } + + return error; +} + +NfcError nfc_iso14443a_poller_trx_custom_parity( + Nfc* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + furi_assert(tx_buffer); + furi_assert(rx_buffer); + + furi_assert(instance->poller_state == NfcPollerStateReady); + + NfcError ret = NfcErrorNone; + FuriHalNfcError error = FuriHalNfcErrorNone; + do { + furi_hal_nfc_trx_reset(); + while(furi_hal_nfc_timer_block_tx_is_running()) { + FuriHalNfcEvent event = + furi_hal_nfc_poller_wait_event(FURI_HAL_NFC_EVENT_WAIT_FOREVER); + if(event & FuriHalNfcEventTimerBlockTxExpired) break; + } + bit_buffer_write_bytes_with_parity( + tx_buffer, instance->tx_buffer, sizeof(instance->tx_buffer), &instance->tx_bits); + error = + furi_hal_nfc_iso14443a_poller_tx_custom_parity(instance->tx_buffer, instance->tx_bits); + if(error != FuriHalNfcErrorNone) { + FURI_LOG_D(TAG, "Failed in poller TX"); + ret = nfc_process_hal_error(error); + break; + } + instance->comm_state = NfcCommStateWaitTxEnd; + ret = nfc_poller_trx_state_machine(instance, fwt); + if(ret != NfcErrorNone) { + FURI_LOG_T(TAG, "Failed TRX state machine"); + break; + } + + error = furi_hal_nfc_poller_rx( + instance->rx_buffer, sizeof(instance->rx_buffer), &instance->rx_bits); + if(error != FuriHalNfcErrorNone) { + FURI_LOG_D(TAG, "Failed in poller RX"); + ret = nfc_process_hal_error(error); + break; + } + if(instance->rx_bits >= 9) { + if((instance->rx_bits % 9) != 0) { + ret = NfcErrorDataFormat; + break; + } + } + + bit_buffer_copy_bytes_with_parity(rx_buffer, instance->rx_buffer, instance->rx_bits); + } while(false); + + return ret; +} + +NfcError + nfc_poller_trx(Nfc* instance, const BitBuffer* tx_buffer, BitBuffer* rx_buffer, uint32_t fwt) { + furi_assert(instance); + furi_assert(tx_buffer); + furi_assert(rx_buffer); + + furi_assert(instance->poller_state == NfcPollerStateReady); + + NfcError ret = NfcErrorNone; + FuriHalNfcError error = FuriHalNfcErrorNone; + do { + furi_hal_nfc_trx_reset(); + while(furi_hal_nfc_timer_block_tx_is_running()) { + FuriHalNfcEvent event = + furi_hal_nfc_poller_wait_event(FURI_HAL_NFC_EVENT_WAIT_FOREVER); + if(event & FuriHalNfcEventTimerBlockTxExpired) break; + } + error = + furi_hal_nfc_poller_tx(bit_buffer_get_data(tx_buffer), bit_buffer_get_size(tx_buffer)); + if(error != FuriHalNfcErrorNone) { + FURI_LOG_D(TAG, "Failed in poller TX"); + ret = nfc_process_hal_error(error); + break; + } + instance->comm_state = NfcCommStateWaitTxEnd; + ret = nfc_poller_trx_state_machine(instance, fwt); + if(ret != NfcErrorNone) { + FURI_LOG_T(TAG, "Failed TRX state machine"); + break; + } + + error = furi_hal_nfc_poller_rx( + instance->rx_buffer, sizeof(instance->rx_buffer), &instance->rx_bits); + if(error != FuriHalNfcErrorNone) { + FURI_LOG_D(TAG, "Failed in poller RX"); + ret = nfc_process_hal_error(error); + break; + } + + bit_buffer_copy_bits(rx_buffer, instance->rx_buffer, instance->rx_bits); + } while(false); + + return ret; +} + +NfcError nfc_iso14443a_listener_set_col_res_data( + Nfc* instance, + uint8_t* uid, + uint8_t uid_len, + uint8_t* atqa, + uint8_t sak) { + furi_assert(instance); + + FuriHalNfcError error = + furi_hal_nfc_iso14443a_listener_set_col_res_data(uid, uid_len, atqa, sak); + instance->comm_state = NfcCommStateIdle; + return nfc_process_hal_error(error); +} + +NfcError nfc_iso14443a_poller_trx_short_frame( + Nfc* instance, + NfcIso14443aShortFrame frame, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + furi_assert(rx_buffer); + + FuriHalNfcaShortFrame short_frame = (frame == NfcIso14443aShortFrameAllReqa) ? + FuriHalNfcaShortFrameAllReq : + FuriHalNfcaShortFrameSensReq; + + furi_assert(instance->poller_state == NfcPollerStateReady); + + NfcError ret = NfcErrorNone; + FuriHalNfcError error = FuriHalNfcErrorNone; + do { + furi_hal_nfc_trx_reset(); + while(furi_hal_nfc_timer_block_tx_is_running()) { + FuriHalNfcEvent event = + furi_hal_nfc_poller_wait_event(FURI_HAL_NFC_EVENT_WAIT_FOREVER); + if(event & FuriHalNfcEventTimerBlockTxExpired) break; + } + error = furi_hal_nfc_iso14443a_poller_trx_short_frame(short_frame); + if(error != FuriHalNfcErrorNone) { + FURI_LOG_D(TAG, "Failed in poller TX"); + ret = nfc_process_hal_error(error); + break; + } + instance->comm_state = NfcCommStateWaitTxEnd; + ret = nfc_poller_trx_state_machine(instance, fwt); + if(ret != NfcErrorNone) { + FURI_LOG_T(TAG, "Failed TRX state machine"); + break; + } + + error = furi_hal_nfc_poller_rx( + instance->rx_buffer, sizeof(instance->rx_buffer), &instance->rx_bits); + if(error != FuriHalNfcErrorNone) { + FURI_LOG_D(TAG, "Failed in poller RX"); + ret = nfc_process_hal_error(error); + break; + } + + bit_buffer_copy_bits(rx_buffer, instance->rx_buffer, instance->rx_bits); + } while(false); + + return ret; +} + +NfcError nfc_iso14443a_poller_trx_sdd_frame( + Nfc* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + furi_assert(tx_buffer); + furi_assert(rx_buffer); + + furi_assert(instance->poller_state == NfcPollerStateReady); + + NfcError ret = NfcErrorNone; + FuriHalNfcError error = FuriHalNfcErrorNone; + do { + furi_hal_nfc_trx_reset(); + while(furi_hal_nfc_timer_block_tx_is_running()) { + FuriHalNfcEvent event = + furi_hal_nfc_poller_wait_event(FURI_HAL_NFC_EVENT_WAIT_FOREVER); + if(event & FuriHalNfcEventTimerBlockTxExpired) break; + } + error = furi_hal_nfc_iso14443a_tx_sdd_frame( + bit_buffer_get_data(tx_buffer), bit_buffer_get_size(tx_buffer)); + if(error != FuriHalNfcErrorNone) { + FURI_LOG_D(TAG, "Failed in poller TX"); + ret = nfc_process_hal_error(error); + break; + } + instance->comm_state = NfcCommStateWaitTxEnd; + ret = nfc_poller_trx_state_machine(instance, fwt); + if(ret != NfcErrorNone) { + FURI_LOG_T(TAG, "Failed TRX state machine"); + break; + } + + error = furi_hal_nfc_poller_rx( + instance->rx_buffer, sizeof(instance->rx_buffer), &instance->rx_bits); + if(error != FuriHalNfcErrorNone) { + FURI_LOG_D(TAG, "Failed in poller RX"); + ret = nfc_process_hal_error(error); + break; + } + + bit_buffer_copy_bits(rx_buffer, instance->rx_buffer, instance->rx_bits); + } while(false); + + return ret; +} + +NfcError nfc_iso14443a_listener_tx_custom_parity(Nfc* instance, const BitBuffer* tx_buffer) { + furi_assert(instance); + furi_assert(tx_buffer); + + NfcError ret = NfcErrorNone; + FuriHalNfcError error = FuriHalNfcErrorNone; + + const uint8_t* tx_data = bit_buffer_get_data(tx_buffer); + const uint8_t* tx_parity = bit_buffer_get_parity(tx_buffer); + size_t tx_bits = bit_buffer_get_size(tx_buffer); + + error = furi_hal_nfc_iso14443a_listener_tx_custom_parity(tx_data, tx_parity, tx_bits); + ret = nfc_process_hal_error(error); + + return ret; +} + +NfcError nfc_iso15693_listener_tx_sof(Nfc* instance) { + furi_assert(instance); + + while(furi_hal_nfc_timer_block_tx_is_running()) { + } + + FuriHalNfcError error = furi_hal_nfc_iso15693_listener_tx_sof(); + NfcError ret = nfc_process_hal_error(error); + + return ret; +} + +#endif // APP_UNIT_TESTS diff --git a/lib/nfc/nfc.h b/lib/nfc/nfc.h new file mode 100644 index 000000000..1e8f315a5 --- /dev/null +++ b/lib/nfc/nfc.h @@ -0,0 +1,364 @@ +/** + * @file nfc.h + * @brief Transport layer Nfc library. + * + * The Nfc layer is responsible for setting the operating mode (poller or listener) + * and technology (ISO14443-3A/B, ISO15693, ...), data exchange between higher + * protocol-specific levels and underlying NFC hardware, as well as timings handling. + * + * In applications using the NFC protocol system there is no need to neiter explicitly + * create an Nfc instance nor call any of its functions, as it is all handled + * automatically under the hood. + * + * If the NFC protocol system is not suitable for the application's intended purpose + * or there is need of having direct access to the NFC transport layer, then an Nfc + * instance must be allocated and the below functions shall be used to implement + * the required logic. + */ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Nfc opaque type definition. + */ +typedef struct Nfc Nfc; + +/** + * @brief Enumeration of possible Nfc event types. + * + * Not all technologies implement all events (this is due to hardware limitations). + */ +typedef enum { + NfcEventTypeUserAbort, /**< User code explicitly aborted the current operation. */ + NfcEventTypeFieldOn, /**< Reader's field was detected by the NFC hardware. */ + NfcEventTypeFieldOff, /**< Reader's field was lost. */ + NfcEventTypeTxStart, /**< Data transmission has started. */ + NfcEventTypeTxEnd, /**< Data transmission has ended. */ + NfcEventTypeRxStart, /**< Data reception has started. */ + NfcEventTypeRxEnd, /**< Data reception has ended. */ + + NfcEventTypeListenerActivated, /**< The listener has been activated by the reader. */ + NfcEventTypePollerReady, /**< The card has been activated by the poller. */ +} NfcEventType; + +/** + * @brief Nfc event data structure. + */ +typedef struct { + BitBuffer* buffer; /**< Pointer to the received data buffer. */ +} NfcEventData; + +/** + * @brief Nfc event structure. + * + * Upon emission of an event, an instance of this struct will be passed to the callback. + */ +typedef struct { + NfcEventType type; /**< Type of the emitted event. */ + NfcEventData data; /**< Event-specific data. */ +} NfcEvent; + +/** + * @brief Enumeration of possible Nfc commands. + * + * The event callback must return one of these to determine the next action. + */ +typedef enum { + NfcCommandContinue, /**< Continue operation normally. */ + NfcCommandReset, /**< Reset the current state. */ + NfcCommandStop, /**< Stop the current operation. */ + NfcCommandSleep, /**< Switch Nfc hardware to low-power mode. */ +} NfcCommand; + +/** + * @brief Nfc event callback type. + * + * A function of this type must be passed as the callback parameter upon start of a an Nfc instance. + * + * @param [in] event Nfc event, passed by value, complete with protocol type and data. + * @param [in,out] context pointer to the user-specific context (set when starting an Nfc instance). + * @returns command which the event producer must execute. + */ +typedef NfcCommand (*NfcEventCallback)(NfcEvent event, void* context); + +/** + * @brief Enumeration of possible operating modes. + * + * Not all technologies implement the listener operating mode. + */ +typedef enum { + NfcModePoller, /**< Configure the Nfc instance as a poller. */ + NfcModeListener, /**< Configure the Nfc instance as a listener. */ + + NfcModeNum, /**< Operating mode count. Internal use. */ +} NfcMode; + +/** + * @brief Enumeration of available technologies. + */ +typedef enum { + NfcTechIso14443a, /**< Configure the Nfc instance to use the ISO14443-3A technology. */ + NfcTechIso14443b, /**< Configure the Nfc instance to use the ISO14443-3B technology. */ + NfcTechIso15693, /**< Configure the Nfc instance to use the ISO15693 technology. */ + NfcTechFelica, /**< Configure the Nfc instance to use the FeliCa technology. */ + + NfcTechNum, /**< Technologies count. Internal use. */ +} NfcTech; + +/** + * @brief Enumeration of possible Nfc error codes. + */ +typedef enum { + NfcErrorNone, /**< No error has occurred. */ + NfcErrorInternal, /**< An unknown error has occured on the lower level. */ + NfcErrorTimeout, /**< Operation is taking too long (e.g. card does not respond). */ + NfcErrorIncompleteFrame, /**< An incomplete data frame has been received. */ + NfcErrorDataFormat, /**< Data has not been parsed due to wrong/unknown format. */ +} NfcError; + +/** + * @brief Allocate an Nfc instance. + * + * Will exclusively take over the NFC HAL until deleted. + * + * @returns pointer to the allocated Nfc instance. + */ +Nfc* nfc_alloc(); + +/** + * @brief Delete an Nfc instance. + * + * Will release the NFC HAL lock, making it available for use by others. + * + * @param[in,out] instance pointer to the instance to be deleted. + */ +void nfc_free(Nfc* instance); + +/** + * @brief Configure the Nfc instance to work in a particular mode. + * + * Not all technologies implement the listener operating mode. + * + * @param[in,out] instance pointer to the instance to be configured. + * @param[in] mode required operating mode. + * @param[in] tech required technology configuration. + */ +void nfc_config(Nfc* instance, NfcMode mode, NfcTech tech); + +/** + * @brief Set poller frame delay time. + * + * @param[in,out] instance pointer to the instance to be modified. + * @param[in] fdt_poll_fc frame delay time, in carrier cycles. +*/ +void nfc_set_fdt_poll_fc(Nfc* instance, uint32_t fdt_poll_fc); + +/** + * @brief Set listener frame delay time. + * + * @param[in,out] instance pointer to the instance to be modified. + * @param[in] fdt_listen_fc frame delay time, in carrier cycles. + */ +void nfc_set_fdt_listen_fc(Nfc* instance, uint32_t fdt_listen_fc); + +/** + * @brief Set mask receive time. + * + * @param[in,out] instance pointer to the instance to be modified. + * @param[in] mask_rx_time mask receive time, in carrier cycles. + */ +void nfc_set_mask_receive_time_fc(Nfc* instance, uint32_t mask_rx_time_fc); + +/** + * @brief Set frame delay time. + * + * Frame delay time is the minimum time between two consecutive poll frames. + * + * @param[in,out] instance pointer to the instance to be modified. + * @param[in] fdt_poll_poll_us frame delay time, in microseconds. + */ +void nfc_set_fdt_poll_poll_us(Nfc* instance, uint32_t fdt_poll_poll_us); + +/** + * @brief Set guard time. + * + * @param[in,out] instance pointer to the instance to be modified. + * @param[in] guard_time_us guard time, in microseconds. + */ +void nfc_set_guard_time_us(Nfc* instance, uint32_t guard_time_us); + +/** + * @brief Start the Nfc instance. + * + * The instance must be configured to work with a specific technology + * in a specific operating mode with a nfc_config() call before starting. + * + * Once started, the user code will be receiving events through the provided + * callback which must handle them according to the logic required. + * + * @param[in,out] instance pointer to the instance to be started. + * @param[in] callback pointer to a user-defined callback function which will receive events. + * @param[in] context pointer to a user-specific context (will be passed to the callback). + */ +void nfc_start(Nfc* instance, NfcEventCallback callback, void* context); + +/** + * @brief Stop Nfc instance. + * + * The instance can only be stopped if it is running. + * + * @param[in,out] instance pointer to the instance to be stopped. + */ +void nfc_stop(Nfc* instance); + +/** + * @brief Transmit and receive a data frame in poller mode. + * + * The rx_buffer will be filled with any data received as a response to data + * sent from tx_buffer, with a timeout defined by the fwt parameter. + * + * The data being transmitted and received may be either bit- or byte-oriented. + * It shall not contain any technology-specific sequences as start or stop bits + * and/or other special symbols, as this is handled on the underlying HAL level. + * + * Must ONLY be used inside the callback function. + * + * @param[in,out] instance pointer to the instance to be used in the transaction. + * @param[in] tx_buffer pointer to the buffer containing the data to be transmitted. + * @param[out] rx_buffer pointer to the buffer to be filled with received data. + * @param[in] fwt frame wait time (response timeout), in carrier cycles. + * @returns NfcErrorNone on success, any other error code on failure. + */ +NfcError + nfc_poller_trx(Nfc* instance, const BitBuffer* tx_buffer, BitBuffer* rx_buffer, uint32_t fwt); + +/** + * @brief Transmit a data frame in listener mode. + * + * Used to transmit a response to the reader request in listener mode. + * + * The data being transmitted may be either bit- or byte-oriented. + * It shall not contain any technology-specific sequences as start or stop bits + * and/or other special symbols, as this is handled on the underlying HAL level. + * + * Must ONLY be used inside the callback function. + * + * @param[in,out] instance pointer to the instance to be used in the transaction. + * @param[in] tx_buffer pointer to the buffer containing the data to be transmitted. + * @returns NfcErrorNone on success, any other error code on failure. + */ +NfcError nfc_listener_tx(Nfc* instance, const BitBuffer* tx_buffer); + +/* + * Technology-specific functions. + * + * In a perfect world, this would not be necessary. + * However, the current implementation employs NFC hardware that partially implements + * certain protocols (e.g. ISO14443-3A), thus requiring methods to access such features. + */ + +/******************* ISO14443-3A specific API *******************/ + +/** + * @brief Enumeration of possible ISO14443-3A short frame types. + */ +typedef enum { + NfcIso14443aShortFrameSensReq, + NfcIso14443aShortFrameAllReqa, +} NfcIso14443aShortFrame; + +/** + * @brief Transmit an ISO14443-3A short frame and receive the response in poller mode. + * + * @param[in,out] instance pointer to the instance to be used in the transaction. + * @param[in] frame type of short frame to be sent. + * @param[out] rx_buffer pointer to the buffer to be filled with received data. + * @param[in] fwt frame wait time (response timeout), in carrier cycles. + * @returns NfcErrorNone on success, any other error code on failure. + */ +NfcError nfc_iso14443a_poller_trx_short_frame( + Nfc* instance, + NfcIso14443aShortFrame frame, + BitBuffer* rx_buffer, + uint32_t fwt); + +/** + * @brief Transmit an ISO14443-3A SDD frame and receive the response in poller mode. + * + * @param[in,out] instance pointer to the instance to be used in the transaction. + * @param[in] tx_buffer pointer to the buffer containing the data to be transmitted. + * @param[out] rx_buffer pointer to the buffer to be filled with received data. + * @param[in] fwt frame wait time (response timeout), in carrier cycles. + * @returns NfcErrorNone on success, any other error code on failure. + */ +NfcError nfc_iso14443a_poller_trx_sdd_frame( + Nfc* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt); + +/** + * @brief Transmit an ISO14443-3A data frame with custom parity bits and receive the response in poller mode. + * + * Same as nfc_poller_trx(), but uses the parity bits provided by the user code + * instead of calculating them automatically. + * + * @param[in,out] instance pointer to the instance to be used in the transaction. + * @param[in] tx_buffer pointer to the buffer containing the data to be transmitted. + * @param[out] rx_buffer pointer to the buffer to be filled with received data. + * @param[in] fwt frame wait time (response timeout), in carrier cycles. + * @returns NfcErrorNone on success, any other error code on failure. + */ +NfcError nfc_iso14443a_poller_trx_custom_parity( + Nfc* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt); + +/** + * @brief Transmit an ISO14443-3A frame with custom parity bits in listener mode. + * + * Same as nfc_listener_tx(), but uses the parity bits provided by the user code + * instead of calculating them automatically. + * + * @param[in,out] instance pointer to the instance to be used in the transaction. + * @param[in] tx_buffer pointer to the buffer containing the data to be transmitted. + * @returns NfcErrorNone on success, any other error code on failure. + */ +NfcError nfc_iso14443a_listener_tx_custom_parity(Nfc* instance, const BitBuffer* tx_buffer); + +/** + * @brief Set ISO14443-3A collision resolution parameters in listener mode. + * + * Configures the NFC hardware for automatic collision resolution. + * + * @param[in,out] instance pointer to the instance to be configured. + * @param[in] uid pointer to a byte array containing the UID. + * @param[in] uid_len UID length in bytes (must be supported by the protocol). + * @param[in] atqa ATQA byte value. + * @param[in] sak SAK byte value. + * @returns NfcErrorNone on success, any other error code on failure. + */ +NfcError nfc_iso14443a_listener_set_col_res_data( + Nfc* instance, + uint8_t* uid, + uint8_t uid_len, + uint8_t* atqa, + uint8_t sak); + +/** + * @brief Send ISO15693 Start of Frame pattern in listener mode + * + * @param[in,out] instance pointer to the instance to be configured. + * @returns NfcErrorNone on success, any other error code on failure. + */ +NfcError nfc_iso15693_listener_tx_sof(Nfc* instance); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/nfc_common.h b/lib/nfc/nfc_common.h new file mode 100644 index 000000000..c3cccf697 --- /dev/null +++ b/lib/nfc/nfc_common.h @@ -0,0 +1,22 @@ +/** + * @file nfc_common.h + * @brief Various common NFC-related macros. + */ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/* NFC file format version which changed ATQA format. Deprecated. */ +#define NFC_LSB_ATQA_FORMAT_VERSION (2) +/* NFC file format version which is still supported as backwards compatible. */ +#define NFC_MINIMUM_SUPPORTED_FORMAT_VERSION NFC_LSB_ATQA_FORMAT_VERSION +/* NFC file format version which implemented the unified loading process. */ +#define NFC_UNIFIED_FORMAT_VERSION (4) +/* Current NFC file format version. */ +#define NFC_CURRENT_FORMAT_VERSION NFC_UNIFIED_FORMAT_VERSION + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/nfc_device.c b/lib/nfc/nfc_device.c index 19830cd04..267824d16 100644 --- a/lib/nfc/nfc_device.c +++ b/lib/nfc/nfc_device.c @@ -1,1741 +1,356 @@ -#include "nfc_device.h" -#include "assets_icons.h" -#include "nfc_types.h" +#include "nfc_device_i.h" -#include -#include -#include +#include #include -#define TAG "NfcDevice" -#define NFC_DEVICE_KEYS_FOLDER EXT_PATH("nfc/.cache") -#define NFC_DEVICE_KEYS_EXTENSION ".keys" +#include "nfc_common.h" +#include "protocols/nfc_device_defs.h" -static const char* nfc_file_header = "Flipper NFC device"; -static const uint32_t nfc_file_version = 3; +#define NFC_FILE_HEADER "Flipper NFC device" +#define NFC_DEV_TYPE_ERROR "Protocol type mismatch" -static const char* nfc_keys_file_header = "Flipper NFC keys"; -static const uint32_t nfc_keys_file_version = 1; +#define NFC_DEVICE_UID_KEY "UID" +#define NFC_DEVICE_TYPE_KEY "Device type" -// Protocols format versions -static const uint32_t nfc_mifare_classic_data_format_version = 2; -static const uint32_t nfc_mifare_ultralight_data_format_version = 1; +#define NFC_DEVICE_UID_MAX_LEN (10U) NfcDevice* nfc_device_alloc() { - NfcDevice* nfc_dev = malloc(sizeof(NfcDevice)); - nfc_dev->storage = furi_record_open(RECORD_STORAGE); - nfc_dev->dialogs = furi_record_open(RECORD_DIALOGS); - nfc_dev->load_path = furi_string_alloc(); - nfc_dev->dev_data.parsed_data = furi_string_alloc(); - nfc_dev->folder = furi_string_alloc(); + NfcDevice* instance = malloc(sizeof(NfcDevice)); + instance->protocol = NfcProtocolInvalid; - // Rename cache folder name for backward compatibility - if(storage_common_stat(nfc_dev->storage, "/ext/nfc/cache", NULL) == FSE_OK) { - storage_common_rename(nfc_dev->storage, "/ext/nfc/cache", NFC_DEVICE_KEYS_FOLDER); - } - return nfc_dev; + return instance; } -void nfc_device_free(NfcDevice* nfc_dev) { - furi_assert(nfc_dev); - nfc_device_clear(nfc_dev); - furi_record_close(RECORD_STORAGE); - furi_record_close(RECORD_DIALOGS); - furi_string_free(nfc_dev->load_path); - furi_string_free(nfc_dev->dev_data.parsed_data); - furi_string_free(nfc_dev->folder); - free(nfc_dev); +void nfc_device_free(NfcDevice* instance) { + furi_assert(instance); + + nfc_device_clear(instance); + free(instance); } -static void nfc_device_prepare_format_string(NfcDevice* dev, FuriString* format_string) { - if(dev->format == NfcDeviceSaveFormatUid) { - furi_string_set(format_string, "UID"); - } else if(dev->format == NfcDeviceSaveFormatBankCard) { - furi_string_set(format_string, "Bank card"); - } else if(dev->format == NfcDeviceSaveFormatMifareUl) { - furi_string_set(format_string, nfc_mf_ul_type(dev->dev_data.mf_ul_data.type, true)); - } else if(dev->format == NfcDeviceSaveFormatMifareClassic) { - furi_string_set(format_string, "Mifare Classic"); - } else if(dev->format == NfcDeviceSaveFormatMifareDesfire) { - furi_string_set(format_string, "Mifare DESFire"); - } else if(dev->format == NfcDeviceSaveFormatNfcV) { - furi_string_set(format_string, "ISO15693"); - } else { - furi_string_set(format_string, "Unknown"); +void nfc_device_clear(NfcDevice* instance) { + furi_assert(instance); + + if(instance->protocol == NfcProtocolInvalid) { + furi_assert(instance->protocol_data == NULL); + } else if(instance->protocol < NfcProtocolNum) { + if(instance->protocol_data) { + nfc_devices[instance->protocol]->free(instance->protocol_data); + instance->protocol_data = NULL; + } + instance->protocol = NfcProtocolInvalid; } } -static bool nfc_device_parse_format_string(NfcDevice* dev, FuriString* format_string) { - if(furi_string_start_with_str(format_string, "UID")) { - dev->format = NfcDeviceSaveFormatUid; - dev->dev_data.protocol = NfcDeviceProtocolUnknown; - return true; - } - if(furi_string_start_with_str(format_string, "Bank card")) { - dev->format = NfcDeviceSaveFormatBankCard; - dev->dev_data.protocol = NfcDeviceProtocolEMV; - return true; - } - // Check Mifare Ultralight types - for(MfUltralightType type = MfUltralightTypeUnknown; type < MfUltralightTypeNum; type++) { - if(furi_string_equal(format_string, nfc_mf_ul_type(type, true))) { - dev->format = NfcDeviceSaveFormatMifareUl; - dev->dev_data.protocol = NfcDeviceProtocolMifareUl; - dev->dev_data.mf_ul_data.type = type; - return true; - } - } - if(furi_string_start_with_str(format_string, "Mifare Classic")) { - dev->format = NfcDeviceSaveFormatMifareClassic; - dev->dev_data.protocol = NfcDeviceProtocolMifareClassic; - return true; - } - if(furi_string_start_with_str(format_string, "Mifare DESFire")) { - dev->format = NfcDeviceSaveFormatMifareDesfire; - dev->dev_data.protocol = NfcDeviceProtocolMifareDesfire; - return true; - } - if(furi_string_start_with_str(format_string, "ISO15693")) { - dev->format = NfcDeviceSaveFormatNfcV; - dev->dev_data.protocol = NfcDeviceProtocolNfcV; - return true; - } - return false; -} +void nfc_device_reset(NfcDevice* instance) { + furi_assert(instance); + furi_assert(instance->protocol < NfcProtocolNum); -static bool nfc_device_save_mifare_ul_data(FlipperFormat* file, NfcDevice* dev) { - bool saved = false; - MfUltralightData* data = &dev->dev_data.mf_ul_data; - FuriString* temp_str; - temp_str = furi_string_alloc(); - - // Save Mifare Ultralight specific data - do { - if(!flipper_format_write_comment_cstr(file, "Mifare Ultralight specific data")) break; - if(!flipper_format_write_uint32( - file, "Data format version", &nfc_mifare_ultralight_data_format_version, 1)) - break; - if(!flipper_format_write_hex(file, "Signature", data->signature, sizeof(data->signature))) - break; - if(!flipper_format_write_hex( - file, "Mifare version", (uint8_t*)&data->version, sizeof(data->version))) - break; - // Write conters and tearing flags data - bool counters_saved = true; - for(uint8_t i = 0; i < 3; i++) { - furi_string_printf(temp_str, "Counter %d", i); - if(!flipper_format_write_uint32( - file, furi_string_get_cstr(temp_str), &data->counter[i], 1)) { - counters_saved = false; - break; - } - furi_string_printf(temp_str, "Tearing %d", i); - if(!flipper_format_write_hex( - file, furi_string_get_cstr(temp_str), &data->tearing[i], 1)) { - counters_saved = false; - break; - } - } - if(!counters_saved) break; - // Write pages data - uint32_t pages_total = data->data_size / 4; - if(!flipper_format_write_uint32(file, "Pages total", &pages_total, 1)) break; - uint32_t pages_read = data->data_read / 4; - if(!flipper_format_write_uint32(file, "Pages read", &pages_read, 1)) break; - bool pages_saved = true; - for(uint16_t i = 0; i < data->data_size; i += 4) { - furi_string_printf(temp_str, "Page %d", i / 4); - if(!flipper_format_write_hex(file, furi_string_get_cstr(temp_str), &data->data[i], 4)) { - pages_saved = false; - break; - } - } - if(!pages_saved) break; - - // Write authentication counter - uint32_t auth_counter = data->curr_authlim; - if(!flipper_format_write_uint32(file, "Failed authentication attempts", &auth_counter, 1)) - break; - - saved = true; - } while(false); - - furi_string_free(temp_str); - return saved; -} - -bool nfc_device_load_mifare_ul_data(FlipperFormat* file, NfcDevice* dev) { - bool parsed = false; - MfUltralightData* data = &dev->dev_data.mf_ul_data; - FuriString* temp_str; - temp_str = furi_string_alloc(); - uint32_t data_format_version = 0; - - do { - // Read Mifare Ultralight format version - if(!flipper_format_read_uint32(file, "Data format version", &data_format_version, 1)) { - if(!flipper_format_rewind(file)) break; - } - - // Read signature - if(!flipper_format_read_hex(file, "Signature", data->signature, sizeof(data->signature))) - break; - // Read Mifare version - if(!flipper_format_read_hex( - file, "Mifare version", (uint8_t*)&data->version, sizeof(data->version))) - break; - // Read counters and tearing flags - bool counters_parsed = true; - for(uint8_t i = 0; i < 3; i++) { - furi_string_printf(temp_str, "Counter %d", i); - if(!flipper_format_read_uint32( - file, furi_string_get_cstr(temp_str), &data->counter[i], 1)) { - counters_parsed = false; - break; - } - furi_string_printf(temp_str, "Tearing %d", i); - if(!flipper_format_read_hex( - file, furi_string_get_cstr(temp_str), &data->tearing[i], 1)) { - counters_parsed = false; - break; - } - } - if(!counters_parsed) break; - // Read pages - uint32_t pages_total = 0; - if(!flipper_format_read_uint32(file, "Pages total", &pages_total, 1)) break; - uint32_t pages_read = 0; - if(data_format_version < nfc_mifare_ultralight_data_format_version) { - pages_read = pages_total; - } else { - if(!flipper_format_read_uint32(file, "Pages read", &pages_read, 1)) break; - } - data->data_size = pages_total * 4; - data->data_read = pages_read * 4; - if(data->data_size > MF_UL_MAX_DUMP_SIZE || data->data_read > MF_UL_MAX_DUMP_SIZE) break; - bool pages_parsed = true; - for(uint16_t i = 0; i < pages_total; i++) { - furi_string_printf(temp_str, "Page %d", i); - if(!flipper_format_read_hex( - file, furi_string_get_cstr(temp_str), &data->data[i * 4], 4)) { - pages_parsed = false; - break; - } - } - if(!pages_parsed) break; - - // Read authentication counter - uint32_t auth_counter; - if(!flipper_format_read_uint32(file, "Failed authentication attempts", &auth_counter, 1)) - auth_counter = 0; - data->curr_authlim = auth_counter; - - data->auth_success = mf_ul_is_full_capture(data); - - parsed = true; - } while(false); - - furi_string_free(temp_str); - return parsed; -} - -static bool nfc_device_save_mifare_df_key_settings( - FlipperFormat* file, - MifareDesfireKeySettings* ks, - const char* prefix) { - bool saved = false; - FuriString* key; - key = furi_string_alloc(); - - do { - furi_string_printf(key, "%s Change Key ID", prefix); - if(!flipper_format_write_hex(file, furi_string_get_cstr(key), &ks->change_key_id, 1)) - break; - furi_string_printf(key, "%s Config Changeable", prefix); - if(!flipper_format_write_bool(file, furi_string_get_cstr(key), &ks->config_changeable, 1)) - break; - furi_string_printf(key, "%s Free Create Delete", prefix); - if(!flipper_format_write_bool(file, furi_string_get_cstr(key), &ks->free_create_delete, 1)) - break; - furi_string_printf(key, "%s Free Directory List", prefix); - if(!flipper_format_write_bool(file, furi_string_get_cstr(key), &ks->free_directory_list, 1)) - break; - furi_string_printf(key, "%s Key Changeable", prefix); - if(!flipper_format_write_bool( - file, furi_string_get_cstr(key), &ks->master_key_changeable, 1)) - break; - if(ks->flags) { - furi_string_printf(key, "%s Flags", prefix); - if(!flipper_format_write_hex(file, furi_string_get_cstr(key), &ks->flags, 1)) break; - } - furi_string_printf(key, "%s Max Keys", prefix); - if(!flipper_format_write_hex(file, furi_string_get_cstr(key), &ks->max_keys, 1)) break; - for(MifareDesfireKeyVersion* kv = ks->key_version_head; kv; kv = kv->next) { - furi_string_printf(key, "%s Key %d Version", prefix, kv->id); - if(!flipper_format_write_hex(file, furi_string_get_cstr(key), &kv->version, 1)) break; - } - saved = true; - } while(false); - - furi_string_free(key); - return saved; -} - -bool nfc_device_load_mifare_df_key_settings( - FlipperFormat* file, - MifareDesfireKeySettings* ks, - const char* prefix) { - bool parsed = false; - FuriString* key; - key = furi_string_alloc(); - - do { - furi_string_printf(key, "%s Change Key ID", prefix); - if(!flipper_format_read_hex(file, furi_string_get_cstr(key), &ks->change_key_id, 1)) break; - furi_string_printf(key, "%s Config Changeable", prefix); - if(!flipper_format_read_bool(file, furi_string_get_cstr(key), &ks->config_changeable, 1)) - break; - furi_string_printf(key, "%s Free Create Delete", prefix); - if(!flipper_format_read_bool(file, furi_string_get_cstr(key), &ks->free_create_delete, 1)) - break; - furi_string_printf(key, "%s Free Directory List", prefix); - if(!flipper_format_read_bool(file, furi_string_get_cstr(key), &ks->free_directory_list, 1)) - break; - furi_string_printf(key, "%s Key Changeable", prefix); - if(!flipper_format_read_bool( - file, furi_string_get_cstr(key), &ks->master_key_changeable, 1)) - break; - furi_string_printf(key, "%s Flags", prefix); - if(flipper_format_key_exist(file, furi_string_get_cstr(key))) { - if(!flipper_format_read_hex(file, furi_string_get_cstr(key), &ks->flags, 1)) break; - } - furi_string_printf(key, "%s Max Keys", prefix); - if(!flipper_format_read_hex(file, furi_string_get_cstr(key), &ks->max_keys, 1)) break; - ks->flags |= ks->max_keys >> 4; - ks->max_keys &= 0xF; - MifareDesfireKeyVersion** kv_head = &ks->key_version_head; - for(int key_id = 0; key_id < ks->max_keys; key_id++) { - furi_string_printf(key, "%s Key %d Version", prefix, key_id); - uint8_t version; - if(flipper_format_read_hex(file, furi_string_get_cstr(key), &version, 1)) { - MifareDesfireKeyVersion* kv = malloc(sizeof(MifareDesfireKeyVersion)); - memset(kv, 0, sizeof(MifareDesfireKeyVersion)); - kv->id = key_id; - kv->version = version; - *kv_head = kv; - kv_head = &kv->next; - } - } - parsed = true; - } while(false); - - furi_string_free(key); - return parsed; -} - -static bool nfc_device_save_mifare_df_app(FlipperFormat* file, MifareDesfireApplication* app) { - bool saved = false; - FuriString *prefix, *key; - prefix = - furi_string_alloc_printf("Application %02x%02x%02x", app->id[0], app->id[1], app->id[2]); - key = furi_string_alloc(); - uint8_t* tmp = NULL; - - do { - if(app->key_settings) { - if(!nfc_device_save_mifare_df_key_settings( - file, app->key_settings, furi_string_get_cstr(prefix))) - break; - } - if(!app->file_head) break; - uint32_t n_files = 0; - for(MifareDesfireFile* f = app->file_head; f; f = f->next) { - n_files++; - } - tmp = malloc(n_files); - int i = 0; - for(MifareDesfireFile* f = app->file_head; f; f = f->next) { - tmp[i++] = f->id; - } - furi_string_printf(key, "%s File IDs", furi_string_get_cstr(prefix)); - if(!flipper_format_write_hex(file, furi_string_get_cstr(key), tmp, n_files)) break; - bool saved_files = true; - for(MifareDesfireFile* f = app->file_head; f; f = f->next) { - saved_files = false; - furi_string_printf(key, "%s File %d Type", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_hex(file, furi_string_get_cstr(key), &f->type, 1)) break; - furi_string_printf( - key, "%s File %d Communication Settings", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_hex(file, furi_string_get_cstr(key), &f->comm, 1)) break; - furi_string_printf( - key, "%s File %d Access Rights", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_hex( - file, furi_string_get_cstr(key), (uint8_t*)&f->access_rights, 2)) - break; - uint16_t size = 0; - if(f->type == MifareDesfireFileTypeStandard || - f->type == MifareDesfireFileTypeBackup) { - size = f->settings.data.size; - furi_string_printf(key, "%s File %d Size", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_uint32( - file, furi_string_get_cstr(key), &f->settings.data.size, 1)) - break; - } else if(f->type == MifareDesfireFileTypeValue) { - furi_string_printf( - key, "%s File %d Hi Limit", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_uint32( - file, furi_string_get_cstr(key), &f->settings.value.hi_limit, 1)) - break; - furi_string_printf( - key, "%s File %d Lo Limit", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_uint32( - file, furi_string_get_cstr(key), &f->settings.value.lo_limit, 1)) - break; - furi_string_printf( - key, "%s File %d Limited Credit Value", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_uint32( - file, furi_string_get_cstr(key), &f->settings.value.limited_credit_value, 1)) - break; - furi_string_printf( - key, "%s File %d Limited Credit Enabled", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_bool( - file, - furi_string_get_cstr(key), - &f->settings.value.limited_credit_enabled, - 1)) - break; - size = 4; - } else if( - f->type == MifareDesfireFileTypeLinearRecord || - f->type == MifareDesfireFileTypeCyclicRecord) { - furi_string_printf(key, "%s File %d Size", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_uint32( - file, furi_string_get_cstr(key), &f->settings.record.size, 1)) - break; - furi_string_printf(key, "%s File %d Max", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_uint32( - file, furi_string_get_cstr(key), &f->settings.record.max, 1)) - break; - furi_string_printf(key, "%s File %d Cur", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_uint32( - file, furi_string_get_cstr(key), &f->settings.record.cur, 1)) - break; - size = f->settings.record.size * f->settings.record.cur; - } - if(f->contents) { - furi_string_printf(key, "%s File %d", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_write_hex(file, furi_string_get_cstr(key), f->contents, size)) - break; - } - saved_files = true; - } - if(!saved_files) { - break; - } - saved = true; - } while(false); - - free(tmp); - furi_string_free(prefix); - furi_string_free(key); - return saved; -} - -bool nfc_device_load_mifare_df_app(FlipperFormat* file, MifareDesfireApplication* app) { - bool parsed = false; - FuriString *prefix, *key; - prefix = - furi_string_alloc_printf("Application %02x%02x%02x", app->id[0], app->id[1], app->id[2]); - key = furi_string_alloc(); - uint8_t* tmp = NULL; - MifareDesfireFile* f = NULL; - - do { - app->key_settings = malloc(sizeof(MifareDesfireKeySettings)); - memset(app->key_settings, 0, sizeof(MifareDesfireKeySettings)); - if(!nfc_device_load_mifare_df_key_settings( - file, app->key_settings, furi_string_get_cstr(prefix))) { - free(app->key_settings); - app->key_settings = NULL; - break; - } - furi_string_printf(key, "%s File IDs", furi_string_get_cstr(prefix)); - uint32_t n_files; - if(!flipper_format_get_value_count(file, furi_string_get_cstr(key), &n_files)) break; - tmp = malloc(n_files); - if(!flipper_format_read_hex(file, furi_string_get_cstr(key), tmp, n_files)) break; - MifareDesfireFile** file_head = &app->file_head; - bool parsed_files = true; - for(uint32_t i = 0; i < n_files; i++) { - parsed_files = false; - f = malloc(sizeof(MifareDesfireFile)); - memset(f, 0, sizeof(MifareDesfireFile)); - f->id = tmp[i]; - furi_string_printf(key, "%s File %d Type", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_hex(file, furi_string_get_cstr(key), &f->type, 1)) break; - furi_string_printf( - key, "%s File %d Communication Settings", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_hex(file, furi_string_get_cstr(key), &f->comm, 1)) break; - furi_string_printf( - key, "%s File %d Access Rights", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_hex( - file, furi_string_get_cstr(key), (uint8_t*)&f->access_rights, 2)) - break; - if(f->type == MifareDesfireFileTypeStandard || - f->type == MifareDesfireFileTypeBackup) { - furi_string_printf(key, "%s File %d Size", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_uint32( - file, furi_string_get_cstr(key), &f->settings.data.size, 1)) - break; - } else if(f->type == MifareDesfireFileTypeValue) { - furi_string_printf( - key, "%s File %d Hi Limit", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_uint32( - file, furi_string_get_cstr(key), &f->settings.value.hi_limit, 1)) - break; - furi_string_printf( - key, "%s File %d Lo Limit", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_uint32( - file, furi_string_get_cstr(key), &f->settings.value.lo_limit, 1)) - break; - furi_string_printf( - key, "%s File %d Limited Credit Value", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_uint32( - file, furi_string_get_cstr(key), &f->settings.value.limited_credit_value, 1)) - break; - furi_string_printf( - key, "%s File %d Limited Credit Enabled", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_bool( - file, - furi_string_get_cstr(key), - &f->settings.value.limited_credit_enabled, - 1)) - break; - } else if( - f->type == MifareDesfireFileTypeLinearRecord || - f->type == MifareDesfireFileTypeCyclicRecord) { - furi_string_printf(key, "%s File %d Size", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_uint32( - file, furi_string_get_cstr(key), &f->settings.record.size, 1)) - break; - furi_string_printf(key, "%s File %d Max", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_uint32( - file, furi_string_get_cstr(key), &f->settings.record.max, 1)) - break; - furi_string_printf(key, "%s File %d Cur", furi_string_get_cstr(prefix), f->id); - if(!flipper_format_read_uint32( - file, furi_string_get_cstr(key), &f->settings.record.cur, 1)) - break; - } - furi_string_printf(key, "%s File %d", furi_string_get_cstr(prefix), f->id); - if(flipper_format_key_exist(file, furi_string_get_cstr(key))) { - uint32_t size; - if(!flipper_format_get_value_count(file, furi_string_get_cstr(key), &size)) break; - f->contents = malloc(size); - if(!flipper_format_read_hex(file, furi_string_get_cstr(key), f->contents, size)) - break; - } - *file_head = f; - file_head = &f->next; - f = NULL; - parsed_files = true; - } - if(!parsed_files) { - break; - } - parsed = true; - } while(false); - - if(f) { - free(f->contents); - free(f); - } - free(tmp); - furi_string_free(prefix); - furi_string_free(key); - return parsed; -} - -static bool nfc_device_save_mifare_df_data(FlipperFormat* file, NfcDevice* dev) { - bool saved = false; - MifareDesfireData* data = &dev->dev_data.mf_df_data; - uint8_t* tmp = NULL; - - do { - if(!flipper_format_write_comment_cstr(file, "Mifare DESFire specific data")) break; - if(!flipper_format_write_hex( - file, "PICC Version", (uint8_t*)&data->version, sizeof(data->version))) - break; - if(data->free_memory) { - if(!flipper_format_write_uint32(file, "PICC Free Memory", &data->free_memory->bytes, 1)) - break; - } - if(data->master_key_settings) { - if(!nfc_device_save_mifare_df_key_settings(file, data->master_key_settings, "PICC")) - break; - } - uint32_t n_apps = 0; - for(MifareDesfireApplication* app = data->app_head; app; app = app->next) { - n_apps++; - } - if(!flipper_format_write_uint32(file, "Application Count", &n_apps, 1)) break; - if(n_apps) { - tmp = malloc(n_apps * 3); - int i = 0; - for(MifareDesfireApplication* app = data->app_head; app; app = app->next) { - memcpy(tmp + i, app->id, 3); //-V769 - i += 3; - } - if(!flipper_format_write_hex(file, "Application IDs", tmp, n_apps * 3)) break; - for(MifareDesfireApplication* app = data->app_head; app; app = app->next) { - if(!nfc_device_save_mifare_df_app(file, app)) break; - } - } - saved = true; - } while(false); - - free(tmp); - return saved; -} - -bool nfc_device_load_mifare_df_data(FlipperFormat* file, NfcDevice* dev) { - bool parsed = false; - MifareDesfireData* data = &dev->dev_data.mf_df_data; - memset(data, 0, sizeof(MifareDesfireData)); - uint8_t* tmp = NULL; - - do { - if(!flipper_format_read_hex( - file, "PICC Version", (uint8_t*)&data->version, sizeof(data->version))) - break; - if(flipper_format_key_exist(file, "PICC Free Memory")) { - data->free_memory = malloc(sizeof(MifareDesfireFreeMemory)); - memset(data->free_memory, 0, sizeof(MifareDesfireFreeMemory)); - if(!flipper_format_read_uint32( - file, "PICC Free Memory", &data->free_memory->bytes, 1)) { - free(data->free_memory); - break; - } - } - if(flipper_format_key_exist(file, "PICC Change Key ID")) { - data->master_key_settings = malloc(sizeof(MifareDesfireKeySettings)); - memset(data->master_key_settings, 0, sizeof(MifareDesfireKeySettings)); - if(!nfc_device_load_mifare_df_key_settings(file, data->master_key_settings, "PICC")) { - free(data->master_key_settings); - data->master_key_settings = NULL; - break; - } - } - uint32_t n_apps; - if(!flipper_format_read_uint32(file, "Application Count", &n_apps, 1)) break; - if(n_apps) { - tmp = malloc(n_apps * 3); - if(!flipper_format_read_hex(file, "Application IDs", tmp, n_apps * 3)) break; - bool parsed_apps = true; - MifareDesfireApplication** app_head = &data->app_head; - for(uint32_t i = 0; i < n_apps; i++) { - MifareDesfireApplication* app = malloc(sizeof(MifareDesfireApplication)); - memset(app, 0, sizeof(MifareDesfireApplication)); - memcpy(app->id, &tmp[i * 3], 3); - if(!nfc_device_load_mifare_df_app(file, app)) { - free(app); - parsed_apps = false; - break; - } - *app_head = app; - app_head = &app->next; - } - if(!parsed_apps) { - // accept non-parsed apps, just log a warning: - FURI_LOG_W(TAG, "Non-parsed apps found!"); - } - } - parsed = true; - } while(false); - - free(tmp); - return parsed; -} - -static bool nfc_device_save_slix_data( - FlipperFormat* file, - NfcDevice* dev, - SlixTypeFeatures features, - const char* type) { - bool saved = false; - NfcVSlixData* data = &dev->dev_data.nfcv_data.sub_data.slix; - - do { - char msg[64]; - snprintf(msg, sizeof(msg), "%s specific data", type); - if(!flipper_format_write_comment_cstr(file, msg)) break; - if(!flipper_format_write_comment_cstr( - file, "Passwords are optional. If password is omitted, any password is accepted")) - break; - - if(features & SlixFeatureRead) { - if(data->flags & NfcVSlixDataFlagsHasKeyRead) { - if(!flipper_format_write_hex( - file, "Password Read", data->key_read, sizeof(data->key_read))) - break; - } - } - if(features & SlixFeatureWrite) { - if(data->flags & NfcVSlixDataFlagsHasKeyWrite) { - if(!flipper_format_write_hex( - file, "Password Write", data->key_write, sizeof(data->key_write))) - break; - } - } - if(features & SlixFeaturePrivacy) { - if(data->flags & NfcVSlixDataFlagsHasKeyPrivacy) { - if(!flipper_format_write_hex( - file, "Password Privacy", data->key_privacy, sizeof(data->key_privacy))) - break; - } - } - if(features & SlixFeatureDestroy) { - if(data->flags & NfcVSlixDataFlagsHasKeyDestroy) { - if(!flipper_format_write_hex( - file, "Password Destroy", data->key_destroy, sizeof(data->key_destroy))) - break; - } - } - if(features & SlixFeatureEas) { - if(data->flags & NfcVSlixDataFlagsHasKeyEas) { - if(!flipper_format_write_hex( - file, "Password EAS", data->key_eas, sizeof(data->key_eas))) - break; - } - } - if(features & SlixFeatureSignature) { - if(!flipper_format_write_comment_cstr( - file, - "This is the card's secp128r1 elliptic curve signature. It can not be calculated without knowing NXP's private key.")) - break; - if(!flipper_format_write_hex( - file, "Signature", data->signature, sizeof(data->signature))) - break; - } - if(features & SlixFeaturePrivacy) { - bool privacy = (data->flags & NfcVSlixDataFlagsPrivacy) ? true : false; - if(!flipper_format_write_bool(file, "Privacy Mode", &privacy, 1)) break; - } - if(features & SlixFeatureProtection) { - if(!flipper_format_write_comment_cstr(file, "Protection pointer configuration")) break; - if(!flipper_format_write_hex(file, "Protection pointer", &data->pp_pointer, 1)) break; - if(!flipper_format_write_hex(file, "Protection condition", &data->pp_condition, 1)) - break; - } - saved = true; - } while(false); - - return saved; -} - -bool nfc_device_load_slix_data(FlipperFormat* file, NfcDevice* dev, SlixTypeFeatures features) { - bool parsed = false; - NfcVSlixData* data = &dev->dev_data.nfcv_data.sub_data.slix; - memset(data, 0, sizeof(NfcVSlixData)); - - do { - data->flags = 0; - - if(features & SlixFeatureRead) { - if(flipper_format_key_exist(file, "Password Read")) { - if(!flipper_format_read_hex( - file, "Password Read", data->key_read, sizeof(data->key_read))) { - FURI_LOG_D(TAG, "Failed reading Password Read"); - break; - } - data->flags |= NfcVSlixDataFlagsHasKeyRead; - } - } - if(features & SlixFeatureWrite) { - if(flipper_format_key_exist(file, "Password Write")) { - if(!flipper_format_read_hex( - file, "Password Write", data->key_write, sizeof(data->key_write))) { - FURI_LOG_D(TAG, "Failed reading Password Write"); - break; - } - data->flags |= NfcVSlixDataFlagsHasKeyWrite; - } - } - if(features & SlixFeaturePrivacy) { - if(flipper_format_key_exist(file, "Password Privacy")) { - if(!flipper_format_read_hex( - file, "Password Privacy", data->key_privacy, sizeof(data->key_privacy))) { - FURI_LOG_D(TAG, "Failed reading Password Privacy"); - break; - } - data->flags |= NfcVSlixDataFlagsHasKeyPrivacy; - } - } - if(features & SlixFeatureDestroy) { - if(flipper_format_key_exist(file, "Password Destroy")) { - if(!flipper_format_read_hex( - file, "Password Destroy", data->key_destroy, sizeof(data->key_destroy))) { - FURI_LOG_D(TAG, "Failed reading Password Destroy"); - break; - } - data->flags |= NfcVSlixDataFlagsHasKeyDestroy; - } - } - if(features & SlixFeatureEas) { - if(flipper_format_key_exist(file, "Password EAS")) { - if(!flipper_format_read_hex( - file, "Password EAS", data->key_eas, sizeof(data->key_eas))) { - FURI_LOG_D(TAG, "Failed reading Password EAS"); - break; - } - data->flags |= NfcVSlixDataFlagsHasKeyEas; - } - } - if(features & SlixFeatureSignature) { - if(!flipper_format_read_hex( - file, "Signature", data->signature, sizeof(data->signature))) { - FURI_LOG_D(TAG, "Failed reading Signature"); - break; - } - } - if(features & SlixFeaturePrivacy) { - bool privacy; - if(!flipper_format_read_bool(file, "Privacy Mode", &privacy, 1)) { - FURI_LOG_D(TAG, "Failed reading Privacy Mode"); - break; - } - if(privacy) { - data->flags |= NfcVSlixDataFlagsPrivacy; - } - } - if(features & SlixFeatureProtection) { - if(!flipper_format_read_hex(file, "Protection pointer", &(data->pp_pointer), 1)) { - FURI_LOG_D(TAG, "Failed reading Protection pointer"); - break; - } - if(!flipper_format_read_hex(file, "Protection condition", &(data->pp_condition), 1)) { - FURI_LOG_D(TAG, "Failed reading Protection condition"); - break; - } - } - parsed = true; - } while(false); - - return parsed; -} - -static bool nfc_device_save_nfcv_data(FlipperFormat* file, NfcDevice* dev) { - bool saved = false; - NfcVData* data = &dev->dev_data.nfcv_data; - - do { - uint32_t temp_uint32 = 0; - uint8_t temp_uint8 = 0; - - if(!flipper_format_write_comment_cstr(file, "Data Storage Format Identifier")) break; - if(!flipper_format_write_hex(file, "DSFID", &(data->dsfid), 1)) break; - if(!flipper_format_write_comment_cstr(file, "Application Family Identifier")) break; - if(!flipper_format_write_hex(file, "AFI", &(data->afi), 1)) break; - if(!flipper_format_write_hex(file, "IC Reference", &(data->ic_ref), 1)) break; - temp_uint32 = data->block_num; - if(!flipper_format_write_comment_cstr(file, "Number of memory blocks, usually 0 to 256")) - break; - if(!flipper_format_write_uint32(file, "Block Count", &temp_uint32, 1)) break; - if(!flipper_format_write_comment_cstr(file, "Size of a single memory block, usually 4")) - break; - if(!flipper_format_write_hex(file, "Block Size", &(data->block_size), 1)) break; - if(!flipper_format_write_hex( - file, "Data Content", data->data, data->block_num * data->block_size)) - break; - if(!flipper_format_write_comment_cstr( - file, - "First byte: DSFID (0x01) / AFI (0x02) / EAS (0x04) / PPL (0x08) lock info, others: block lock info")) - break; - if(!flipper_format_write_hex( - file, "Security Status", data->security_status, 1 + data->block_num)) - break; - if(!flipper_format_write_comment_cstr( - file, - "Subtype of this card (0 = ISO15693, 1 = SLIX, 2 = SLIX-S, 3 = SLIX-L, 4 = SLIX2)")) - break; - temp_uint8 = (uint8_t)data->sub_type; - if(!flipper_format_write_hex(file, "Subtype", &temp_uint8, 1)) break; - - switch(data->sub_type) { - case NfcVTypePlain: - if(!flipper_format_write_comment_cstr(file, "End of ISO15693 parameters")) break; - saved = true; - break; - case NfcVTypeSlix: - saved = nfc_device_save_slix_data(file, dev, SlixFeatureSlix, "SLIX"); - break; - case NfcVTypeSlixS: - saved = nfc_device_save_slix_data(file, dev, SlixFeatureSlixS, "SLIX-S"); - break; - case NfcVTypeSlixL: - saved = nfc_device_save_slix_data(file, dev, SlixFeatureSlixL, "SLIX-L"); - break; - case NfcVTypeSlix2: - saved = nfc_device_save_slix_data(file, dev, SlixFeatureSlix2, "SLIX2"); - break; - default: - break; - } - } while(false); - - return saved; -} - -bool nfc_device_load_nfcv_data(FlipperFormat* file, NfcDevice* dev) { - bool parsed = false; - NfcVData* data = &dev->dev_data.nfcv_data; - - memset(data, 0x00, sizeof(NfcVData)); - - do { - uint32_t temp_uint32 = 0; - uint8_t temp_value = 0; - - if(!flipper_format_read_hex(file, "DSFID", &(data->dsfid), 1)) { - FURI_LOG_D(TAG, "Failed reading DSFID"); - break; - } - if(!flipper_format_read_hex(file, "AFI", &(data->afi), 1)) { - FURI_LOG_D(TAG, "Failed reading AFI"); - break; - } - if(!flipper_format_read_hex(file, "IC Reference", &(data->ic_ref), 1)) { - FURI_LOG_D(TAG, "Failed reading IC Reference"); - break; - } - if(!flipper_format_read_uint32(file, "Block Count", &temp_uint32, 1)) { - FURI_LOG_D(TAG, "Failed reading Block Count"); - break; - } - data->block_num = temp_uint32; - if(!flipper_format_read_hex(file, "Block Size", &(data->block_size), 1)) { - FURI_LOG_D(TAG, "Failed reading Block Size"); - break; - } - if(!flipper_format_read_hex( - file, "Data Content", data->data, data->block_num * data->block_size)) { - FURI_LOG_D(TAG, "Failed reading Data Content"); - break; - } - - /* optional, as added later */ - if(flipper_format_key_exist(file, "Security Status")) { - if(!flipper_format_read_hex( - file, "Security Status", data->security_status, 1 + data->block_num)) { - FURI_LOG_D(TAG, "Failed reading Security Status"); - break; - } - } - if(!flipper_format_read_hex(file, "Subtype", &temp_value, 1)) { - FURI_LOG_D(TAG, "Failed reading Subtype"); - break; - } - data->sub_type = temp_value; - - switch(data->sub_type) { - case NfcVTypePlain: - parsed = true; - break; - case NfcVTypeSlix: - parsed = nfc_device_load_slix_data(file, dev, SlixFeatureSlix); - break; - case NfcVTypeSlixS: - parsed = nfc_device_load_slix_data(file, dev, SlixFeatureSlixS); - break; - case NfcVTypeSlixL: - parsed = nfc_device_load_slix_data(file, dev, SlixFeatureSlixL); - break; - case NfcVTypeSlix2: - parsed = nfc_device_load_slix_data(file, dev, SlixFeatureSlix2); - break; - default: - break; - } - } while(false); - - return parsed; -} - -static bool nfc_device_save_bank_card_data(FlipperFormat* file, NfcDevice* dev) { - bool saved = false; - EmvData* data = &dev->dev_data.emv_data; - uint32_t data_temp = 0; - - do { - // Write Bank card specific data - if(!flipper_format_write_comment_cstr(file, "Bank card specific data")) break; - if(!flipper_format_write_hex(file, "AID", data->aid, data->aid_len)) break; - if(!flipper_format_write_string_cstr(file, "Name", data->name)) break; - if(!flipper_format_write_hex(file, "Number", data->number, data->number_len)) break; - if(data->exp_mon) { - uint8_t exp_data[2] = {data->exp_mon, data->exp_year}; - if(!flipper_format_write_hex(file, "Exp data", exp_data, sizeof(exp_data))) break; - } - if(data->country_code) { - data_temp = data->country_code; - if(!flipper_format_write_uint32(file, "Country code", &data_temp, 1)) break; - } - if(data->currency_code) { - data_temp = data->currency_code; - if(!flipper_format_write_uint32(file, "Currency code", &data_temp, 1)) break; - } - saved = true; - } while(false); - - return saved; -} - -bool nfc_device_load_bank_card_data(FlipperFormat* file, NfcDevice* dev) { - bool parsed = false; - EmvData* data = &dev->dev_data.emv_data; - memset(data, 0, sizeof(EmvData)); - uint32_t data_cnt = 0; - FuriString* temp_str; - temp_str = furi_string_alloc(); - - do { - // Load essential data - if(!flipper_format_get_value_count(file, "AID", &data_cnt)) break; - data->aid_len = data_cnt; - if(!flipper_format_read_hex(file, "AID", data->aid, data->aid_len)) break; - if(!flipper_format_read_string(file, "Name", temp_str)) { - furi_string_set_str(temp_str, "Unknown"); - } - strlcpy(data->name, furi_string_get_cstr(temp_str), sizeof(data->name)); - if(!flipper_format_get_value_count(file, "Number", &data_cnt)) { - data_cnt = 0; - } - data->number_len = data_cnt; - if(!flipper_format_read_hex(file, "Number", data->number, data->number_len)) { - memset(data->number, 0, sizeof(data->number)); - }; - parsed = true; - // Load optional data - uint8_t exp_data[2] = {}; - if(flipper_format_read_hex(file, "Exp data", exp_data, 2)) { - data->exp_mon = exp_data[0]; - data->exp_year = exp_data[1]; - } - if(flipper_format_read_uint32(file, "Country code", &data_cnt, 1)) { - data->country_code = data_cnt; - } - if(flipper_format_read_uint32(file, "Currency code", &data_cnt, 1)) { - data->currency_code = data_cnt; - } - } while(false); - - furi_string_free(temp_str); - return parsed; -} - -static void nfc_device_write_mifare_classic_block( - FuriString* block_str, - MfClassicData* data, - uint8_t block_num) { - furi_string_reset(block_str); - bool is_sec_trailer = mf_classic_is_sector_trailer(block_num); - if(is_sec_trailer) { - uint8_t sector_num = mf_classic_get_sector_by_block(block_num); - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, sector_num); - // Write key A - for(size_t i = 0; i < sizeof(sec_tr->key_a); i++) { - if(mf_classic_is_key_found(data, sector_num, MfClassicKeyA)) { - furi_string_cat_printf(block_str, "%02X ", sec_tr->key_a[i]); - } else { - furi_string_cat_printf(block_str, "?? "); - } - } - // Write Access bytes - for(size_t i = 0; i < MF_CLASSIC_ACCESS_BYTES_SIZE; i++) { - if(mf_classic_is_block_read(data, block_num)) { - furi_string_cat_printf(block_str, "%02X ", sec_tr->access_bits[i]); - } else { - furi_string_cat_printf(block_str, "?? "); - } - } - // Write key B - for(size_t i = 0; i < sizeof(sec_tr->key_b); i++) { - if(mf_classic_is_key_found(data, sector_num, MfClassicKeyB)) { - furi_string_cat_printf(block_str, "%02X ", sec_tr->key_b[i]); - } else { - furi_string_cat_printf(block_str, "?? "); - } - } - } else { - // Write data block - for(size_t i = 0; i < MF_CLASSIC_BLOCK_SIZE; i++) { - if(mf_classic_is_block_read(data, block_num)) { - furi_string_cat_printf(block_str, "%02X ", data->block[block_num].value[i]); - } else { - furi_string_cat_printf(block_str, "?? "); - } - } - } - furi_string_trim(block_str); -} - -static bool nfc_device_save_mifare_classic_data(FlipperFormat* file, NfcDevice* dev) { - bool saved = false; - MfClassicData* data = &dev->dev_data.mf_classic_data; - FuriString* temp_str; - temp_str = furi_string_alloc(); - uint16_t blocks = 0; - - // Save Mifare Classic specific data - do { - if(!flipper_format_write_comment_cstr(file, "Mifare Classic specific data")) break; - - if(data->type == MfClassicTypeMini) { - if(!flipper_format_write_string_cstr(file, "Mifare Classic type", "MINI")) break; - blocks = 20; - } else if(data->type == MfClassicType1k) { - if(!flipper_format_write_string_cstr(file, "Mifare Classic type", "1K")) break; - blocks = 64; - } else if(data->type == MfClassicType4k) { - if(!flipper_format_write_string_cstr(file, "Mifare Classic type", "4K")) break; - blocks = 256; - } - if(!flipper_format_write_uint32( - file, "Data format version", &nfc_mifare_classic_data_format_version, 1)) - break; - if(!flipper_format_write_comment_cstr( - file, "Mifare Classic blocks, \'??\' means unknown data")) - break; - bool block_saved = true; - FuriString* block_str; - block_str = furi_string_alloc(); - for(size_t i = 0; i < blocks; i++) { - furi_string_printf(temp_str, "Block %d", i); - nfc_device_write_mifare_classic_block(block_str, data, i); - if(!flipper_format_write_string(file, furi_string_get_cstr(temp_str), block_str)) { - block_saved = false; - break; - } - } - furi_string_free(block_str); - if(!block_saved) break; - saved = true; - } while(false); - - furi_string_free(temp_str); - return saved; -} - -static void nfc_device_load_mifare_classic_block( - FuriString* block_str, - MfClassicData* data, - uint8_t block_num) { - furi_string_trim(block_str); - MfClassicBlock block_tmp = {}; - bool is_sector_trailer = mf_classic_is_sector_trailer(block_num); - uint8_t sector_num = mf_classic_get_sector_by_block(block_num); - uint16_t block_unknown_bytes_mask = 0; - - furi_string_trim(block_str); - for(size_t i = 0; i < MF_CLASSIC_BLOCK_SIZE; i++) { - char hi = furi_string_get_char(block_str, 3 * i); - char low = furi_string_get_char(block_str, 3 * i + 1); - uint8_t byte = 0; - if(hex_char_to_uint8(hi, low, &byte)) { - block_tmp.value[i] = byte; - } else { - FURI_BIT_SET(block_unknown_bytes_mask, i); - } - } - - if(block_unknown_bytes_mask == 0xffff) { - // All data is unknown, exit - return; - } - - if(is_sector_trailer) { - MfClassicSectorTrailer* sec_tr_tmp = (MfClassicSectorTrailer*)&block_tmp; - // Load Key A - // Key A mask 0b0000000000111111 = 0x003f - if((block_unknown_bytes_mask & 0x003f) == 0) { - uint64_t key = nfc_util_bytes2num(sec_tr_tmp->key_a, sizeof(sec_tr_tmp->key_a)); - mf_classic_set_key_found(data, sector_num, MfClassicKeyA, key); - } - // Load Access Bits - // Access bits mask 0b0000001111000000 = 0x03c0 - if((block_unknown_bytes_mask & 0x03c0) == 0) { - mf_classic_set_block_read(data, block_num, &block_tmp); - } - // Load Key B - // Key B mask 0b1111110000000000 = 0xfc00 - if((block_unknown_bytes_mask & 0xfc00) == 0) { - uint64_t key = nfc_util_bytes2num(sec_tr_tmp->key_b, sizeof(sec_tr_tmp->key_b)); - mf_classic_set_key_found(data, sector_num, MfClassicKeyB, key); - } - } else { - if(block_unknown_bytes_mask == 0) { - mf_classic_set_block_read(data, block_num, &block_tmp); - } + if(instance->protocol_data) { + nfc_devices[instance->protocol]->reset(instance->protocol_data); } } -static bool nfc_device_load_mifare_classic_data(FlipperFormat* file, NfcDevice* dev) { - bool parsed = false; - MfClassicData* data = &dev->dev_data.mf_classic_data; - FuriString* temp_str; - uint32_t data_format_version = 0; - temp_str = furi_string_alloc(); - uint16_t data_blocks = 0; - memset(data, 0, sizeof(MfClassicData)); - - do { - // Read Mifare Classic type - if(!flipper_format_read_string(file, "Mifare Classic type", temp_str)) break; - if(!furi_string_cmp(temp_str, "MINI")) { - data->type = MfClassicTypeMini; - data_blocks = 20; - } else if(!furi_string_cmp(temp_str, "1K")) { - data->type = MfClassicType1k; - data_blocks = 64; - } else if(!furi_string_cmp(temp_str, "4K")) { - data->type = MfClassicType4k; - data_blocks = 256; - } else { - break; - } - - bool old_format = false; - // Read Mifare Classic format version - if(!flipper_format_read_uint32(file, "Data format version", &data_format_version, 1)) { - // Load unread sectors with zero keys access for backward compatibility - if(!flipper_format_rewind(file)) break; - old_format = true; - } else { - if(data_format_version < nfc_mifare_classic_data_format_version) { - old_format = true; - } - } - - // Read Mifare Classic blocks - bool block_read = true; - FuriString* block_str; - block_str = furi_string_alloc(); - for(size_t i = 0; i < data_blocks; i++) { - furi_string_printf(temp_str, "Block %d", i); - if(!flipper_format_read_string(file, furi_string_get_cstr(temp_str), block_str)) { - block_read = false; - break; - } - nfc_device_load_mifare_classic_block(block_str, data, i); - } - furi_string_free(block_str); - if(!block_read) break; - - // Set keys and blocks as unknown for backward compatibility - if(old_format) { - data->key_a_mask = 0ULL; - data->key_b_mask = 0ULL; - memset(data->block_read_mask, 0, sizeof(data->block_read_mask)); - } - - parsed = true; - } while(false); - - furi_string_free(temp_str); - return parsed; +NfcProtocol nfc_device_get_protocol(const NfcDevice* instance) { + furi_assert(instance); + return instance->protocol; } -static void nfc_device_get_key_cache_file_path(NfcDevice* dev, FuriString* file_path) { - uint8_t* uid = dev->dev_data.nfc_data.uid; - uint8_t uid_len = dev->dev_data.nfc_data.uid_len; - furi_string_set(file_path, NFC_DEVICE_KEYS_FOLDER "/"); - for(size_t i = 0; i < uid_len; i++) { - furi_string_cat_printf(file_path, "%02X", uid[i]); +const NfcDeviceData* nfc_device_get_data(const NfcDevice* instance, NfcProtocol protocol) { + return nfc_device_get_data_ptr(instance, protocol); +} + +const char* nfc_device_get_protocol_name(NfcProtocol protocol) { + furi_assert(protocol < NfcProtocolNum); + + return nfc_devices[protocol]->protocol_name; +} + +const char* nfc_device_get_name(const NfcDevice* instance, NfcDeviceNameType name_type) { + furi_assert(instance); + furi_assert(instance->protocol < NfcProtocolNum); + + return nfc_devices[instance->protocol]->get_name(instance->protocol_data, name_type); +} + +const uint8_t* nfc_device_get_uid(const NfcDevice* instance, size_t* uid_len) { + furi_assert(instance); + furi_assert(instance->protocol < NfcProtocolNum); + + return nfc_devices[instance->protocol]->get_uid(instance->protocol_data, uid_len); +} + +bool nfc_device_set_uid(NfcDevice* instance, const uint8_t* uid, size_t uid_len) { + furi_assert(instance); + furi_assert(instance->protocol < NfcProtocolNum); + + return nfc_devices[instance->protocol]->set_uid(instance->protocol_data, uid, uid_len); +} + +void nfc_device_set_data( + NfcDevice* instance, + NfcProtocol protocol, + const NfcDeviceData* protocol_data) { + furi_assert(instance); + furi_assert(protocol < NfcProtocolNum); + + nfc_device_clear(instance); + + instance->protocol = protocol; + instance->protocol_data = nfc_devices[protocol]->alloc(); + + nfc_devices[protocol]->copy(instance->protocol_data, protocol_data); +} + +void nfc_device_copy_data( + const NfcDevice* instance, + NfcProtocol protocol, + NfcDeviceData* protocol_data) { + furi_assert(instance); + furi_assert(protocol < NfcProtocolNum); + furi_assert(protocol_data); + + if(instance->protocol != protocol) { + furi_crash(NFC_DEV_TYPE_ERROR); } - furi_string_cat_printf(file_path, NFC_DEVICE_KEYS_EXTENSION); + + nfc_devices[protocol]->copy(protocol_data, instance->protocol_data); } -static bool nfc_device_save_mifare_classic_keys(NfcDevice* dev) { - FlipperFormat* file = flipper_format_file_alloc(dev->storage); - MfClassicData* data = &dev->dev_data.mf_classic_data; - FuriString* temp_str; - temp_str = furi_string_alloc(); +bool nfc_device_is_equal_data( + const NfcDevice* instance, + NfcProtocol protocol, + const NfcDeviceData* protocol_data) { + furi_assert(instance); + furi_assert(protocol < NfcProtocolNum); + furi_assert(protocol_data); - nfc_device_get_key_cache_file_path(dev, temp_str); - bool save_success = false; - do { - if(!storage_simply_mkdir(dev->storage, NFC_DEVICE_KEYS_FOLDER)) break; - if(!storage_simply_remove(dev->storage, furi_string_get_cstr(temp_str))) break; - if(!flipper_format_file_open_always(file, furi_string_get_cstr(temp_str))) break; - if(!flipper_format_write_header_cstr(file, nfc_keys_file_header, nfc_keys_file_version)) - break; - if(data->type == MfClassicTypeMini) { - if(!flipper_format_write_string_cstr(file, "Mifare Classic type", "MINI")) break; - } else if(data->type == MfClassicType1k) { - if(!flipper_format_write_string_cstr(file, "Mifare Classic type", "1K")) break; - } else if(data->type == MfClassicType4k) { - if(!flipper_format_write_string_cstr(file, "Mifare Classic type", "4K")) break; - } - if(!flipper_format_write_hex_uint64(file, "Key A map", &data->key_a_mask, 1)) break; - if(!flipper_format_write_hex_uint64(file, "Key B map", &data->key_b_mask, 1)) break; - uint8_t sector_num = mf_classic_get_total_sectors_num(data->type); - bool key_save_success = true; - for(size_t i = 0; (i < sector_num) && (key_save_success); i++) { - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, i); - if(FURI_BIT(data->key_a_mask, i)) { - furi_string_printf(temp_str, "Key A sector %d", i); - key_save_success = flipper_format_write_hex( - file, furi_string_get_cstr(temp_str), sec_tr->key_a, 6); - } - if(!key_save_success) break; - if(FURI_BIT(data->key_b_mask, i)) { - furi_string_printf(temp_str, "Key B sector %d", i); - key_save_success = flipper_format_write_hex( - file, furi_string_get_cstr(temp_str), sec_tr->key_b, 6); - } - } - save_success = key_save_success; - } while(false); - - flipper_format_free(file); - furi_string_free(temp_str); - return save_success; + return instance->protocol == protocol && + nfc_devices[protocol]->is_equal(instance->protocol_data, protocol_data); } -bool nfc_device_load_key_cache(NfcDevice* dev) { - furi_assert(dev); - FuriString* temp_str; - temp_str = furi_string_alloc(); +bool nfc_device_is_equal(const NfcDevice* instance, const NfcDevice* other) { + furi_assert(instance); + furi_assert(other); - MfClassicData* data = &dev->dev_data.mf_classic_data; - nfc_device_get_key_cache_file_path(dev, temp_str); - FlipperFormat* file = flipper_format_file_alloc(dev->storage); - - bool load_success = false; - do { - if(storage_common_stat(dev->storage, furi_string_get_cstr(temp_str), NULL) != FSE_OK) - break; - if(!flipper_format_file_open_existing(file, furi_string_get_cstr(temp_str))) break; - uint32_t version = 0; - if(!flipper_format_read_header(file, temp_str, &version)) break; - if(furi_string_cmp_str(temp_str, nfc_keys_file_header)) break; - if(version != nfc_keys_file_version) break; - if(!flipper_format_read_string(file, "Mifare Classic type", temp_str)) break; - if(!furi_string_cmp(temp_str, "MINI")) { - data->type = MfClassicTypeMini; - } else if(!furi_string_cmp(temp_str, "1K")) { - data->type = MfClassicType1k; - } else if(!furi_string_cmp(temp_str, "4K")) { - data->type = MfClassicType4k; - } else { - break; - } - if(!flipper_format_read_hex_uint64(file, "Key A map", &data->key_a_mask, 1)) break; - if(!flipper_format_read_hex_uint64(file, "Key B map", &data->key_b_mask, 1)) break; - uint8_t sectors = mf_classic_get_total_sectors_num(data->type); - bool key_read_success = true; - for(size_t i = 0; (i < sectors) && (key_read_success); i++) { - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, i); - if(FURI_BIT(data->key_a_mask, i)) { - furi_string_printf(temp_str, "Key A sector %d", i); - key_read_success = flipper_format_read_hex( - file, furi_string_get_cstr(temp_str), sec_tr->key_a, 6); - } - if(!key_read_success) break; - if(FURI_BIT(data->key_b_mask, i)) { - furi_string_printf(temp_str, "Key B sector %d", i); - key_read_success = flipper_format_read_hex( - file, furi_string_get_cstr(temp_str), sec_tr->key_b, 6); - } - } - load_success = key_read_success; - } while(false); - - furi_string_free(temp_str); - flipper_format_free(file); - - return load_success; + return nfc_device_is_equal_data(instance, other->protocol, other->protocol_data); } -void nfc_device_set_name(NfcDevice* dev, const char* name) { - furi_assert(dev); +void nfc_device_set_loading_callback( + NfcDevice* instance, + NfcLoadingCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); - strlcpy(dev->dev_name, name, NFC_DEV_NAME_MAX_LEN); + instance->loading_callback = callback; + instance->loading_callback_context = context; } -static void nfc_device_get_path_without_ext(FuriString* orig_path, FuriString* shadow_path) { - // TODO: this won't work if there is ".nfc" anywhere in the path other than - // at the end - size_t ext_start = furi_string_search(orig_path, NFC_APP_FILENAME_EXTENSION); - furi_string_set_n(shadow_path, orig_path, 0, ext_start); -} - -static void nfc_device_get_shadow_path(FuriString* orig_path, FuriString* shadow_path) { - nfc_device_get_path_without_ext(orig_path, shadow_path); - furi_string_cat_printf(shadow_path, "%s", NFC_APP_SHADOW_EXTENSION); -} - -static void nfc_device_get_folder_from_path(FuriString* path, FuriString* folder) { - size_t last_slash = furi_string_search_rchar(path, '/'); - if(last_slash == FURI_STRING_FAILURE) { - // No slashes in the path, treat the whole path as a folder - furi_string_set(folder, path); - } else { - furi_string_set_n(folder, path, 0, last_slash); - } -} - -bool nfc_device_save(NfcDevice* dev, const char* dev_name) { - furi_assert(dev); +bool nfc_device_save(NfcDevice* instance, const char* path) { + furi_assert(instance); + furi_assert(instance->protocol < NfcProtocolNum); + furi_assert(path); bool saved = false; - FlipperFormat* file = flipper_format_file_alloc(dev->storage); - FuriHalNfcDevData* data = &dev->dev_data.nfc_data; - FuriString* temp_str; - temp_str = furi_string_alloc(); + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_buffered_file_alloc(storage); + FuriString* temp_str = furi_string_alloc(); + + if(instance->loading_callback) { + instance->loading_callback(instance->loading_callback_context, true); + } do { - // Create directory if necessary - FuriString* folder = furi_string_alloc(); - // Get folder from filename (filename is in the form of "folder/filename.nfc", so the folder is "folder/") - furi_string_set(temp_str, dev_name); - // Get folder from filename - nfc_device_get_folder_from_path(temp_str, folder); - FURI_LOG_I("Nfc", "Saving to folder %s", furi_string_get_cstr(folder)); - if(!storage_simply_mkdir(dev->storage, furi_string_get_cstr(folder))) { - FURI_LOG_E("Nfc", "Failed to create folder %s", furi_string_get_cstr(folder)); - break; - } - furi_string_free(folder); - // First remove nfc device file if it was saved // Open file - if(!flipper_format_file_open_always(file, furi_string_get_cstr(temp_str))) break; + if(!flipper_format_buffered_file_open_always(ff, path)) break; + // Write header - if(!flipper_format_write_header_cstr(file, nfc_file_header, nfc_file_version)) break; - // Write nfc device type - if(!flipper_format_write_comment_cstr( - file, "Nfc device type can be UID, Mifare Ultralight, Mifare Classic or ISO15693")) + if(!flipper_format_write_header_cstr(ff, NFC_FILE_HEADER, NFC_CURRENT_FORMAT_VERSION)) break; - nfc_device_prepare_format_string(dev, temp_str); - if(!flipper_format_write_string(file, "Device type", temp_str)) break; + + // Write allowed device types + furi_string_printf(temp_str, "%s can be ", NFC_DEVICE_TYPE_KEY); + for(NfcProtocol protocol = 0; protocol < NfcProtocolNum; ++protocol) { + furi_string_cat(temp_str, nfc_devices[protocol]->protocol_name); + if(protocol < NfcProtocolNum - 1) { + furi_string_cat(temp_str, ", "); + } + } + + if(!flipper_format_write_comment(ff, temp_str)) break; + + // Write device type + if(!flipper_format_write_string_cstr( + ff, NFC_DEVICE_TYPE_KEY, nfc_devices[instance->protocol]->protocol_name)) + break; + // Write UID - if(!flipper_format_write_comment_cstr(file, "UID is common for all formats")) break; - if(!flipper_format_write_hex(file, "UID", data->uid, data->uid_len)) break; + furi_string_printf(temp_str, "%s is common for all formats", NFC_DEVICE_UID_KEY); + if(!flipper_format_write_comment(ff, temp_str)) break; - if(dev->format != NfcDeviceSaveFormatNfcV) { - // Write ATQA, SAK - if(!flipper_format_write_comment_cstr(file, "ISO14443 specific fields")) break; - // Save ATQA in MSB order for correct companion apps display - uint8_t atqa[2] = {data->atqa[1], data->atqa[0]}; - if(!flipper_format_write_hex(file, "ATQA", atqa, 2)) break; - if(!flipper_format_write_hex(file, "SAK", &data->sak, 1)) break; - } + size_t uid_len; + const uint8_t* uid = nfc_device_get_uid(instance, &uid_len); + if(!flipper_format_write_hex(ff, NFC_DEVICE_UID_KEY, uid, uid_len)) break; + + // Write protocol-dependent data + if(!nfc_devices[instance->protocol]->save(instance->protocol_data, ff)) break; - // Save more data if necessary - if(dev->format == NfcDeviceSaveFormatMifareUl) { - if(!nfc_device_save_mifare_ul_data(file, dev)) break; - } else if(dev->format == NfcDeviceSaveFormatMifareDesfire) { - if(!nfc_device_save_mifare_df_data(file, dev)) break; - } else if(dev->format == NfcDeviceSaveFormatNfcV) { - if(!nfc_device_save_nfcv_data(file, dev)) break; - } else if(dev->format == NfcDeviceSaveFormatBankCard) { - if(!nfc_device_save_bank_card_data(file, dev)) break; - } else if(dev->format == NfcDeviceSaveFormatMifareClassic) { - // Save data - if(!nfc_device_save_mifare_classic_data(file, dev)) break; - // Save keys cache - if(!nfc_device_save_mifare_classic_keys(dev)) break; - } saved = true; - } while(0); + } while(false); - if(!saved) { //-V547 - dialog_message_show_storage_error(dev->dialogs, "Can not save\nkey file"); + if(instance->loading_callback) { + instance->loading_callback(instance->loading_callback_context, false); } + furi_string_free(temp_str); - flipper_format_free(file); + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + return saved; } -bool nfc_device_save_shadow(NfcDevice* dev, const char* path) { - dev->shadow_file_exist = true; - // Replace extension from .nfc to .shd if necessary - FuriString* orig_path = furi_string_alloc(); - furi_string_set_str(orig_path, path); - FuriString* shadow_path = furi_string_alloc(); - nfc_device_get_shadow_path(orig_path, shadow_path); +static bool nfc_device_load_uid( + FlipperFormat* ff, + uint8_t* uid, + uint32_t* uid_len, + const uint32_t uid_maxlen) { + bool loaded = false; - bool file_saved = nfc_device_save(dev, furi_string_get_cstr(shadow_path)); - furi_string_free(orig_path); - furi_string_free(shadow_path); + do { + uint32_t uid_len_current; + if(!flipper_format_get_value_count(ff, NFC_DEVICE_UID_KEY, &uid_len_current)) break; + if(uid_len_current > uid_maxlen) break; + if(!flipper_format_read_hex(ff, NFC_DEVICE_UID_KEY, uid, uid_len_current)) break; - return file_saved; + *uid_len = uid_len_current; + loaded = true; + } while(false); + + return loaded; } -static bool nfc_device_load_data(NfcDevice* dev, FuriString* path, bool show_dialog) { - bool parsed = false; - FlipperFormat* file = flipper_format_file_alloc(dev->storage); - FuriHalNfcDevData* data = &dev->dev_data.nfc_data; - uint32_t data_cnt = 0; +static bool nfc_device_load_unified(NfcDevice* instance, FlipperFormat* ff, uint32_t version) { + bool loaded = false; + + FuriString* temp_str = furi_string_alloc(); + + do { + // Read Nfc device type + if(!flipper_format_read_string(ff, NFC_DEVICE_TYPE_KEY, temp_str)) break; + + // Detect protocol + NfcProtocol protocol; + for(protocol = 0; protocol < NfcProtocolNum; ++protocol) { + if(furi_string_equal(temp_str, nfc_devices[protocol]->protocol_name)) { + break; + } + } + + if(protocol == NfcProtocolNum) break; + + nfc_device_clear(instance); + + instance->protocol = protocol; + instance->protocol_data = nfc_devices[protocol]->alloc(); + + // Load UID + uint8_t uid[NFC_DEVICE_UID_MAX_LEN]; + uint32_t uid_len; + + if(!nfc_device_load_uid(ff, uid, &uid_len, NFC_DEVICE_UID_MAX_LEN)) break; + if(!nfc_device_set_uid(instance, uid, uid_len)) break; + + // Load data + if(!nfc_devices[protocol]->load(instance->protocol_data, ff, version)) break; + + loaded = true; + } while(false); + + if(!loaded) { + nfc_device_clear(instance); + } + + furi_string_free(temp_str); + return loaded; +} + +static bool nfc_device_load_legacy(NfcDevice* instance, FlipperFormat* ff, uint32_t version) { + bool loaded = false; + + FuriString* temp_str = furi_string_alloc(); + + do { + // Read Nfc device type + if(!flipper_format_read_string(ff, NFC_DEVICE_TYPE_KEY, temp_str)) break; + + nfc_device_clear(instance); + + // Detect protocol + for(NfcProtocol protocol = 0; protocol < NfcProtocolNum; protocol++) { + instance->protocol = protocol; + instance->protocol_data = nfc_devices[protocol]->alloc(); + + // Verify protocol + if(nfc_devices[protocol]->verify(instance->protocol_data, temp_str)) { + uint8_t uid[NFC_DEVICE_UID_MAX_LEN]; + uint32_t uid_len; + + // Load data + loaded = nfc_device_load_uid(ff, uid, &uid_len, NFC_DEVICE_UID_MAX_LEN) && + nfc_device_set_uid(instance, uid, uid_len) && + nfc_devices[protocol]->load(instance->protocol_data, ff, version); + break; + } + + nfc_device_clear(instance); + } + + } while(false); + + furi_string_free(temp_str); + return loaded; +} + +bool nfc_device_load(NfcDevice* instance, const char* path) { + furi_assert(instance); + furi_assert(path); + + bool loaded = false; + Storage* storage = furi_record_open(RECORD_STORAGE); + FlipperFormat* ff = flipper_format_buffered_file_alloc(storage); + FuriString* temp_str; temp_str = furi_string_alloc(); - bool deprecated_version = false; - // Version 2 of file format had ATQA bytes swapped - uint32_t version_with_lsb_atqa = 2; - - if(dev->loading_cb) { - dev->loading_cb(dev->loading_cb_ctx, true); + if(instance->loading_callback) { + instance->loading_callback(instance->loading_callback_context, true); } do { - // Check existence of shadow file - nfc_device_get_shadow_path(path, temp_str); - dev->shadow_file_exist = - storage_common_stat(dev->storage, furi_string_get_cstr(temp_str), NULL) == FSE_OK; - // Open shadow file if it exists. If not - open original - if(dev->shadow_file_exist) { - if(!flipper_format_file_open_existing(file, furi_string_get_cstr(temp_str))) break; - } else { - if(!flipper_format_file_open_existing(file, furi_string_get_cstr(path))) break; - } + if(!flipper_format_buffered_file_open_existing(ff, path)) break; + // Read and verify file header uint32_t version = 0; - if(!flipper_format_read_header(file, temp_str, &version)) break; - if(furi_string_cmp_str(temp_str, nfc_file_header)) break; - if(version != nfc_file_version) { - if(version < version_with_lsb_atqa) { - deprecated_version = true; - break; - } - } - // Read Nfc device type - if(!flipper_format_read_string(file, "Device type", temp_str)) break; - if(!nfc_device_parse_format_string(dev, temp_str)) break; - // Read and parse UID, ATQA and SAK - if(!flipper_format_get_value_count(file, "UID", &data_cnt)) break; - if(!(data_cnt == 4 || data_cnt == 7 || data_cnt == 8)) break; - data->uid_len = data_cnt; - if(!flipper_format_read_hex(file, "UID", data->uid, data->uid_len)) break; - if(dev->format != NfcDeviceSaveFormatNfcV) { - if(version == version_with_lsb_atqa) { - if(!flipper_format_read_hex(file, "ATQA", data->atqa, 2)) break; - } else { - uint8_t atqa[2] = {}; - if(!flipper_format_read_hex(file, "ATQA", atqa, 2)) break; - data->atqa[0] = atqa[1]; - data->atqa[1] = atqa[0]; - } - if(!flipper_format_read_hex(file, "SAK", &data->sak, 1)) break; - } - // Load CUID - uint8_t* cuid_start = data->uid; - if(data->uid_len == 7) { - cuid_start = &data->uid[3]; - } - data->cuid = (cuid_start[0] << 24) | (cuid_start[1] << 16) | (cuid_start[2] << 8) | - (cuid_start[3]); - // Parse other data - if(dev->format == NfcDeviceSaveFormatMifareUl) { - if(!nfc_device_load_mifare_ul_data(file, dev)) break; - } else if(dev->format == NfcDeviceSaveFormatMifareClassic) { - if(!nfc_device_load_mifare_classic_data(file, dev)) break; - } else if(dev->format == NfcDeviceSaveFormatMifareDesfire) { - if(!nfc_device_load_mifare_df_data(file, dev)) break; - } else if(dev->format == NfcDeviceSaveFormatNfcV) { - if(!nfc_device_load_nfcv_data(file, dev)) break; - } else if(dev->format == NfcDeviceSaveFormatBankCard) { - if(!nfc_device_load_bank_card_data(file, dev)) break; - } - parsed = true; + if(!flipper_format_read_header(ff, temp_str, &version)) break; + + if(furi_string_cmp_str(temp_str, NFC_FILE_HEADER)) break; + if(version < NFC_MINIMUM_SUPPORTED_FORMAT_VERSION) break; + + // Select loading method + loaded = (version < NFC_UNIFIED_FORMAT_VERSION) ? + nfc_device_load_legacy(instance, ff, version) : + nfc_device_load_unified(instance, ff, version); + } while(false); - if(dev->loading_cb) { - dev->loading_cb(dev->loading_cb_ctx, false); - } - - if((!parsed) && (show_dialog)) { - if(deprecated_version) { - dialog_message_show_storage_error(dev->dialogs, "File format deprecated"); - } else { - dialog_message_show_storage_error(dev->dialogs, "Can not parse\nfile"); - } + if(instance->loading_callback) { + instance->loading_callback(instance->loading_callback_context, false); } furi_string_free(temp_str); - flipper_format_free(file); - return parsed; -} - -bool nfc_device_load(NfcDevice* dev, const char* file_path, bool show_dialog) { - furi_assert(dev); - furi_assert(file_path); - - // Load device data - furi_string_set(dev->load_path, file_path); - bool dev_load = nfc_device_load_data(dev, dev->load_path, show_dialog); - if(dev_load) { - // Set device name - FuriString* filename; - filename = furi_string_alloc(); - path_extract_filename_no_ext(file_path, filename); - nfc_device_set_name(dev, furi_string_get_cstr(filename)); - furi_string_free(filename); - } - - return dev_load; -} - -bool nfc_file_select(NfcDevice* dev) { - furi_assert(dev); - const char* folder = furi_string_get_cstr(dev->folder); - - // Input events and views are managed by file_browser - - const DialogsFileBrowserOptions browser_options = { - .extension = NFC_APP_FILENAME_EXTENSION, - .skip_assets = true, - .hide_dot_files = true, - .icon = &I_Nfc_10px, - .hide_ext = true, - .item_loader_callback = NULL, - .item_loader_context = NULL, - .base_path = folder, - }; - - bool res = - dialog_file_browser_show(dev->dialogs, dev->load_path, dev->load_path, &browser_options); - - if(res) { - FuriString* filename; - filename = furi_string_alloc(); - path_extract_filename(dev->load_path, filename, true); - strncpy(dev->dev_name, furi_string_get_cstr(filename), NFC_DEV_NAME_MAX_LEN); - res = nfc_device_load_data(dev, dev->load_path, true); - if(res) { - nfc_device_set_name(dev, dev->dev_name); - } - furi_string_free(filename); - } - - return res; -} - -void nfc_device_data_clear(NfcDeviceData* dev_data) { - if(dev_data->protocol == NfcDeviceProtocolMifareDesfire) { - mf_df_clear(&dev_data->mf_df_data); - } else if(dev_data->protocol == NfcDeviceProtocolMifareClassic) { - memset(&dev_data->mf_classic_data, 0, sizeof(MfClassicData)); - } else if(dev_data->protocol == NfcDeviceProtocolMifareUl) { - mf_ul_reset(&dev_data->mf_ul_data); - } else if(dev_data->protocol == NfcDeviceProtocolEMV) { - memset(&dev_data->emv_data, 0, sizeof(EmvData)); - } - - furi_string_reset(dev_data->parsed_data); - - memset(&dev_data->nfc_data, 0, sizeof(FuriHalNfcDevData)); - dev_data->protocol = NfcDeviceProtocolUnknown; - furi_string_reset(dev_data->parsed_data); -} - -void nfc_device_clear(NfcDevice* dev) { - furi_assert(dev); - - nfc_device_set_name(dev, ""); - nfc_device_data_clear(&dev->dev_data); - dev->format = NfcDeviceSaveFormatUid; - furi_string_reset(dev->load_path); -} - -bool nfc_device_delete(NfcDevice* dev, bool use_load_path) { - furi_assert(dev); - - bool deleted = false; - FuriString* file_path; - file_path = furi_string_alloc(); - - do { - // Delete original file - if(use_load_path && !furi_string_empty(dev->load_path)) { - furi_string_set(file_path, dev->load_path); - } else { - furi_string_printf( - file_path, - "%s/%s%s", - furi_string_get_cstr(dev->folder), - dev->dev_name, - NFC_APP_FILENAME_EXTENSION); - } - if(!storage_simply_remove(dev->storage, furi_string_get_cstr(file_path))) break; - // Delete shadow file if it exists - if(dev->shadow_file_exist) { - if(use_load_path && !furi_string_empty(dev->load_path)) { - nfc_device_get_shadow_path(dev->load_path, file_path); - } else { - furi_string_printf( - file_path, - "%s/%s%s", - furi_string_get_cstr(dev->folder), - dev->dev_name, - NFC_APP_SHADOW_EXTENSION); - } - if(!storage_simply_remove(dev->storage, furi_string_get_cstr(file_path))) break; - } - deleted = true; - } while(0); - - if(!deleted) { - dialog_message_show_storage_error(dev->dialogs, "Can not remove file"); - } - - furi_string_free(file_path); - return deleted; -} - -bool nfc_device_restore(NfcDevice* dev, bool use_load_path) { - furi_assert(dev); - furi_assert(dev->shadow_file_exist); - - bool restored = false; - FuriString* path; - - path = furi_string_alloc(); - - do { - if(use_load_path && !furi_string_empty(dev->load_path)) { - nfc_device_get_shadow_path(dev->load_path, path); - } else { - furi_string_printf( - path, - "%s/%s%s", - furi_string_get_cstr(dev->folder), - dev->dev_name, - NFC_APP_SHADOW_EXTENSION); - } - if(!storage_simply_remove(dev->storage, furi_string_get_cstr(path))) break; - dev->shadow_file_exist = false; - if(use_load_path && !furi_string_empty(dev->load_path)) { - furi_string_set(path, dev->load_path); - } else { - furi_string_printf( - path, - "%s/%s%s", - furi_string_get_cstr(dev->folder), - dev->dev_name, - NFC_APP_FILENAME_EXTENSION); - } - if(!nfc_device_load_data(dev, path, true)) break; - restored = true; - } while(0); - - furi_string_free(path); - return restored; -} - -void nfc_device_set_loading_callback(NfcDevice* dev, NfcLoadingCallback callback, void* context) { - furi_assert(dev); - - dev->loading_cb = callback; - dev->loading_cb_ctx = context; + flipper_format_free(ff); + furi_record_close(RECORD_STORAGE); + + return loaded; } diff --git a/lib/nfc/nfc_device.h b/lib/nfc/nfc_device.h index 1470b306b..6636e7c76 100644 --- a/lib/nfc/nfc_device.h +++ b/lib/nfc/nfc_device.h @@ -1,127 +1,265 @@ +/** + * @file nfc_device.h + * @brief Abstract interface for managing NFC device data. + * + * Under the hood, it makes use of the protocol-specific functions that each one of them provides + * and abstracts it with a protocol-independent API. + * + * It does not perform any signal processing, but merely serves as a container with some handy + * operations such as loading and saving from and to a file. + */ #pragma once +#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "protocols/nfc_device_base.h" +#include "protocols/nfc_protocol.h" #ifdef __cplusplus extern "C" { #endif -#define NFC_DEV_NAME_MAX_LEN 22 -#define NFC_READER_DATA_MAX_SIZE 64 -#define NFC_DICT_KEY_BATCH_SIZE 10 - -#define NFC_APP_FILENAME_PREFIX "NFC" -#define NFC_APP_FILENAME_EXTENSION ".nfc" -#define NFC_APP_SHADOW_EXTENSION ".shd" +/** + * @brief NfcDevice opaque type definition. + */ +typedef struct NfcDevice NfcDevice; +/** + * @brief Loading callback function signature. + * + * A function with such signature can be set as a callback to indicate + * the completion (or a failure) of nfc_device_load() and nfc_device_save() functions. + * + * This facility is commonly used to control GUI elements, such as progress dialogs. + * + * @param[in] context user-defined context that was passed in nfc_device_set_loading_callback(). + * @param[in] state true if the data was loaded successfully, false otherwise. + */ typedef void (*NfcLoadingCallback)(void* context, bool state); -typedef enum { - NfcDeviceProtocolUnknown, - NfcDeviceProtocolEMV, - NfcDeviceProtocolMifareUl, - NfcDeviceProtocolMifareClassic, - NfcDeviceProtocolMifareDesfire, - NfcDeviceProtocolNfcV -} NfcProtocol; - -typedef enum { - NfcDeviceSaveFormatUid, - NfcDeviceSaveFormatBankCard, - NfcDeviceSaveFormatMifareUl, - NfcDeviceSaveFormatMifareClassic, - NfcDeviceSaveFormatMifareDesfire, - NfcDeviceSaveFormatNfcV, -} NfcDeviceSaveFormat; - -typedef struct { - uint8_t data[NFC_READER_DATA_MAX_SIZE]; - uint16_t size; -} NfcReaderRequestData; - -typedef struct { - MfClassicDict* dict; - uint8_t current_sector; -} NfcMfClassicDictAttackData; - -typedef enum { - NfcReadModeAuto, - NfcReadModeMfClassic, - NfcReadModeMfUltralight, - NfcReadModeMfDesfire, - NfcReadModeEMV, - NfcReadModeNFCA, -} NfcReadMode; - -typedef struct { - FuriHalNfcDevData nfc_data; - NfcProtocol protocol; - NfcReadMode read_mode; - union { - NfcReaderRequestData reader_data; - NfcMfClassicDictAttackData mf_classic_dict_attack_data; - MfUltralightAuth mf_ul_auth; - }; - union { - EmvData emv_data; - MfUltralightData mf_ul_data; - MfClassicData mf_classic_data; - MifareDesfireData mf_df_data; - NfcVData nfcv_data; - }; - FuriString* parsed_data; -} NfcDeviceData; - -typedef struct { - Storage* storage; - DialogsApp* dialogs; - NfcDeviceData dev_data; - char dev_name[NFC_DEV_NAME_MAX_LEN + 1]; - FuriString* load_path; - FuriString* folder; - NfcDeviceSaveFormat format; - bool shadow_file_exist; - - NfcLoadingCallback loading_cb; - void* loading_cb_ctx; -} NfcDevice; - +/** + * @brief Allocate an NfcDevice instance. + * + * A newly created instance does not hold any data and thus is considered invalid. The most common + * use case would be to set its data by calling nfc_device_set_data() right afterwards. + * + * @returns pointer to the allocated instance. + */ NfcDevice* nfc_device_alloc(); -void nfc_device_free(NfcDevice* nfc_dev); +/** + * @brief Delete an NfcDevice instance. + * + * @param[in,out] instance pointer to the instance to be deleted. + */ +void nfc_device_free(NfcDevice* instance); -void nfc_device_set_name(NfcDevice* dev, const char* name); +/** + * @brief Clear an NfcDevice instance. + * + * All data contained in the instance will be deleted and the instance itself will become invalid + * as if it was just allocated. + * + * @param[in,out] instance pointer to the instance to be cleared. + */ +void nfc_device_clear(NfcDevice* instance); -bool nfc_device_save(NfcDevice* dev, const char* dev_name); +/** + * @brief Reset an NfcDevice instance. + * + * The data contained in the instance will be reset according to the protocol-defined procedure. + * Unlike the nfc_device_clear() function, the instance will remain valid. + * + * @param[in,out] instance pointer to the instance to be reset. + */ +void nfc_device_reset(NfcDevice* instance); -bool nfc_device_save_shadow(NfcDevice* dev, const char* dev_name); +/** + * @brief Get the protocol identifier from an NfcDevice instance. + * + * If the instance is invalid, the return value will be NfcProtocolInvalid. + * + * @param[in] instance pointer to the instance to be queried. + * @returns protocol identifier contained in the instance. + */ +NfcProtocol nfc_device_get_protocol(const NfcDevice* instance); -bool nfc_device_load(NfcDevice* dev, const char* file_path, bool show_dialog); +/** + * @brief Get the protocol-specific data from an NfcDevice instance. + * + * The protocol parameter's behaviour is a bit tricky. The function will check + * whether there is such a protocol somewhere in the protocol hierarchy and return + * the data exactly from that level. + * + * Example: Call nfc_device_get_data() on an instance with Mf DESFire protocol. + * The protocol hierarchy will look like the following: + * + * `Mf DESFire --> ISO14443-4A --> ISO14443-3A` + * + * Thus, the following values of the protocol parameter are valid: + * + * * NfcProtocolIso14443_3a + * * NfcProtocolIso14443_4a + * * NfcProtocolMfDesfire + * + * and passing them to the call would result in the respective data being returned. + * + * However, supplying a protocol identifier which is not in the hierarchy will + * result in a crash. This is to improve type safety. + * + * @param instance pointer to the instance to be queried + * @param protocol protocol identifier of the data to be retrieved. + * @returns pointer to the instance's data. + */ +const NfcDeviceData* nfc_device_get_data(const NfcDevice* instance, NfcProtocol protocol); -bool nfc_device_load_key_cache(NfcDevice* dev); +/** + * @brief Get the protocol name by its identifier. + * + * This function does not require an instance as its return result depends only + * the protocol identifier. + * + * @param[in] protocol numeric identifier of the protocol in question. + * @returns pointer to a statically allocated string containing the protocol name. + */ +const char* nfc_device_get_protocol_name(NfcProtocol protocol); -bool nfc_file_select(NfcDevice* dev); +/** + * @brief Get the name of an NfcDevice instance. + * + * The return value may change depending on the instance's internal state and the name_type parameter. + * + * @param[in] instance pointer to the instance to be queried. + * @param[in] name_type type of the name to be displayed. + * @returns pointer to a statically allocated string containing the device name. + */ +const char* nfc_device_get_name(const NfcDevice* instance, NfcDeviceNameType name_type); -void nfc_device_data_clear(NfcDeviceData* dev); +/** + * @brief Get the unique identifier (UID) of an NfcDevice instance. + * + * The UID length is protocol-dependent. Additionally, a particular protocol might support + * several UID lengths. + * + * @param[in] instance pointer to the instance to be queried. + * @param[out] uid_len pointer to the variable to contain the UID length. + * @returns pointer to the byte array containing the instance's UID. + */ +const uint8_t* nfc_device_get_uid(const NfcDevice* instance, size_t* uid_len); -void nfc_device_clear(NfcDevice* dev); +/** + * @brief Set the unique identifier (UID) of an NfcDevice instance. + * + * The UID length must be supported by the instance's protocol. + * + * @param[in,out] instance pointer to the instance to be modified. + * @param[in] uid pointer to the byte array containing the new UID. + * @param[in] uid_len length of the UID. + * @return true if the UID was valid and set, false otherwise. + */ +bool nfc_device_set_uid(NfcDevice* instance, const uint8_t* uid, size_t uid_len); -bool nfc_device_delete(NfcDevice* dev, bool use_load_path); +/** + * @brief Set the data and protocol of an NfcDevice instance. + * + * Any data previously contained in the instance will be deleted. + * + * @param[in,out] instance pointer to the instance to be modified. + * @param[in] protocol numeric identifier of the data's protocol. + * @param[in] protocol_data pointer to the protocol-specific data. + */ +void nfc_device_set_data( + NfcDevice* instance, + NfcProtocol protocol, + const NfcDeviceData* protocol_data); -bool nfc_device_restore(NfcDevice* dev, bool use_load_path); +/** + * @brief Copy (export) the data contained in an NfcDevice instance to an outside NfcDeviceData instance. + * + * This function does the inverse of nfc_device_set_data(). -void nfc_device_set_loading_callback(NfcDevice* dev, NfcLoadingCallback callback, void* context); + * The protocol identifier passed as the protocol parameter MUST match the one + * stored in the instance, otherwise a crash will occur. + * This is to improve type safety. + * + * @param[in] instance pointer to the instance to be copied from. + * @param[in] protocol numeric identifier of the instance's protocol. + * @param[out] protocol_data pointer to the destination data. + */ +void nfc_device_copy_data( + const NfcDevice* instance, + NfcProtocol protocol, + NfcDeviceData* protocol_data); + +/** + * @brief Check whether an NfcDevice instance holds certain data. + * + * This function's behaviour is similar to nfc_device_is_equal(), with the difference + * that it takes NfcProtocol and NfcDeviceData* instead of the second NfcDevice*. + * + * The following code snippets [1] and [2] are equivalent: + * + * [1] + * ```c + * bool is_equal = nfc_device_is_equal(device1, device2); + * ``` + * [2] + * ```c + * NfcProtocol protocol = nfc_device_get_protocol(device2); + * const NfcDeviceData* data = nfc_device_get_data(device2, protocol); + * bool is_equal = nfc_device_is_equal_data(device1, protocol, data); + * ``` + * + * @param[in] instance pointer to the instance to be compared. + * @param[in] protocol protocol identifier of the data to be compared. + * @param[in] protocol_data pointer to the NFC device data to be compared. + * @returns true if the instance is of the right type and the data matches, false otherwise. + */ +bool nfc_device_is_equal_data( + const NfcDevice* instance, + NfcProtocol protocol, + const NfcDeviceData* protocol_data); + +/** + * @brief Compare two NfcDevice instances to determine whether they are equal. + * + * @param[in] instance pointer to the first instance to be compared. + * @param[in] other pointer to the second instance to be compared. + * @returns true if both instances are considered equal, false otherwise. + */ +bool nfc_device_is_equal(const NfcDevice* instance, const NfcDevice* other); + +/** + * @brief Set the loading callback function. + * + * @param[in,out] instance pointer to the instance to be modified. + * @param[in] callback pointer to a function to be called when the load operation completes. + * @param[in] context pointer to a user-specific context (will be passed to the callback). + */ +void nfc_device_set_loading_callback( + NfcDevice* instance, + NfcLoadingCallback callback, + void* context); + +/** + * @brief Save NFC device data form an NfcDevice instance to a file. + * + * @param[in] instance pointer to the instance to be saved. + * @param[in] path pointer to a character string with a full file path. + * @returns true if the data was successfully saved, false otherwise. + */ +bool nfc_device_save(NfcDevice* instance, const char* path); + +/** + * @brief Load NFC device data to an NfcDevice instance from a file. + * + * @param[in,out] instance pointer to the instance to be loaded into. + * @param[in] path pointer to a character string with a full file path. + * @returns true if the data was successfully loaded, false otherwise. + */ +bool nfc_device_load(NfcDevice* instance, const char* path); #ifdef __cplusplus } diff --git a/lib/nfc/nfc_device_i.c b/lib/nfc/nfc_device_i.c new file mode 100644 index 000000000..e98b04251 --- /dev/null +++ b/lib/nfc/nfc_device_i.c @@ -0,0 +1,37 @@ +#include "nfc_device_i.h" +#include "protocols/nfc_device_defs.h" + +#include + +static NfcDeviceData* + nfc_device_search_base_protocol_data(const NfcDevice* instance, NfcProtocol protocol) { + NfcProtocol protocol_tmp = instance->protocol; + NfcDeviceData* dev_data_tmp = instance->protocol_data; + + while(true) { + dev_data_tmp = nfc_devices[protocol_tmp]->get_base_data(dev_data_tmp); + protocol_tmp = nfc_protocol_get_parent(protocol_tmp); + if(protocol_tmp == protocol) { + break; + } + } + + return dev_data_tmp; +} + +NfcDeviceData* nfc_device_get_data_ptr(const NfcDevice* instance, NfcProtocol protocol) { + furi_assert(instance); + furi_assert(protocol < NfcProtocolNum); + + NfcDeviceData* dev_data = NULL; + + if(instance->protocol == protocol) { + dev_data = instance->protocol_data; + } else if(nfc_protocol_has_parent(instance->protocol, protocol)) { + dev_data = nfc_device_search_base_protocol_data(instance, protocol); + } else { + furi_crash("Incorrect protocol"); + } + + return dev_data; +} diff --git a/lib/nfc/nfc_device_i.h b/lib/nfc/nfc_device_i.h new file mode 100644 index 000000000..1a9017d03 --- /dev/null +++ b/lib/nfc/nfc_device_i.h @@ -0,0 +1,46 @@ +/** + * @file nfc_device_i.h + * @brief NfcDevice private types and definitions. + * + * This file is an implementation detail. It must not be included in + * any public API-related headers. + */ +#pragma once + +#include "nfc_device.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief NfcDevice structure definition. + */ +struct NfcDevice { + NfcProtocol protocol; /**< Numeric identifier of the data's protocol*/ + NfcDeviceData* protocol_data; /**< Pointer to the NFC device data. */ + + NfcLoadingCallback + loading_callback; /**< Pointer to the function to be called upon loading completion. */ + void* loading_callback_context; /**< Pointer to the context to be passed to the loading callback. */ +}; + +/** + * @brief Get the mutable (non-const) data from an NfcDevice instance. + * + * The behaviour is the same as with nfc_device_get_data(), but the + * return pointer is non-const, allowing for changing data it is pointing to. + * + * @see nfc_device.h + * + * Under the hood, nfc_device_get_data() calls this and then adds const-ness to the return value. + * + * @param instance pointer to the instance to be queried + * @param protocol protocol identifier of the data to be retrieved. + * @returns pointer to the instance's (mutable) data. + */ +NfcDeviceData* nfc_device_get_data_ptr(const NfcDevice* instance, NfcProtocol protocol); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/nfc_listener.c b/lib/nfc/nfc_listener.c new file mode 100644 index 000000000..57b00a875 --- /dev/null +++ b/lib/nfc/nfc_listener.c @@ -0,0 +1,144 @@ +#include "nfc_listener.h" + +#include +#include + +#include + +typedef struct NfcListenerListElement { + NfcProtocol protocol; + NfcGenericInstance* listener; + const NfcListenerBase* listener_api; + struct NfcListenerListElement* child; +} NfcListenerListElement; + +typedef struct { + NfcListenerListElement* head; + NfcListenerListElement* tail; +} NfcListenerList; + +struct NfcListener { + NfcProtocol protocol; + Nfc* nfc; + NfcListenerList list; + NfcDevice* nfc_dev; +}; + +static void nfc_listener_list_alloc(NfcListener* instance) { + instance->list.head = malloc(sizeof(NfcListenerListElement)); + instance->list.head->protocol = instance->protocol; + + instance->list.head->listener_api = nfc_listeners_api[instance->protocol]; + instance->list.head->child = NULL; + instance->list.tail = instance->list.head; + + // Build linked list + do { + NfcProtocol parent_protocol = nfc_protocol_get_parent(instance->list.head->protocol); + if(parent_protocol == NfcProtocolInvalid) break; + + NfcListenerListElement* parent = malloc(sizeof(NfcListenerListElement)); + parent->protocol = parent_protocol; + parent->listener_api = nfc_listeners_api[parent_protocol]; + parent->child = instance->list.head; + + instance->list.head = parent; + } while(true); + + // Allocate listener instances + NfcListenerListElement* iter = instance->list.head; + NfcDeviceData* data_tmp = nfc_device_get_data_ptr(instance->nfc_dev, iter->protocol); + iter->listener = iter->listener_api->alloc(instance->nfc, data_tmp); + + do { + if(iter->child == NULL) break; + data_tmp = nfc_device_get_data_ptr(instance->nfc_dev, iter->child->protocol); + iter->child->listener = iter->child->listener_api->alloc(iter->listener, data_tmp); + iter->listener_api->set_callback( + iter->listener, iter->child->listener_api->run, iter->child->listener); + + iter = iter->child; + } while(true); +} + +static void nfc_listener_list_free(NfcListener* instance) { + // Free listener instances + do { + instance->list.head->listener_api->free(instance->list.head->listener); + NfcListenerListElement* child = instance->list.head->child; + free(instance->list.head); + if(child == NULL) break; + instance->list.head = child; + } while(true); +} + +NfcListener* nfc_listener_alloc(Nfc* nfc, NfcProtocol protocol, const NfcDeviceData* data) { + furi_assert(nfc); + furi_assert(protocol < NfcProtocolNum); + furi_assert(data); + furi_assert(nfc_listeners_api[protocol]); + + NfcListener* instance = malloc(sizeof(NfcListener)); + instance->nfc = nfc; + instance->protocol = protocol; + instance->nfc_dev = nfc_device_alloc(); + nfc_device_set_data(instance->nfc_dev, protocol, data); + nfc_listener_list_alloc(instance); + + return instance; +} + +void nfc_listener_free(NfcListener* instance) { + furi_assert(instance); + + nfc_listener_list_free(instance); + nfc_device_free(instance->nfc_dev); + free(instance); +} + +NfcCommand nfc_listener_start_callback(NfcEvent event, void* context) { + furi_assert(context); + + NfcListener* instance = context; + furi_assert(instance->list.head); + + NfcCommand command = NfcCommandContinue; + NfcGenericEvent generic_event = { + .protocol = NfcProtocolInvalid, + .instance = instance->nfc, + .event_data = &event, + }; + + NfcListenerListElement* head_listener = instance->list.head; + command = head_listener->listener_api->run(generic_event, head_listener->listener); + + return command; +} + +void nfc_listener_start(NfcListener* instance, NfcGenericCallback callback, void* context) { + furi_assert(instance); + + NfcListenerListElement* tail_element = instance->list.tail; + tail_element->listener_api->set_callback(tail_element->listener, callback, context); + nfc_start(instance->nfc, nfc_listener_start_callback, instance); +} + +void nfc_listener_stop(NfcListener* instance) { + furi_assert(instance); + + nfc_stop(instance->nfc); +} + +NfcProtocol nfc_listener_get_protocol(const NfcListener* instance) { + furi_assert(instance); + + return instance->protocol; +} + +const NfcDeviceData* nfc_listener_get_data(const NfcListener* instance, NfcProtocol protocol) { + furi_assert(instance); + furi_assert(instance->protocol == protocol); + + NfcListenerListElement* tail_element = instance->list.tail; + return tail_element->listener_api->get_data(tail_element->listener); +} diff --git a/lib/nfc/nfc_listener.h b/lib/nfc/nfc_listener.h new file mode 100644 index 000000000..dbfeb23bf --- /dev/null +++ b/lib/nfc/nfc_listener.h @@ -0,0 +1,94 @@ +/** + * @file nfc_listener.h + * @brief NFC card emulation library. + * + * Once started, it will respond to supported commands from an NFC reader, thus imitating + * (or emulating) an NFC card. The responses will depend on the data that was supplied to + * the listener, so various card types and different cards of the same type can be emulated. + * + * It will also make any changes necessary to the emulated data in response to the + * reader commands if the protocol supports it. + * + * When running, NfcListener will generate events that the calling code must handle + * by providing a callback function. The events passed to the callback are protocol-specific + * and may include errors, state changes, data reception, special function requests and more. + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief NfcListener opaque type definition. + */ +typedef struct NfcListener NfcListener; + +/** + * @brief Allocate an NfcListener instance. + * + * @param[in] nfc pointer to an Nfc instance. + * @param[in] protocol identifier of the protocol to be used. + * @param[in] data pointer to the data to use during emulation. + * @returns pointer to an allocated instance. + * + * @see nfc.h + */ +NfcListener* nfc_listener_alloc(Nfc* nfc, NfcProtocol protocol, const NfcDeviceData* data); + +/** + * @brief Delete an NfcListener instance. + * + * @param[in,out] instance pointer to the instance to be deleted. + */ +void nfc_listener_free(NfcListener* instance); + +/** + * @brief Start an NfcListener instance. + * + * The callback logic is protocol-specific, so it cannot be described here in detail. + * However, the callback return value ALWAYS determines what the listener should do next: + * to continue whatever it was doing prior to the callback run or to stop. + * + * @param[in,out] instance pointer to the instance to be started. + * @param[in] callback pointer to a user-defined callback function which will receive events. + * @param[in] context pointer to a user-specific context (will be passed to the callback). + */ +void nfc_listener_start(NfcListener* instance, NfcGenericCallback callback, void* context); + +/** + * @brief Stop an NfcListener instance. + * + * The emulation process can be stopped explicitly (the other way is via the callback return value). + * + * @param[in,out] instance pointer to the instance to be stopped. + */ +void nfc_listener_stop(NfcListener* instance); + +/** + * @brief Get the protocol identifier an NfcListener instance was created with. + * + * @param[in] instance pointer to the instance to be queried. + * @returns identifier of the protocol used by the instance. + */ +NfcProtocol nfc_listener_get_protocol(const NfcListener* instance); + +/** + * @brief Get the data that was that was provided for emulation. + * + * The protocol identifier passed as the protocol parameter MUST match the one + * stored in the instance, otherwise a crash will occur. + * This is to improve type safety. + * + * @param[in] instance pointer to the instance to be queried. + * @param[in] protocol assumed protocol identifier of the data to be retrieved. + * @returns pointer to the NFC device data. + */ +const NfcDeviceData* nfc_listener_get_data(const NfcListener* instance, NfcProtocol protocol); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/nfc_poller.c b/lib/nfc/nfc_poller.c new file mode 100644 index 000000000..ffe0318a0 --- /dev/null +++ b/lib/nfc/nfc_poller.c @@ -0,0 +1,211 @@ +#include "nfc_poller.h" + +#include + +#include + +typedef enum { + NfcPollerSessionStateIdle, + NfcPollerSessionStateActive, + NfcPollerSessionStateStopRequest, +} NfcPollerSessionState; + +typedef struct NfcPollerListElement { + NfcProtocol protocol; + NfcGenericInstance* poller; + const NfcPollerBase* poller_api; + struct NfcPollerListElement* child; +} NfcPollerListElement; + +typedef struct { + NfcPollerListElement* head; + NfcPollerListElement* tail; +} NfcPollerList; + +struct NfcPoller { + NfcProtocol protocol; + Nfc* nfc; + NfcPollerList list; + NfcPollerSessionState session_state; + bool protocol_detected; +}; + +static void nfc_poller_list_alloc(NfcPoller* instance) { + instance->list.head = malloc(sizeof(NfcPollerListElement)); + instance->list.head->protocol = instance->protocol; + instance->list.head->poller_api = nfc_pollers_api[instance->protocol]; + instance->list.head->child = NULL; + instance->list.tail = instance->list.head; + + do { + NfcProtocol parent_protocol = nfc_protocol_get_parent(instance->list.head->protocol); + if(parent_protocol == NfcProtocolInvalid) break; + + NfcPollerListElement* parent = malloc(sizeof(NfcPollerListElement)); + parent->protocol = parent_protocol; + parent->poller_api = nfc_pollers_api[parent_protocol]; + parent->child = instance->list.head; + instance->list.head = parent; + } while(true); + + NfcPollerListElement* iter = instance->list.head; + iter->poller = iter->poller_api->alloc(instance->nfc); + + do { + if(iter->child == NULL) break; + iter->child->poller = iter->child->poller_api->alloc(iter->poller); + iter->poller_api->set_callback( + iter->poller, iter->child->poller_api->run, iter->child->poller); + + iter = iter->child; + } while(true); +} + +static void nfc_poller_list_free(NfcPoller* instance) { + do { + instance->list.head->poller_api->free(instance->list.head->poller); + NfcPollerListElement* child = instance->list.head->child; + free(instance->list.head); + if(child == NULL) break; + instance->list.head = child; + } while(true); +} + +NfcPoller* nfc_poller_alloc(Nfc* nfc, NfcProtocol protocol) { + furi_assert(nfc); + furi_assert(protocol < NfcProtocolNum); + + NfcPoller* instance = malloc(sizeof(NfcPoller)); + instance->session_state = NfcPollerSessionStateIdle; + instance->nfc = nfc; + instance->protocol = protocol; + nfc_poller_list_alloc(instance); + + return instance; +} + +void nfc_poller_free(NfcPoller* instance) { + furi_assert(instance); + + nfc_poller_list_free(instance); + free(instance); +} + +static NfcCommand nfc_poller_start_callback(NfcEvent event, void* context) { + furi_assert(context); + + NfcPoller* instance = context; + + NfcCommand command = NfcCommandContinue; + NfcGenericEvent poller_event = { + .protocol = NfcProtocolInvalid, + .instance = instance->nfc, + .event_data = &event, + }; + + if(event.type == NfcEventTypePollerReady) { + NfcPollerListElement* head_poller = instance->list.head; + command = head_poller->poller_api->run(poller_event, head_poller->poller); + } + + if(instance->session_state == NfcPollerSessionStateStopRequest) { + command = NfcCommandStop; + } + + return command; +} + +void nfc_poller_start(NfcPoller* instance, NfcGenericCallback callback, void* context) { + furi_assert(instance); + furi_assert(callback); + furi_assert(instance->session_state == NfcPollerSessionStateIdle); + + NfcPollerListElement* tail_poller = instance->list.tail; + tail_poller->poller_api->set_callback(tail_poller->poller, callback, context); + + instance->session_state = NfcPollerSessionStateActive; + nfc_start(instance->nfc, nfc_poller_start_callback, instance); +} + +void nfc_poller_stop(NfcPoller* instance) { + furi_assert(instance); + furi_assert(instance->nfc); + + instance->session_state = NfcPollerSessionStateStopRequest; + nfc_stop(instance->nfc); + instance->session_state = NfcPollerSessionStateIdle; +} + +static NfcCommand nfc_poller_detect_tail_callback(NfcGenericEvent event, void* context) { + furi_assert(context); + + NfcPoller* instance = context; + NfcPollerListElement* tail_poller = instance->list.tail; + instance->protocol_detected = tail_poller->poller_api->detect(event, tail_poller->poller); + + return NfcCommandStop; +} + +static NfcCommand nfc_poller_detect_head_callback(NfcEvent event, void* context) { + furi_assert(context); + + NfcPoller* instance = context; + NfcPollerListElement* tail_poller = instance->list.tail; + NfcPollerListElement* head_poller = instance->list.head; + + NfcCommand command = NfcCommandContinue; + NfcGenericEvent poller_event = { + .protocol = NfcProtocolInvalid, + .instance = instance->nfc, + .event_data = &event, + }; + + if(event.type == NfcEventTypePollerReady) { + if(tail_poller == head_poller) { + instance->protocol_detected = + tail_poller->poller_api->detect(poller_event, tail_poller->poller); + command = NfcCommandStop; + } else { + command = head_poller->poller_api->run(poller_event, head_poller->poller); + } + } + + return command; +} + +bool nfc_poller_detect(NfcPoller* instance) { + furi_assert(instance); + furi_assert(instance->session_state == NfcPollerSessionStateIdle); + + instance->session_state = NfcPollerSessionStateActive; + NfcPollerListElement* tail_poller = instance->list.tail; + NfcPollerListElement* iter = instance->list.head; + + if(tail_poller != instance->list.head) { + while(iter->child != tail_poller) iter = iter->child; + iter->poller_api->set_callback(iter->poller, nfc_poller_detect_tail_callback, instance); + } + + nfc_start(instance->nfc, nfc_poller_detect_head_callback, instance); + nfc_stop(instance->nfc); + + if(tail_poller != instance->list.head) { + iter->poller_api->set_callback( + iter->poller, tail_poller->poller_api->run, tail_poller->poller); + } + + return instance->protocol_detected; +} + +NfcProtocol nfc_poller_get_protocol(const NfcPoller* instance) { + furi_assert(instance); + + return instance->protocol; +} + +const NfcDeviceData* nfc_poller_get_data(const NfcPoller* instance) { + furi_assert(instance); + + NfcPollerListElement* tail_poller = instance->list.tail; + return tail_poller->poller_api->get_data(tail_poller->poller); +} diff --git a/lib/nfc/nfc_poller.h b/lib/nfc/nfc_poller.h new file mode 100644 index 000000000..8ae01a8e4 --- /dev/null +++ b/lib/nfc/nfc_poller.h @@ -0,0 +1,104 @@ +/** + * @file nfc_poller.h + * @brief NFC card reading library. + * + * Once started, it will try to activate and read a card using the designated protocol, + * which is usually obtained by creating and starting an NfcScanner first. + * + * @see nfc_scanner.h + * + * When running, NfcPoller will generate events that the calling code must handle + * by providing a callback function. The events passed to the callback are protocol-specific + * and may include errors, state changes, data reception, special function requests and more. + * + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief NfcPoller opaque type definition. + */ +typedef struct NfcPoller NfcPoller; + +/** + * @brief Allocate an NfcPoller instance. + * + * @param[in] nfc pointer to an Nfc instance. + * @param[in] protocol identifier of the protocol to be used. + * @returns pointer to an allocated instance. + * + * @see nfc.h + */ +NfcPoller* nfc_poller_alloc(Nfc* nfc, NfcProtocol protocol); + +/** + * @brief Delete an NfcPoller instance. + * + * @param[in,out] instance pointer to the instance to be deleted. + */ +void nfc_poller_free(NfcPoller* instance); + +/** + * @brief Start an NfcPoller instance. + * + * The callback logic is protocol-specific, so it cannot be described here in detail. + * However, the callback return value ALWAYS determines what the poller should do next: + * to continue whatever it was doing prior to the callback run or to stop. + * + * @param[in,out] instance pointer to the instance to be started. + * @param[in] callback pointer to a user-defined callback function which will receive events. + * @param[in] context pointer to a user-specific context (will be passed to the callback). + */ +void nfc_poller_start(NfcPoller* instance, NfcGenericCallback callback, void* context); + +/** + * @brief Stop an NfcPoller instance. + * + * The reading process can be stopped explicitly (the other way is via the callback return value). + * + * @param[in,out] instance pointer to the instance to be stopped. + */ +void nfc_poller_stop(NfcPoller* instance); + +/** + * @brief Detect whether there is a card supporting a particular protocol in the vicinity. + * + * The behaviour of this function is protocol-defined, in general, it will do whatever is + * necessary to determine whether a card supporting the current protocol is in the vicinity + * and whether it is functioning normally. + * + * It is used automatically inside NfcScanner, so there is usually no need + * to call it explicitly. + * + * @see nfc_scanner.h + * + * @param[in,out] instance pointer to the instance to perform the detection with. + * @returns true if a supported card was detected, false otherwise. + */ +bool nfc_poller_detect(NfcPoller* instance); + +/** + * @brief Get the protocol identifier an NfcPoller instance was created with. + * + * @param[in] instance pointer to the instance to be queried. + * @returns identifier of the protocol used by the instance. + */ +NfcProtocol nfc_poller_get_protocol(const NfcPoller* instance); + +/** + * @brief Get the data that was that was gathered during the reading process. + * + * @param[in] instance pointer to the instance to be queried. + * @returns pointer to the NFC device data. + */ +const NfcDeviceData* nfc_poller_get_data(const NfcPoller* instance); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/nfc_scanner.c b/lib/nfc/nfc_scanner.c new file mode 100644 index 000000000..0056dfb1c --- /dev/null +++ b/lib/nfc/nfc_scanner.c @@ -0,0 +1,267 @@ +#include "nfc_scanner.h" +#include "nfc_poller.h" + +#include + +#include + +#define TAG "NfcScanner" + +typedef enum { + NfcScannerStateIdle, + NfcScannerStateTryBasePollers, + NfcScannerStateFindChildrenProtocols, + NfcScannerStateDetectChildrenProtocols, + NfcScannerStateComplete, + + NfcScannerStateNum, +} NfcScannerState; + +typedef enum { + NfcScannerSessionStateIdle, + NfcScannerSessionStateActive, + NfcScannerSessionStateStopRequest, +} NfcScannerSessionState; + +struct NfcScanner { + Nfc* nfc; + NfcScannerState state; + NfcScannerSessionState session_state; + + NfcScannerCallback callback; + void* context; + + NfcEvent nfc_event; + + NfcProtocol first_detected_protocol; + + size_t base_protocols_num; + size_t base_protocols_idx; + NfcProtocol base_protocols[NfcProtocolNum]; + + size_t detected_base_protocols_num; + NfcProtocol detected_base_protocols[NfcProtocolNum]; + + size_t children_protocols_num; + size_t children_protocols_idx; + NfcProtocol children_protocols[NfcProtocolNum]; + + size_t detected_protocols_num; + NfcProtocol detected_protocols[NfcProtocolNum]; + + NfcProtocol current_protocol; + + FuriThread* scan_worker; +}; + +static void nfc_scanner_reset(NfcScanner* instance) { + instance->base_protocols_idx = 0; + instance->base_protocols_num = 0; + + instance->children_protocols_idx = 0; + instance->children_protocols_num = 0; + + instance->detected_protocols_num = 0; + instance->detected_base_protocols_num = 0; + + instance->current_protocol = 0; +} + +typedef void (*NfcScannerStateHandler)(NfcScanner* instance); + +void nfc_scanner_state_handler_idle(NfcScanner* instance) { + for(size_t i = 0; i < NfcProtocolNum; i++) { + NfcProtocol parent_protocol = nfc_protocol_get_parent(i); + if(parent_protocol == NfcProtocolInvalid) { + instance->base_protocols[instance->base_protocols_num] = i; + instance->base_protocols_num++; + } + } + FURI_LOG_D(TAG, "Found %zu base protocols", instance->base_protocols_num); + + instance->first_detected_protocol = NfcProtocolInvalid; + instance->state = NfcScannerStateTryBasePollers; +} + +void nfc_scanner_state_handler_try_base_pollers(NfcScanner* instance) { + do { + instance->current_protocol = instance->base_protocols[instance->base_protocols_idx]; + + if(instance->first_detected_protocol == instance->current_protocol) { + instance->state = NfcScannerStateFindChildrenProtocols; + break; + } + + NfcPoller* poller = nfc_poller_alloc(instance->nfc, instance->current_protocol); + bool protocol_detected = nfc_poller_detect(poller); + nfc_poller_free(poller); + + if(protocol_detected) { + instance->detected_protocols[instance->detected_protocols_num] = + instance->current_protocol; + instance->detected_protocols_num++; + + instance->detected_base_protocols[instance->detected_base_protocols_num] = + instance->current_protocol; + instance->detected_base_protocols_num++; + + if(instance->first_detected_protocol == NfcProtocolInvalid) { + instance->first_detected_protocol = instance->current_protocol; + instance->current_protocol = NfcProtocolInvalid; + } + } + + instance->base_protocols_idx = + (instance->base_protocols_idx + 1) % instance->base_protocols_num; + } while(false); +} + +void nfc_scanner_state_handler_find_children_protocols(NfcScanner* instance) { + for(size_t i = 0; i < NfcProtocolNum; i++) { + for(size_t j = 0; j < instance->detected_base_protocols_num; j++) { + if(nfc_protocol_has_parent(i, instance->detected_base_protocols[j])) { + instance->children_protocols[instance->children_protocols_num] = i; + instance->children_protocols_num++; + } + } + } + + if(instance->children_protocols_num > 0) { + instance->state = NfcScannerStateDetectChildrenProtocols; + } else { + instance->state = NfcScannerStateComplete; + } + FURI_LOG_D(TAG, "Found %zu children", instance->children_protocols_num); +} + +void nfc_scanner_state_handler_detect_children_protocols(NfcScanner* instance) { + furi_assert(instance->children_protocols_num); + + instance->current_protocol = instance->children_protocols[instance->children_protocols_idx]; + + NfcPoller* poller = nfc_poller_alloc(instance->nfc, instance->current_protocol); + bool protocol_detected = nfc_poller_detect(poller); + nfc_poller_free(poller); + + if(protocol_detected) { + instance->detected_protocols[instance->detected_protocols_num] = + instance->current_protocol; + instance->detected_protocols_num++; + } + + instance->children_protocols_idx++; + if(instance->children_protocols_idx == instance->children_protocols_num) { + instance->state = NfcScannerStateComplete; + } +} + +static void nfc_scanner_filter_detected_protocols(NfcScanner* instance) { + size_t filtered_protocols_num = 0; + NfcProtocol filtered_protocols[NfcProtocolNum] = {}; + + for(size_t i = 0; i < instance->detected_protocols_num; i++) { + bool is_parent = false; + for(size_t j = i; j < instance->detected_protocols_num; j++) { + is_parent = nfc_protocol_has_parent( + instance->detected_protocols[j], instance->detected_protocols[i]); + if(is_parent) break; + } + if(!is_parent) { + filtered_protocols[filtered_protocols_num] = instance->detected_protocols[i]; + filtered_protocols_num++; + } + } + + instance->detected_protocols_num = filtered_protocols_num; + memcpy(instance->detected_protocols, filtered_protocols, filtered_protocols_num); +} + +void nfc_scanner_state_handler_complete(NfcScanner* instance) { + if(instance->detected_protocols_num > 1) { + nfc_scanner_filter_detected_protocols(instance); + } + FURI_LOG_I(TAG, "Detected %zu protocols", instance->detected_protocols_num); + + NfcScannerEvent event = { + .type = NfcScannerEventTypeDetected, + .data = + { + .protocol_num = instance->detected_protocols_num, + .protocols = instance->detected_protocols, + }, + }; + + instance->callback(event, instance->context); + furi_delay_ms(100); +} + +static NfcScannerStateHandler nfc_scanner_state_handlers[NfcScannerStateNum] = { + [NfcScannerStateIdle] = nfc_scanner_state_handler_idle, + [NfcScannerStateTryBasePollers] = nfc_scanner_state_handler_try_base_pollers, + [NfcScannerStateFindChildrenProtocols] = nfc_scanner_state_handler_find_children_protocols, + [NfcScannerStateDetectChildrenProtocols] = nfc_scanner_state_handler_detect_children_protocols, + [NfcScannerStateComplete] = nfc_scanner_state_handler_complete, +}; + +static int32_t nfc_scanner_worker(void* context) { + furi_assert(context); + + NfcScanner* instance = context; + + while(instance->session_state == NfcScannerSessionStateActive) { + nfc_scanner_state_handlers[instance->state](instance); + } + + nfc_scanner_reset(instance); + + return 0; +} + +NfcScanner* nfc_scanner_alloc(Nfc* nfc) { + furi_assert(nfc); + + NfcScanner* instance = malloc(sizeof(NfcScanner)); + instance->nfc = nfc; + + return instance; +} + +void nfc_scanner_free(NfcScanner* instance) { + furi_assert(instance); + + free(instance); +} + +void nfc_scanner_start(NfcScanner* instance, NfcScannerCallback callback, void* context) { + furi_assert(instance); + furi_assert(callback); + furi_assert(instance->session_state == NfcScannerSessionStateIdle); + furi_assert(instance->scan_worker == NULL); + + instance->callback = callback; + instance->context = context; + instance->session_state = NfcScannerSessionStateActive; + + instance->scan_worker = furi_thread_alloc(); + furi_thread_set_name(instance->scan_worker, "NfcScanWorker"); + furi_thread_set_context(instance->scan_worker, instance); + furi_thread_set_stack_size(instance->scan_worker, 4 * 1024); + furi_thread_set_callback(instance->scan_worker, nfc_scanner_worker); + + furi_thread_start(instance->scan_worker); +} + +void nfc_scanner_stop(NfcScanner* instance) { + furi_assert(instance); + furi_assert(instance->scan_worker); + + instance->session_state = NfcScannerSessionStateStopRequest; + furi_thread_join(instance->scan_worker); + instance->session_state = NfcScannerSessionStateIdle; + + furi_thread_free(instance->scan_worker); + instance->scan_worker = NULL; + instance->callback = NULL; + instance->context = NULL; + instance->state = NfcScannerStateIdle; +} diff --git a/lib/nfc/nfc_scanner.h b/lib/nfc/nfc_scanner.h new file mode 100644 index 000000000..a1b4aabcd --- /dev/null +++ b/lib/nfc/nfc_scanner.h @@ -0,0 +1,97 @@ +/** + * @file nfc_scanner.h + * @brief NFC card detection library. + * + * Once started, a NfcScanner instance will iterate over all available protocols + * and return a list of one or more detected protocol identifiers via a user-provided callback. + * + * The NfcScanner behaviour is greedy, i.e. it will not stop scanning upon detection of + * a just one protocol and will try others as well until all possibilities are exhausted. + * This is to allow for multi-protocol card support. + * + * If no supported cards are in the vicinity, the scanning process will continue + * until stopped explicitly. + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief NfcScanner opaque type definition. + */ +typedef struct NfcScanner NfcScanner; + +/** + * @brief Event type passed to the user callback. + */ +typedef enum { + NfcScannerEventTypeDetected, /**< One or more protocols have been detected. */ +} NfcScannerEventType; + +/** + * @brief Event data passed to the user callback. + */ +typedef struct { + size_t protocol_num; /**< Number of detected protocols (one or more). */ + NfcProtocol* protocols; /**< Pointer to the array of detected protocol identifiers. */ +} NfcScannerEventData; + +/** + * @brief Event passed to the user callback. + */ +typedef struct { + NfcScannerEventType type; /**< Type of event. Determines how the data must be handled. */ + NfcScannerEventData data; /**< Event-specific data. Handled accordingly to the even type. */ +} NfcScannerEvent; + +/** + * @brief User callback function signature. + * + * A function with such signature must be provided by the user upon calling nfc_scanner_start(). + * + * @param[in] event occurred event, complete with type and data. + * @param[in] context pointer to the context data provided in nfc_scanner_start() call. + */ +typedef void (*NfcScannerCallback)(NfcScannerEvent event, void* context); + +/** + * @brief Allocate an NfcScanner instance. + * + * @param[in] nfc pointer to an Nfc instance. + * @returns pointer to the allocated NfcScanner instance. + * + * @see nfc.h + */ +NfcScanner* nfc_scanner_alloc(Nfc* nfc); + +/** + * @brief Delete an NfcScanner instance. + * + * @param[in,out] pointer to the instance to be deleted. + */ +void nfc_scanner_free(NfcScanner* instance); + +/** + * @brief Start an NfcScanner. + * + * @param[in,out] pointer to the instance to be started. + * @param[in] callback pointer to the callback function (will be called upon a detection event). + * @param[in] context pointer to the caller-specific context (will be passed to the callback). + */ +void nfc_scanner_start(NfcScanner* instance, NfcScannerCallback callback, void* context); + +/** + * @brief Stop an NfcScanner. + * + * @param[in,out] pointer to the instance to be stopped. + */ +void nfc_scanner_stop(NfcScanner* instance); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/nfc_types.c b/lib/nfc/nfc_types.c deleted file mode 100644 index 96b92640f..000000000 --- a/lib/nfc/nfc_types.c +++ /dev/null @@ -1,69 +0,0 @@ -#include "nfc_types.h" - -const char* nfc_get_dev_type(FuriHalNfcType type) { - if(type == FuriHalNfcTypeA) { - return "NFC-A"; - } else if(type == FuriHalNfcTypeB) { - return "NFC-B"; - } else if(type == FuriHalNfcTypeF) { - return "NFC-F"; - } else if(type == FuriHalNfcTypeV) { - return "NFC-V"; - } else { - return "Unknown"; - } -} - -const char* nfc_guess_protocol(NfcProtocol protocol) { - if(protocol == NfcDeviceProtocolEMV) { - return "EMV bank card"; - } else if(protocol == NfcDeviceProtocolMifareUl) { - return "Mifare Ultral/NTAG"; - } else if(protocol == NfcDeviceProtocolMifareClassic) { - return "Mifare Classic"; - } else if(protocol == NfcDeviceProtocolMifareDesfire) { - return "Mifare DESFire"; - } else { - return "Unrecognized"; - } -} - -const char* nfc_mf_ul_type(MfUltralightType type, bool full_name) { - if(type == MfUltralightTypeNTAG213) { - return "NTAG213"; - } else if(type == MfUltralightTypeNTAG215) { - return "NTAG215"; - } else if(type == MfUltralightTypeNTAG216) { - return "NTAG216"; - } else if(type == MfUltralightTypeNTAGI2C1K) { - return "NTAG I2C 1K"; - } else if(type == MfUltralightTypeNTAGI2C2K) { - return "NTAG I2C 2K"; - } else if(type == MfUltralightTypeNTAGI2CPlus1K) { - return "NTAG I2C Plus 1K"; - } else if(type == MfUltralightTypeNTAGI2CPlus2K) { - return "NTAG I2C Plus 2K"; - } else if(type == MfUltralightTypeNTAG203) { - return "NTAG203"; - } else if(type == MfUltralightTypeULC) { - return "Mifare Ultralight C"; - } else if(type == MfUltralightTypeUL11 && full_name) { - return "Mifare Ultralight 11"; - } else if(type == MfUltralightTypeUL21 && full_name) { - return "Mifare Ultralight 21"; - } else { - return "Mifare Ultralight"; - } -} - -const char* nfc_mf_classic_type(MfClassicType type) { - if(type == MfClassicTypeMini) { - return "Mifare Mini 0.3K"; - } else if(type == MfClassicType1k) { - return "Mifare Classic 1K"; - } else if(type == MfClassicType4k) { - return "Mifare Classic 4K"; - } else { - return "Mifare Classic"; - } -} diff --git a/lib/nfc/nfc_types.h b/lib/nfc/nfc_types.h deleted file mode 100644 index 5ebb2d27b..000000000 --- a/lib/nfc/nfc_types.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include "nfc_device.h" - -#ifdef __cplusplus -extern "C" { -#endif - -const char* nfc_get_dev_type(FuriHalNfcType type); - -const char* nfc_guess_protocol(NfcProtocol protocol); - -const char* nfc_mf_ul_type(MfUltralightType type, bool full_name); - -const char* nfc_mf_classic_type(MfClassicType type); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/lib/nfc/nfc_worker.c b/lib/nfc/nfc_worker.c deleted file mode 100644 index 77c95de34..000000000 --- a/lib/nfc/nfc_worker.c +++ /dev/null @@ -1,1405 +0,0 @@ -#include "nfc_worker_i.h" -#include - -#include -#include "parsers/nfc_supported_card.h" - -#define TAG "NfcWorker" - -/***************************** NFC Worker API *******************************/ - -NfcWorker* nfc_worker_alloc() { - NfcWorker* nfc_worker = malloc(sizeof(NfcWorker)); - - // Worker thread attributes - nfc_worker->thread = furi_thread_alloc_ex("NfcWorker", 8192, nfc_worker_task, nfc_worker); - - nfc_worker->callback = NULL; - nfc_worker->context = NULL; - nfc_worker->storage = furi_record_open(RECORD_STORAGE); - - // Initialize rfal - while(furi_hal_nfc_is_busy()) { - furi_delay_ms(10); - } - nfc_worker_change_state(nfc_worker, NfcWorkerStateReady); - - nfc_worker->reader_analyzer = reader_analyzer_alloc(nfc_worker->storage); - - return nfc_worker; -} - -void nfc_worker_free(NfcWorker* nfc_worker) { - furi_assert(nfc_worker); - - furi_thread_free(nfc_worker->thread); - - furi_record_close(RECORD_STORAGE); - - reader_analyzer_free(nfc_worker->reader_analyzer); - - free(nfc_worker); -} - -NfcWorkerState nfc_worker_get_state(NfcWorker* nfc_worker) { - return nfc_worker->state; -} - -void nfc_worker_start( - NfcWorker* nfc_worker, - NfcWorkerState state, - NfcDeviceData* dev_data, - NfcWorkerCallback callback, - void* context) { - furi_assert(nfc_worker); - furi_assert(dev_data); - while(furi_hal_nfc_is_busy()) { - furi_delay_ms(10); - } - furi_hal_nfc_deinit(); - furi_hal_nfc_init(); - - nfc_worker->callback = callback; - nfc_worker->context = context; - nfc_worker->dev_data = dev_data; - nfc_worker_change_state(nfc_worker, state); - furi_thread_start(nfc_worker->thread); -} - -void nfc_worker_stop(NfcWorker* nfc_worker) { - furi_assert(nfc_worker); - furi_assert(nfc_worker->thread); - if(furi_thread_get_state(nfc_worker->thread) != FuriThreadStateStopped) { - furi_hal_nfc_stop(); - nfc_worker_change_state(nfc_worker, NfcWorkerStateStop); - furi_thread_join(nfc_worker->thread); - } -} - -void nfc_worker_change_state(NfcWorker* nfc_worker, NfcWorkerState state) { - nfc_worker->state = state; -} - -/***************************** NFC Worker Thread *******************************/ - -int32_t nfc_worker_task(void* context) { - NfcWorker* nfc_worker = context; - - furi_hal_nfc_exit_sleep(); - - if(nfc_worker->state == NfcWorkerStateRead) { - if(nfc_worker->dev_data->read_mode == NfcReadModeAuto) { - nfc_worker_read(nfc_worker); - } else { - nfc_worker_read_type(nfc_worker); - } - } else if(nfc_worker->state == NfcWorkerStateUidEmulate) { - nfc_worker_emulate_uid(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateEmulateApdu) { - nfc_worker_emulate_apdu(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateMfUltralightEmulate) { - nfc_worker_emulate_mf_ultralight(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateMfClassicEmulate) { - nfc_worker_emulate_mf_classic(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateMfClassicWrite) { - nfc_worker_write_mf_classic(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateMfClassicUpdate) { - nfc_worker_update_mf_classic(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateReadMfUltralightReadAuth) { - nfc_worker_mf_ultralight_read_auth(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateMfClassicDictAttack) { - nfc_worker_mf_classic_dict_attack(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateAnalyzeReader) { - nfc_worker_analyze_reader(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateNfcVEmulate) { - nfc_worker_nfcv_emulate(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateNfcVSniff) { - nfc_worker_nfcv_sniff(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateNfcVUnlock) { - nfc_worker_nfcv_unlock(nfc_worker); - } else if(nfc_worker->state == NfcWorkerStateNfcVUnlockAndSave) { - nfc_worker_nfcv_unlock(nfc_worker); - } - furi_hal_nfc_sleep(); - nfc_worker_change_state(nfc_worker, NfcWorkerStateReady); - - return 0; -} - -static bool nfc_worker_read_nfcv(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - bool read_success = false; - NfcVReader reader = {}; - - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - NfcVData* nfcv_data = &nfc_worker->dev_data->nfcv_data; - - furi_hal_nfc_sleep(); - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, tx_rx, false); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - do { - if(!furi_hal_nfc_detect(&nfc_worker->dev_data->nfc_data, 200)) break; - if(!nfcv_read_card(&reader, nfc_data, nfcv_data)) break; - - read_success = true; - } while(false); - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } - - return read_success; -} - -void nfc_worker_nfcv_emulate(NfcWorker* nfc_worker) { - FuriHalNfcTxRxContext tx_rx = {}; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - NfcVData* nfcv_data = &nfc_worker->dev_data->nfcv_data; - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, &tx_rx, true); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - nfcv_emu_init(nfc_data, nfcv_data); - while(nfc_worker->state == NfcWorkerStateNfcVEmulate) { - if(nfcv_emu_loop(&tx_rx, nfc_data, nfcv_data, 100)) { - if(nfc_worker->callback) { - nfc_worker->callback(NfcWorkerEventNfcVCommandExecuted, nfc_worker->context); - if(nfcv_data->modified) { - nfc_worker->callback(NfcWorkerEventNfcVContentChanged, nfc_worker->context); - nfcv_data->modified = false; - } - } - } - } - nfcv_emu_deinit(nfcv_data); - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } -} - -void nfc_worker_nfcv_sniff(NfcWorker* nfc_worker) { - FuriHalNfcTxRxContext tx_rx = {}; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - NfcVData* nfcv_data = &nfc_worker->dev_data->nfcv_data; - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, &tx_rx, true); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - nfcv_data->sub_type = NfcVTypeSniff; - nfcv_emu_init(nfc_data, nfcv_data); - - while(nfc_worker->state == NfcWorkerStateNfcVSniff) { - if(nfcv_emu_loop(&tx_rx, nfc_data, nfcv_data, 100)) { - if(nfc_worker->callback) { - nfc_worker->callback(NfcWorkerEventNfcVCommandExecuted, nfc_worker->context); - } - } - } - nfcv_emu_deinit(nfcv_data); - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } -} - -void nfc_worker_nfcv_unlock(NfcWorker* nfc_worker) { - furi_assert(nfc_worker); - furi_assert(nfc_worker->callback); - - NfcVData* nfcv_data = &nfc_worker->dev_data->nfcv_data; - FuriHalNfcTxRxContext tx_rx = {}; - uint8_t* key_data = nfcv_data->sub_data.slix.key_privacy; - uint32_t key = 0; - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, &tx_rx, true); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - furi_hal_nfc_sleep(); - - while((nfc_worker->state == NfcWorkerStateNfcVUnlock) || - (nfc_worker->state == NfcWorkerStateNfcVUnlockAndSave)) { - furi_hal_nfc_exit_sleep(); - furi_hal_nfc_ll_txrx_on(); - furi_hal_nfc_ll_poll(); - if(furi_hal_nfc_ll_set_mode( - FuriHalNfcModePollNfcv, FuriHalNfcBitrate26p48, FuriHalNfcBitrate26p48) != - FuriHalNfcReturnOk) { - break; - } - - furi_hal_nfc_ll_set_fdt_listen(FURI_HAL_NFC_LL_FDT_LISTEN_NFCV_POLLER); - furi_hal_nfc_ll_set_fdt_poll(FURI_HAL_NFC_LL_FDT_POLL_NFCV_POLLER); - furi_hal_nfc_ll_set_error_handling(FuriHalNfcErrorHandlingNfc); - furi_hal_nfc_ll_set_guard_time(FURI_HAL_NFC_LL_GT_NFCV); - - FURI_LOG_D(TAG, "Detect presence"); - ReturnCode ret = slix_get_random(nfcv_data); - - if(ret == ERR_NONE) { - /* there is some chip, responding with a RAND */ - nfc_worker->dev_data->protocol = NfcDeviceProtocolNfcV; - FURI_LOG_D(TAG, " Chip detected. In privacy?"); - ret = nfcv_inventory(NULL); - - if(ret == ERR_NONE) { - /* chip is also visible, so no action required, just save */ - if(nfc_worker->state == NfcWorkerStateNfcVUnlockAndSave) { - NfcVReader reader = {}; - - if(!nfcv_read_card(&reader, &nfc_worker->dev_data->nfc_data, nfcv_data)) { - FURI_LOG_D(TAG, " => failed, wait for chip to disappear."); - snprintf(nfcv_data->error, sizeof(nfcv_data->error), "Read card\nfailed"); - nfc_worker->callback(NfcWorkerEventWrongCardDetected, nfc_worker->context); - } else { - FURI_LOG_D(TAG, " => success, wait for chip to disappear."); - nfc_worker->callback(NfcWorkerEventCardDetected, nfc_worker->context); - } - } else { - FURI_LOG_D(TAG, " => success, wait for chip to disappear."); - nfc_worker->callback(NfcWorkerEventCardDetected, nfc_worker->context); - } - - while(slix_get_random(NULL) == ERR_NONE) { - furi_delay_ms(100); - } - - FURI_LOG_D(TAG, " => chip is already visible, wait for chip to disappear.\r\n"); - nfc_worker->callback(NfcWorkerEventAborted, nfc_worker->context); - while(slix_get_random(NULL) == ERR_NONE) { - furi_delay_ms(100); - } - - key_data[0] = 0; - key_data[1] = 0; - key_data[2] = 0; - key_data[3] = 0; - - } else { - /* chip is invisible, try to unlock */ - FURI_LOG_D(TAG, " chip is invisible, unlocking"); - - if(nfcv_data->auth_method == NfcVAuthMethodManual) { - key |= key_data[0] << 24; - key |= key_data[1] << 16; - key |= key_data[2] << 8; - key |= key_data[3] << 0; - - ret = slix_unlock(nfcv_data, 4); - } else { - key = 0x7FFD6E5B; - key_data[0] = (key >> 24) & 0xFF; - key_data[1] = (key >> 16) & 0xFF; - key_data[2] = (key >> 8) & 0xFF; - key_data[3] = (key >> 0) & 0xFF; - ret = slix_unlock(nfcv_data, 4); - - if(ret != ERR_NONE) { - /* main key failed, trying second one */ - FURI_LOG_D(TAG, " trying second key after resetting"); - - /* reset chip */ - furi_hal_nfc_ll_txrx_off(); - furi_delay_ms(20); - furi_hal_nfc_ll_txrx_on(); - - if(slix_get_random(nfcv_data) != ERR_NONE) { - FURI_LOG_D(TAG, " reset failed"); - } - - key = 0x0F0F0F0F; - key_data[0] = (key >> 24) & 0xFF; - key_data[1] = (key >> 16) & 0xFF; - key_data[2] = (key >> 8) & 0xFF; - key_data[3] = (key >> 0) & 0xFF; - ret = slix_unlock(nfcv_data, 4); - } - } - if(ret != ERR_NONE) { - /* unlock failed */ - FURI_LOG_D(TAG, " => failed, wait for chip to disappear."); - snprintf( - nfcv_data->error, sizeof(nfcv_data->error), "Passwords not\naccepted"); - nfc_worker->callback(NfcWorkerEventWrongCardDetected, nfc_worker->context); - - /* reset chip */ - furi_hal_nfc_ll_txrx_off(); - furi_delay_ms(20); - furi_hal_nfc_ll_txrx_on(); - - /* wait for disappearing */ - while(slix_get_random(NULL) == ERR_NONE) { - furi_delay_ms(100); - } - } - } - } else { - nfc_worker->callback(NfcWorkerEventNoCardDetected, nfc_worker->context); - } - - furi_hal_nfc_ll_txrx_off(); - furi_hal_nfc_sleep(); - furi_delay_ms(100); - } - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } -} - -static bool nfc_worker_read_mf_ultralight(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - bool read_success = false; - MfUltralightReader reader = {}; - MfUltralightData data = {}; - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, tx_rx, false); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - do { - // Try to read supported card - FURI_LOG_I(TAG, "Trying to read a supported card ..."); - for(size_t i = 0; i < NfcSupportedCardTypeEnd; i++) { - if(nfc_supported_card[i].protocol == NfcDeviceProtocolMifareUl) { - if(nfc_supported_card[i].verify(nfc_worker, tx_rx)) { - if(nfc_supported_card[i].read(nfc_worker, tx_rx)) { - read_success = true; - nfc_supported_card[i].parse(nfc_worker->dev_data); - break; - } - } else { - furi_hal_nfc_sleep(); - } - } - } - if(read_success) break; - furi_hal_nfc_sleep(); - - // Otherwise, try to read as usual - if(!furi_hal_nfc_detect(&nfc_worker->dev_data->nfc_data, 200)) break; - if(!mf_ul_read_card(tx_rx, &reader, &data)) break; - // Copy data - nfc_worker->dev_data->mf_ul_data = data; - read_success = true; - } while(false); - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } - - return read_success; -} - -static bool nfc_worker_read_mf_classic(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker->callback); - bool read_success = false; - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, tx_rx, false); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - do { - // Try to read supported card - FURI_LOG_I(TAG, "Trying to read a supported card ..."); - for(size_t i = 0; i < NfcSupportedCardTypeEnd; i++) { - if(nfc_supported_card[i].protocol == NfcDeviceProtocolMifareClassic) { - if(nfc_supported_card[i].verify(nfc_worker, tx_rx)) { - if(nfc_supported_card[i].read(nfc_worker, tx_rx)) { - read_success = true; - nfc_supported_card[i].parse(nfc_worker->dev_data); - break; - } - } else { - furi_hal_nfc_sleep(); - } - } - } - if(read_success) break; - // Try to read card with key cache - FURI_LOG_I(TAG, "Search for key cache ..."); - if(nfc_worker->callback(NfcWorkerEventReadMfClassicLoadKeyCache, nfc_worker->context)) { - FURI_LOG_I(TAG, "Load keys cache success. Start reading"); - uint8_t sectors_read = - mf_classic_update_card(tx_rx, &nfc_worker->dev_data->mf_classic_data); - uint8_t sectors_total = - mf_classic_get_total_sectors_num(nfc_worker->dev_data->mf_classic_data.type); - FURI_LOG_I(TAG, "Read %d sectors out of %d total", sectors_read, sectors_total); - read_success = mf_classic_is_card_read(&nfc_worker->dev_data->mf_classic_data); - } - } while(false); - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } - return read_success; -} - -static bool nfc_worker_read_mf_desfire(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - bool read_success = false; - MifareDesfireData* data = &nfc_worker->dev_data->mf_df_data; - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, tx_rx, false); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - do { - if(!furi_hal_nfc_detect(&nfc_worker->dev_data->nfc_data, 300)) break; - if(!mf_df_read_card(tx_rx, data)) break; - FURI_LOG_I(TAG, "Trying to parse a supported card ..."); - - // The model for parsing DESFire is a little different to other cards; - // we don't have parsers to provide encryption keys, so we can read the - // data normally, and then pass the read data to a parser. - // - // There are fully-protected DESFire cards, but providing keys for them - // is difficult (and unnessesary for many transit cards). - for(size_t i = 0; i < NfcSupportedCardTypeEnd; i++) { - if(nfc_supported_card[i].protocol == NfcDeviceProtocolMifareDesfire) { - if(nfc_supported_card[i].parse(nfc_worker->dev_data)) break; - } - } - read_success = true; - } while(false); - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } - - return read_success; -} - -static bool nfc_worker_read_bank_card(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - bool read_success = false; - EmvApplication emv_app = {}; - EmvData* result = &nfc_worker->dev_data->emv_data; - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, tx_rx, false); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - // Bank cards require strong field to start application. If we find AID, try at least several - // times to start EMV application - uint8_t start_application_attempts = 0; - while(start_application_attempts < 3) { - if(nfc_worker->state != NfcWorkerStateRead) break; - start_application_attempts++; - if(!furi_hal_nfc_detect(&nfc_worker->dev_data->nfc_data, 300)) break; - if(emv_read_bank_card(tx_rx, &emv_app)) { - FURI_LOG_D(TAG, "Bank card number read from %d attempt", start_application_attempts); - break; - } else if(emv_app.aid_len && !emv_app.app_started) { - FURI_LOG_D( - TAG, - "AID found but failed to start EMV app from %d attempt", - start_application_attempts); - furi_hal_nfc_sleep(); - continue; - } else { - FURI_LOG_D(TAG, "Failed to find AID"); - break; - } - } - // Copy data - if(emv_app.aid_len) { - result->aid_len = emv_app.aid_len; - memcpy(result->aid, emv_app.aid, result->aid_len); - read_success = true; - } - if(emv_app.card_number_len) { - result->number_len = emv_app.card_number_len; - memcpy(result->number, emv_app.card_number, result->number_len); - } - if(emv_app.name_found) { - memcpy(result->name, emv_app.name, sizeof(emv_app.name)); - } - if(emv_app.exp_month) { - result->exp_mon = emv_app.exp_month; - result->exp_year = emv_app.exp_year; - } - if(emv_app.country_code) { - result->country_code = emv_app.country_code; - } - if(emv_app.currency_code) { - result->currency_code = emv_app.currency_code; - } - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } - - return read_success; -} - -static bool nfc_worker_read_nfca(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - - bool card_read = false; - furi_hal_nfc_sleep(); - if(mf_ul_check_card_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak)) { - FURI_LOG_I(TAG, "Mifare Ultralight / NTAG detected"); - nfc_worker->dev_data->protocol = NfcDeviceProtocolMifareUl; - card_read = nfc_worker_read_mf_ultralight(nfc_worker, tx_rx); - } else if(mf_classic_check_card_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak)) { - FURI_LOG_I(TAG, "Mifare Classic detected"); - nfc_worker->dev_data->protocol = NfcDeviceProtocolMifareClassic; - nfc_worker->dev_data->mf_classic_data.type = - mf_classic_get_classic_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak); - card_read = nfc_worker_read_mf_classic(nfc_worker, tx_rx); - } else if(mf_df_check_card_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak)) { - FURI_LOG_I(TAG, "Mifare DESFire detected"); - nfc_worker->dev_data->protocol = NfcDeviceProtocolMifareDesfire; - if(!nfc_worker_read_mf_desfire(nfc_worker, tx_rx)) { - FURI_LOG_I(TAG, "Unknown card. Save UID"); - nfc_worker->dev_data->protocol = NfcDeviceProtocolUnknown; - } - card_read = true; - } else if(nfc_data->interface == FuriHalNfcInterfaceIsoDep) { - FURI_LOG_I(TAG, "ISO14443-4 card detected"); - nfc_worker->dev_data->protocol = NfcDeviceProtocolEMV; - if(!nfc_worker_read_bank_card(nfc_worker, tx_rx)) { - FURI_LOG_I(TAG, "Unknown card. Save UID"); - nfc_worker->dev_data->protocol = NfcDeviceProtocolUnknown; - } - card_read = true; - } else { - nfc_worker->dev_data->protocol = NfcDeviceProtocolUnknown; - card_read = true; - } - - return card_read; -} - -void nfc_worker_read(NfcWorker* nfc_worker) { - furi_assert(nfc_worker); - furi_assert(nfc_worker->callback); - - nfc_device_data_clear(nfc_worker->dev_data); - NfcDeviceData* dev_data = nfc_worker->dev_data; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - FuriHalNfcTxRxContext tx_rx = {}; - NfcWorkerEvent event = 0; - bool card_not_detected_notified = false; - - while(nfc_worker->state == NfcWorkerStateRead) { - if(furi_hal_nfc_detect(nfc_data, 300)) { - // Process first found device - nfc_worker->callback(NfcWorkerEventCardDetected, nfc_worker->context); - card_not_detected_notified = false; - if(nfc_data->type == FuriHalNfcTypeA) { - if(nfc_worker_read_nfca(nfc_worker, &tx_rx)) { - if(dev_data->protocol == NfcDeviceProtocolMifareUl) { - event = NfcWorkerEventReadMfUltralight; - break; - } else if(dev_data->protocol == NfcDeviceProtocolMifareClassic) { - event = NfcWorkerEventReadMfClassicDone; - break; - } else if(dev_data->protocol == NfcDeviceProtocolMifareDesfire) { - event = NfcWorkerEventReadMfDesfire; - break; - } else if(dev_data->protocol == NfcDeviceProtocolEMV) { - event = NfcWorkerEventReadBankCard; - break; - } else if(dev_data->protocol == NfcDeviceProtocolUnknown) { - event = NfcWorkerEventReadUidNfcA; - break; - } - } else { - if(dev_data->protocol == NfcDeviceProtocolMifareClassic) { - event = NfcWorkerEventReadMfClassicDictAttackRequired; - break; - } - } - } else if(nfc_data->type == FuriHalNfcTypeB) { - event = NfcWorkerEventReadUidNfcB; - break; - } else if(nfc_data->type == FuriHalNfcTypeF) { - event = NfcWorkerEventReadUidNfcF; - break; - } else if(nfc_data->type == FuriHalNfcTypeV) { - FURI_LOG_I(TAG, "NfcV detected"); - nfc_worker->dev_data->protocol = NfcDeviceProtocolNfcV; - if(nfc_worker_read_nfcv(nfc_worker, &tx_rx)) { - FURI_LOG_I(TAG, "nfc_worker_read_nfcv success"); - } - event = NfcWorkerEventReadNfcV; - break; - } - } else { - if(!card_not_detected_notified) { - nfc_worker->callback(NfcWorkerEventNoCardDetected, nfc_worker->context); - card_not_detected_notified = true; - } - } - furi_hal_nfc_sleep(); - furi_delay_ms(100); - } - // Notify caller and exit - if(event > NfcWorkerEventReserved) { - nfc_worker->callback(event, nfc_worker->context); - } -} - -void nfc_worker_read_type(NfcWorker* nfc_worker) { - furi_assert(nfc_worker); - furi_assert(nfc_worker->callback); - - NfcReadMode read_mode = nfc_worker->dev_data->read_mode; - nfc_device_data_clear(nfc_worker->dev_data); - NfcDeviceData* dev_data = nfc_worker->dev_data; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - FuriHalNfcTxRxContext tx_rx = {}; - NfcWorkerEvent event = 0; - bool card_not_detected_notified = false; - - while(nfc_worker->state == NfcWorkerStateRead) { - if(furi_hal_nfc_detect(nfc_data, 300)) { - FURI_LOG_D(TAG, "Card detected"); - furi_hal_nfc_sleep(); - // Process first found device - nfc_worker->callback(NfcWorkerEventCardDetected, nfc_worker->context); - card_not_detected_notified = false; - if(nfc_data->type == FuriHalNfcTypeA) { - if(read_mode == NfcReadModeMfClassic) { - nfc_worker->dev_data->protocol = NfcDeviceProtocolMifareClassic; - nfc_worker->dev_data->mf_classic_data.type = mf_classic_get_classic_type( - nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak); - if(nfc_worker_read_mf_classic(nfc_worker, &tx_rx)) { - FURI_LOG_D(TAG, "Card read"); - dev_data->protocol = NfcDeviceProtocolMifareClassic; - event = NfcWorkerEventReadMfClassicDone; - break; - } else { - FURI_LOG_D(TAG, "Card read failed"); - dev_data->protocol = NfcDeviceProtocolMifareClassic; - event = NfcWorkerEventReadMfClassicDictAttackRequired; - break; - } - } else if(read_mode == NfcReadModeMfUltralight) { - FURI_LOG_I(TAG, "Mifare Ultralight / NTAG"); - nfc_worker->dev_data->protocol = NfcDeviceProtocolMifareUl; - if(nfc_worker_read_mf_ultralight(nfc_worker, &tx_rx)) { - event = NfcWorkerEventReadMfUltralight; - break; - } - } else if(read_mode == NfcReadModeMfDesfire) { - nfc_worker->dev_data->protocol = NfcDeviceProtocolMifareDesfire; - if(nfc_worker_read_mf_desfire(nfc_worker, &tx_rx)) { - event = NfcWorkerEventReadMfDesfire; - break; - } - } else if(read_mode == NfcReadModeEMV) { - nfc_worker->dev_data->protocol = NfcDeviceProtocolEMV; - if(nfc_worker_read_bank_card(nfc_worker, &tx_rx)) { - event = NfcWorkerEventReadBankCard; - break; - } - } else if(read_mode == NfcReadModeNFCA) { - nfc_worker->dev_data->protocol = NfcDeviceProtocolUnknown; - event = NfcWorkerEventReadUidNfcA; - break; - } - } - } else { - if(!card_not_detected_notified) { - nfc_worker->callback(NfcWorkerEventNoCardDetected, nfc_worker->context); - card_not_detected_notified = true; - } - } - furi_hal_nfc_sleep(); - furi_delay_ms(100); - } - // Notify caller and exit - if(event > NfcWorkerEventReserved) { - nfc_worker->callback(event, nfc_worker->context); - } -} - -void nfc_worker_emulate_uid(NfcWorker* nfc_worker) { - FuriHalNfcTxRxContext tx_rx = {}; - FuriHalNfcDevData* data = &nfc_worker->dev_data->nfc_data; - NfcReaderRequestData* reader_data = &nfc_worker->dev_data->reader_data; - - // TODO add support for RATS - // Need to save ATS to support ISO-14443A-4 emulation - - while(nfc_worker->state == NfcWorkerStateUidEmulate) { - if(furi_hal_nfc_listen(data->uid, data->uid_len, data->atqa, data->sak, false, 100)) { - if(furi_hal_nfc_tx_rx(&tx_rx, 100)) { - reader_data->size = tx_rx.rx_bits / 8; - if(reader_data->size > 0) { - memcpy(reader_data->data, tx_rx.rx_data, reader_data->size); - if(nfc_worker->callback) { - nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context); - } - } - } else { - FURI_LOG_E(TAG, "Failed to get reader commands"); - } - } - } -} - -void nfc_worker_emulate_apdu(NfcWorker* nfc_worker) { - FuriHalNfcTxRxContext tx_rx = {}; - FuriHalNfcDevData params = { - .uid = {0xCF, 0x72, 0xd4, 0x40}, - .uid_len = 4, - .atqa = {0x00, 0x04}, - .sak = 0x20, - .type = FuriHalNfcTypeA, - }; - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, &tx_rx, true); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - while(nfc_worker->state == NfcWorkerStateEmulateApdu) { //-V1044 - if(furi_hal_nfc_listen(params.uid, params.uid_len, params.atqa, params.sak, false, 300)) { - FURI_LOG_D(TAG, "POS terminal detected"); - if(emv_card_emulation(&tx_rx)) { - FURI_LOG_D(TAG, "EMV card emulated"); - } - } else { - FURI_LOG_D(TAG, "Can't find reader"); - } - furi_hal_nfc_sleep(); - furi_delay_ms(20); - } - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } -} - -void nfc_worker_mf_ultralight_auth_received_callback(MfUltralightAuth auth, void* context) { - furi_assert(context); - - NfcWorker* nfc_worker = context; - nfc_worker->dev_data->mf_ul_auth = auth; - if(nfc_worker->callback) { - nfc_worker->callback(NfcWorkerEventMfUltralightPwdAuth, nfc_worker->context); - } -} - -void nfc_worker_emulate_mf_ultralight(NfcWorker* nfc_worker) { - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - MfUltralightEmulator emulator = {}; - mf_ul_prepare_emulation(&emulator, &nfc_worker->dev_data->mf_ul_data); - - // TODO rework with reader analyzer - emulator.auth_received_callback = nfc_worker_mf_ultralight_auth_received_callback; - emulator.context = nfc_worker; - - rfal_platform_spi_acquire(); - - while(nfc_worker->state == NfcWorkerStateMfUltralightEmulate) { - mf_ul_reset_emulation(&emulator, true); - furi_hal_nfc_emulate_nfca( - nfc_data->uid, - nfc_data->uid_len, - nfc_data->atqa, - nfc_data->sak, - mf_ul_prepare_emulation_response, - &emulator, - 5000); - // Check if data was modified - if(emulator.data_changed) { - nfc_worker->dev_data->mf_ul_data = emulator.data; - if(nfc_worker->callback) { - nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context); - } - emulator.data_changed = false; - } - } - - rfal_platform_spi_release(); -} - -static bool nfc_worker_mf_get_b_key_from_sector_trailer( - FuriHalNfcTxRxContext* tx_rx, - uint16_t sector, - uint64_t key, - uint64_t* found_key) { - // Some access conditions allow reading B key via A key - - uint8_t block = mf_classic_get_sector_trailer_block_num_by_sector(sector); - - Crypto1 crypto = {}; - MfClassicBlock block_tmp = {}; - MfClassicAuthContext auth_context = {.sector = sector, .key_a = MF_CLASSIC_NO_KEY, .key_b = 0}; - - furi_hal_nfc_sleep(); - - if(mf_classic_auth_attempt(tx_rx, &crypto, &auth_context, key)) { - if(mf_classic_read_block(tx_rx, &crypto, block, &block_tmp)) { - *found_key = nfc_util_bytes2num(&block_tmp.value[10], sizeof(uint8_t) * 6); - - return *found_key; - } - } - - return false; -} - -static void nfc_worker_mf_classic_key_attack( - NfcWorker* nfc_worker, - uint64_t key, - FuriHalNfcTxRxContext* tx_rx, - uint16_t start_sector) { - furi_assert(nfc_worker); - furi_assert(nfc_worker->callback); - - bool card_found_notified = true; - bool card_removed_notified = false; - - MfClassicData* data = &nfc_worker->dev_data->mf_classic_data; - NfcMfClassicDictAttackData* dict_attack_data = - &nfc_worker->dev_data->mf_classic_dict_attack_data; - uint32_t total_sectors = mf_classic_get_total_sectors_num(data->type); - - furi_assert(start_sector < total_sectors); - - nfc_worker->callback(NfcWorkerEventKeyAttackStart, nfc_worker->context); - - // Check every sector's A and B keys with the given key - for(size_t i = start_sector; i < total_sectors; i++) { - nfc_worker->callback(NfcWorkerEventKeyAttackNextSector, nfc_worker->context); - dict_attack_data->current_sector = i; - furi_hal_nfc_sleep(); - if(furi_hal_nfc_activate_nfca(200, NULL)) { - furi_hal_nfc_sleep(); - if(!card_found_notified) { - nfc_worker->callback(NfcWorkerEventCardDetected, nfc_worker->context); - card_found_notified = true; - card_removed_notified = false; - } - uint8_t block_num = mf_classic_get_sector_trailer_block_num_by_sector(i); - if(mf_classic_is_sector_read(data, i)) continue; - if(!mf_classic_is_key_found(data, i, MfClassicKeyA)) { - FURI_LOG_D(TAG, "Trying A key for sector %d, key: %012llX", i, key); - if(mf_classic_authenticate(tx_rx, block_num, key, MfClassicKeyA)) { - mf_classic_set_key_found(data, i, MfClassicKeyA, key); - FURI_LOG_D(TAG, "Key A found: %012llX", key); - nfc_worker->callback(NfcWorkerEventFoundKeyA, nfc_worker->context); - - uint64_t found_key; - if(nfc_worker_mf_get_b_key_from_sector_trailer(tx_rx, i, key, &found_key)) { - FURI_LOG_D(TAG, "Found B key via reading sector %d", i); - mf_classic_set_key_found(data, i, MfClassicKeyB, found_key); - - if(nfc_worker->state == NfcWorkerStateMfClassicDictAttack) { - nfc_worker->callback(NfcWorkerEventFoundKeyB, nfc_worker->context); - } - } - } - furi_hal_nfc_sleep(); - } - if(!mf_classic_is_key_found(data, i, MfClassicKeyB)) { - FURI_LOG_D(TAG, "Trying B key for sector %d, key: %012llX", i, key); - if(mf_classic_authenticate(tx_rx, block_num, key, MfClassicKeyB)) { - mf_classic_set_key_found(data, i, MfClassicKeyB, key); - FURI_LOG_D(TAG, "Key B found: %012llX", key); - nfc_worker->callback(NfcWorkerEventFoundKeyB, nfc_worker->context); - } - } - - if(mf_classic_is_sector_read(data, i)) continue; - mf_classic_read_sector(tx_rx, data, i); - } else { - if(!card_removed_notified) { - nfc_worker->callback(NfcWorkerEventNoCardDetected, nfc_worker->context); - card_removed_notified = true; - card_found_notified = false; - } - } - if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack) break; - } - nfc_worker->callback(NfcWorkerEventKeyAttackStop, nfc_worker->context); -} - -void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker) { - furi_assert(nfc_worker); - furi_assert(nfc_worker->callback); - - MfClassicData* data = &nfc_worker->dev_data->mf_classic_data; - NfcMfClassicDictAttackData* dict_attack_data = - &nfc_worker->dev_data->mf_classic_dict_attack_data; - uint32_t total_sectors = mf_classic_get_total_sectors_num(data->type); - uint64_t key = 0; - uint64_t prev_key = 0; - FuriHalNfcTxRxContext tx_rx = {}; - bool card_found_notified = true; - bool card_removed_notified = false; - - // Load dictionary - MfClassicDict* dict = dict_attack_data->dict; - if(!dict) { - FURI_LOG_E(TAG, "Dictionary not found"); - nfc_worker->callback(NfcWorkerEventNoDictFound, nfc_worker->context); - return; - } - - FURI_LOG_D( - TAG, "Start Dictionary attack, Key Count %lu", mf_classic_dict_get_total_keys(dict)); - for(size_t i = 0; i < total_sectors; i++) { - FURI_LOG_I(TAG, "Sector %d", i); - nfc_worker->callback(NfcWorkerEventNewSector, nfc_worker->context); - uint8_t block_num = mf_classic_get_sector_trailer_block_num_by_sector(i); - if(mf_classic_is_sector_read(data, i)) continue; - if(mf_classic_is_key_found(data, i, MfClassicKeyA) && - mf_classic_is_key_found(data, i, MfClassicKeyB)) - continue; - uint16_t key_index = 0; - while(mf_classic_dict_get_next_key(dict, &key)) { - FURI_LOG_T(TAG, "Key %d", key_index); - if(++key_index % NFC_DICT_KEY_BATCH_SIZE == 0) { - nfc_worker->callback(NfcWorkerEventNewDictKeyBatch, nfc_worker->context); - } - furi_hal_nfc_sleep(); - uint32_t cuid; - if(furi_hal_nfc_activate_nfca(200, &cuid)) { - bool deactivated = false; - if(!card_found_notified) { - nfc_worker->callback(NfcWorkerEventCardDetected, nfc_worker->context); - card_found_notified = true; - card_removed_notified = false; - nfc_worker_mf_classic_key_attack(nfc_worker, prev_key, &tx_rx, i); - deactivated = true; - } - FURI_LOG_D(TAG, "Try to auth to sector %d with key %012llX", i, key); - if(!mf_classic_is_key_found(data, i, MfClassicKeyA)) { - if(mf_classic_authenticate_skip_activate( - &tx_rx, block_num, key, MfClassicKeyA, !deactivated, cuid)) { - mf_classic_set_key_found(data, i, MfClassicKeyA, key); - FURI_LOG_D(TAG, "Key A found: %012llX", key); - nfc_worker->callback(NfcWorkerEventFoundKeyA, nfc_worker->context); - - uint64_t found_key; - if(nfc_worker_mf_get_b_key_from_sector_trailer( - &tx_rx, i, key, &found_key)) { - FURI_LOG_D(TAG, "Found B key via reading sector %d", i); - mf_classic_set_key_found(data, i, MfClassicKeyB, found_key); - - if(nfc_worker->state == NfcWorkerStateMfClassicDictAttack) { - nfc_worker->callback(NfcWorkerEventFoundKeyB, nfc_worker->context); - } - - nfc_worker_mf_classic_key_attack(nfc_worker, found_key, &tx_rx, i + 1); - break; - } - nfc_worker_mf_classic_key_attack(nfc_worker, key, &tx_rx, i + 1); - } - furi_hal_nfc_sleep(); - deactivated = true; - } else { - // If the key A is marked as found and matches the searching key, invalidate it - MfClassicSectorTrailer* sec_trailer = - mf_classic_get_sector_trailer_by_sector(data, i); - - uint8_t current_key[6]; - nfc_util_num2bytes(key, 6, current_key); - - if(mf_classic_is_key_found(data, i, MfClassicKeyA) && - memcmp(sec_trailer->key_a, current_key, 6) == 0) { - if(!mf_classic_authenticate_skip_activate( - &tx_rx, block_num, key, MfClassicKeyA, !deactivated, cuid)) { - mf_classic_set_key_not_found(data, i, MfClassicKeyA); - FURI_LOG_D(TAG, "Key %dA not found in attack", i); - } - } - furi_hal_nfc_sleep(); - deactivated = true; - } - if(!mf_classic_is_key_found(data, i, MfClassicKeyB)) { - if(mf_classic_authenticate_skip_activate( - &tx_rx, block_num, key, MfClassicKeyB, !deactivated, cuid)) { //-V547 - FURI_LOG_D(TAG, "Key B found: %012llX", key); - mf_classic_set_key_found(data, i, MfClassicKeyB, key); - nfc_worker->callback(NfcWorkerEventFoundKeyB, nfc_worker->context); - nfc_worker_mf_classic_key_attack(nfc_worker, key, &tx_rx, i + 1); - } - deactivated = true; //-V1048 - } else { - // If the key B is marked as found and matches the searching key, invalidate it - MfClassicSectorTrailer* sec_trailer = - mf_classic_get_sector_trailer_by_sector(data, i); - - uint8_t current_key[6]; - nfc_util_num2bytes(key, 6, current_key); - - if(mf_classic_is_key_found(data, i, MfClassicKeyB) && - memcmp(sec_trailer->key_b, current_key, 6) == 0) { - if(!mf_classic_authenticate_skip_activate( - &tx_rx, block_num, key, MfClassicKeyB, !deactivated, cuid)) { //-V547 - mf_classic_set_key_not_found(data, i, MfClassicKeyB); - FURI_LOG_D(TAG, "Key %dB not found in attack", i); - } - furi_hal_nfc_sleep(); - deactivated = true; //-V1048 - } - } - if(mf_classic_is_key_found(data, i, MfClassicKeyA) && - mf_classic_is_key_found(data, i, MfClassicKeyB)) - break; - if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack) break; - } else { - if(!card_removed_notified) { - nfc_worker->callback(NfcWorkerEventNoCardDetected, nfc_worker->context); - card_removed_notified = true; - card_found_notified = false; - } - if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack) break; - } - prev_key = key; - } - if(nfc_worker->state != NfcWorkerStateMfClassicDictAttack) break; - mf_classic_read_sector(&tx_rx, data, i); - mf_classic_dict_rewind(dict); - } - if(nfc_worker->state == NfcWorkerStateMfClassicDictAttack) { - nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context); - } else { - nfc_worker->callback(NfcWorkerEventAborted, nfc_worker->context); - } -} - -void nfc_worker_emulate_mf_classic(NfcWorker* nfc_worker) { - FuriHalNfcTxRxContext tx_rx = {}; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - MfClassicEmulator emulator = { - .cuid = nfc_util_bytes2num(&nfc_data->uid[nfc_data->uid_len - 4], 4), - .data = nfc_worker->dev_data->mf_classic_data, - .data_changed = false, - }; - NfcaSignal* nfca_signal = nfca_signal_alloc(); - tx_rx.nfca_signal = nfca_signal; - - rfal_platform_spi_acquire(); - - furi_hal_nfc_listen_start(nfc_data); - while(nfc_worker->state == NfcWorkerStateMfClassicEmulate) { //-V1044 - if(furi_hal_nfc_listen_rx(&tx_rx, 300)) { - if(!mf_classic_emulator(&emulator, &tx_rx, false)) { - furi_hal_nfc_listen_start(nfc_data); - } - } - } - if(emulator.data_changed) { - nfc_worker->dev_data->mf_classic_data = emulator.data; - if(nfc_worker->callback) { - nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context); - } - emulator.data_changed = false; - } - - nfca_signal_free(nfca_signal); - - rfal_platform_spi_release(); -} - -void nfc_worker_write_mf_classic(NfcWorker* nfc_worker) { - FuriHalNfcTxRxContext tx_rx = {}; - bool card_found_notified = false; - FuriHalNfcDevData nfc_data = {}; - MfClassicData* src_data = &nfc_worker->dev_data->mf_classic_data; - MfClassicData dest_data = *src_data; - - while(nfc_worker->state == NfcWorkerStateMfClassicWrite) { - if(furi_hal_nfc_detect(&nfc_data, 200)) { - if(!card_found_notified) { - nfc_worker->callback(NfcWorkerEventCardDetected, nfc_worker->context); - card_found_notified = true; - } - furi_hal_nfc_sleep(); - - FURI_LOG_I(TAG, "Check low level nfc data"); - if(memcmp(&nfc_data, &nfc_worker->dev_data->nfc_data, sizeof(FuriHalNfcDevData)) != - 0) { - FURI_LOG_E(TAG, "Wrong card"); - nfc_worker->callback(NfcWorkerEventWrongCard, nfc_worker->context); - break; - } - - FURI_LOG_I(TAG, "Check mf classic type"); - MfClassicType type = - mf_classic_get_classic_type(nfc_data.atqa[0], nfc_data.atqa[1], nfc_data.sak); - if(type != nfc_worker->dev_data->mf_classic_data.type) { - FURI_LOG_E(TAG, "Wrong mf classic type"); - nfc_worker->callback(NfcWorkerEventWrongCard, nfc_worker->context); - break; - } - - // Set blocks not read - mf_classic_set_sector_data_not_read(&dest_data); - FURI_LOG_I(TAG, "Updating card sectors"); - uint8_t total_sectors = mf_classic_get_total_sectors_num(type); - bool write_success = true; - for(uint8_t i = 0; i < total_sectors; i++) { - FURI_LOG_I(TAG, "Reading sector %d", i); - mf_classic_read_sector(&tx_rx, &dest_data, i); - bool old_data_read = mf_classic_is_sector_data_read(src_data, i); - bool new_data_read = mf_classic_is_sector_data_read(&dest_data, i); - if(old_data_read != new_data_read) { - FURI_LOG_E(TAG, "Failed to update sector %d", i); - write_success = false; - break; - } - if(nfc_worker->state != NfcWorkerStateMfClassicWrite) break; - if(!mf_classic_write_sector(&tx_rx, &dest_data, src_data, i)) { - FURI_LOG_E(TAG, "Failed to write %d sector", i); - write_success = false; - break; - } - } - if(nfc_worker->state != NfcWorkerStateMfClassicWrite) break; - if(write_success) { - nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context); - break; - } else { - nfc_worker->callback(NfcWorkerEventFail, nfc_worker->context); - break; - } - - } else { - if(card_found_notified) { - nfc_worker->callback(NfcWorkerEventNoCardDetected, nfc_worker->context); - card_found_notified = false; - } - } - furi_delay_ms(300); - } -} - -void nfc_worker_update_mf_classic(NfcWorker* nfc_worker) { - FuriHalNfcTxRxContext tx_rx = {}; - bool card_found_notified = false; - FuriHalNfcDevData nfc_data = {}; - MfClassicData* old_data = &nfc_worker->dev_data->mf_classic_data; - MfClassicData new_data = *old_data; - - while(nfc_worker->state == NfcWorkerStateMfClassicUpdate) { - if(furi_hal_nfc_detect(&nfc_data, 200)) { - if(!card_found_notified) { - nfc_worker->callback(NfcWorkerEventCardDetected, nfc_worker->context); - card_found_notified = true; - } - furi_hal_nfc_sleep(); - - FURI_LOG_I(TAG, "Check low level nfc data"); - if(memcmp(&nfc_data, &nfc_worker->dev_data->nfc_data, sizeof(FuriHalNfcDevData)) != - 0) { - FURI_LOG_E(TAG, "Low level nfc data mismatch"); - nfc_worker->callback(NfcWorkerEventWrongCard, nfc_worker->context); - break; - } - - FURI_LOG_I(TAG, "Check MF classic type"); - MfClassicType type = - mf_classic_get_classic_type(nfc_data.atqa[0], nfc_data.atqa[1], nfc_data.sak); - if(type != nfc_worker->dev_data->mf_classic_data.type) { - FURI_LOG_E(TAG, "MF classic type mismatch"); - nfc_worker->callback(NfcWorkerEventWrongCard, nfc_worker->context); - break; - } - - // Set blocks not read - mf_classic_set_sector_data_not_read(&new_data); - FURI_LOG_I(TAG, "Updating card sectors"); - uint8_t total_sectors = mf_classic_get_total_sectors_num(type); - bool update_success = true; - for(uint8_t i = 0; i < total_sectors; i++) { - FURI_LOG_I(TAG, "Reading sector %d", i); - mf_classic_read_sector(&tx_rx, &new_data, i); - bool old_data_read = mf_classic_is_sector_data_read(old_data, i); - bool new_data_read = mf_classic_is_sector_data_read(&new_data, i); - if(old_data_read != new_data_read) { - FURI_LOG_E(TAG, "Failed to update sector %d", i); - update_success = false; - break; - } - if(nfc_worker->state != NfcWorkerStateMfClassicUpdate) break; - } - if(nfc_worker->state != NfcWorkerStateMfClassicUpdate) break; - - // Check updated data - if(update_success) { - *old_data = new_data; - nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context); - break; - } - } else { - if(card_found_notified) { - nfc_worker->callback(NfcWorkerEventNoCardDetected, nfc_worker->context); - card_found_notified = false; - } - } - furi_delay_ms(300); - } -} - -void nfc_worker_mf_ultralight_read_auth(NfcWorker* nfc_worker) { - furi_assert(nfc_worker); - furi_assert(nfc_worker->callback); - - MfUltralightData* data = &nfc_worker->dev_data->mf_ul_data; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - FuriHalNfcTxRxContext tx_rx = {}; - MfUltralightReader reader = {}; - mf_ul_reset(data); - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_prepare_tx_rx(nfc_worker->reader_analyzer, &tx_rx, true); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeDebugLog); - } - - uint32_t key = 0; - uint16_t pack = 0; - while(nfc_worker->state == NfcWorkerStateReadMfUltralightReadAuth) { - furi_hal_nfc_sleep(); - if(furi_hal_nfc_detect(nfc_data, 300) && nfc_data->type == FuriHalNfcTypeA) { - if(mf_ul_check_card_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak)) { - nfc_worker->callback(NfcWorkerEventCardDetected, nfc_worker->context); - if(data->auth_method == MfUltralightAuthMethodManual || - data->auth_method == MfUltralightAuthMethodAuto) { - nfc_worker->callback(NfcWorkerEventMfUltralightPassKey, nfc_worker->context); - key = nfc_util_bytes2num(data->auth_key, 4); - } else if(data->auth_method == MfUltralightAuthMethodAmeebo) { - key = mf_ul_pwdgen_amiibo(nfc_data); - } else if(data->auth_method == MfUltralightAuthMethodXiaomi) { - key = mf_ul_pwdgen_xiaomi(nfc_data); - } else { - FURI_LOG_E(TAG, "Incorrect auth method"); - break; - } - - data->auth_success = mf_ultralight_authenticate(&tx_rx, key, &pack); - - if(!data->auth_success) { - // Reset card - furi_hal_nfc_sleep(); - if(!furi_hal_nfc_activate_nfca(300, NULL)) { - nfc_worker->callback(NfcWorkerEventFail, nfc_worker->context); - break; - } - } - - mf_ul_read_card(&tx_rx, &reader, data); - if(data->auth_success) { - MfUltralightConfigPages* config_pages = mf_ultralight_get_config_pages(data); - if(config_pages != NULL) { - config_pages->auth_data.pwd.value = REVERSE_BYTES_U32(key); - config_pages->auth_data.pack.value = pack; - } - nfc_worker->callback(NfcWorkerEventSuccess, nfc_worker->context); - break; - } else { - nfc_worker->callback(NfcWorkerEventFail, nfc_worker->context); - break; - } - } else { - nfc_worker->callback(NfcWorkerEventWrongCardDetected, nfc_worker->context); - furi_delay_ms(10); - } - } else { - nfc_worker->callback(NfcWorkerEventNoCardDetected, nfc_worker->context); - furi_delay_ms(10); - } - } - - if(furi_hal_rtc_is_flag_set(FuriHalRtcFlagDebug)) { - reader_analyzer_stop(nfc_worker->reader_analyzer); - } -} - -static void nfc_worker_reader_analyzer_callback(ReaderAnalyzerEvent event, void* context) { - furi_assert(context); - NfcWorker* nfc_worker = context; - - if((nfc_worker->state == NfcWorkerStateAnalyzeReader) && - (event == ReaderAnalyzerEventMfkeyCollected)) { - if(nfc_worker->callback) { - nfc_worker->callback(NfcWorkerEventDetectReaderMfkeyCollected, nfc_worker->context); - } - } -} - -void nfc_worker_analyze_reader(NfcWorker* nfc_worker) { - furi_assert(nfc_worker); - furi_assert(nfc_worker->callback); - - FuriHalNfcTxRxContext tx_rx = {}; - - ReaderAnalyzer* reader_analyzer = nfc_worker->reader_analyzer; - FuriHalNfcDevData* nfc_data = NULL; - if(nfc_worker->dev_data->protocol == NfcDeviceProtocolMifareClassic) { - nfc_data = &nfc_worker->dev_data->nfc_data; - reader_analyzer_set_nfc_data(reader_analyzer, nfc_data); - } else { - nfc_data = reader_analyzer_get_nfc_data(reader_analyzer); - } - MfClassicEmulator emulator = { - .cuid = nfc_util_bytes2num(&nfc_data->uid[nfc_data->uid_len - 4], 4), - .data = nfc_worker->dev_data->mf_classic_data, - .data_changed = false, - }; - NfcaSignal* nfca_signal = nfca_signal_alloc(); - tx_rx.nfca_signal = nfca_signal; - reader_analyzer_prepare_tx_rx(reader_analyzer, &tx_rx, true); - reader_analyzer_start(nfc_worker->reader_analyzer, ReaderAnalyzerModeMfkey); - reader_analyzer_set_callback(reader_analyzer, nfc_worker_reader_analyzer_callback, nfc_worker); - - rfal_platform_spi_acquire(); - - FURI_LOG_D(TAG, "Start reader analyzer"); - - uint8_t reader_no_data_received_cnt = 0; - bool reader_no_data_notified = true; - - while(nfc_worker->state == NfcWorkerStateAnalyzeReader) { - furi_hal_nfc_listen_start(nfc_data); - if(furi_hal_nfc_listen_rx(&tx_rx, 300)) { - if(reader_no_data_notified) { - nfc_worker->callback(NfcWorkerEventDetectReaderDetected, nfc_worker->context); - } - reader_no_data_received_cnt = 0; - reader_no_data_notified = false; - NfcProtocol protocol = - reader_analyzer_guess_protocol(reader_analyzer, tx_rx.rx_data, tx_rx.rx_bits / 8); - if(protocol == NfcDeviceProtocolMifareClassic) { - if(!mf_classic_emulator(&emulator, &tx_rx, true)) { - furi_hal_nfc_listen_start(nfc_data); - } - } - } else { - reader_no_data_received_cnt++; - if(!reader_no_data_notified && (reader_no_data_received_cnt > 5)) { - nfc_worker->callback(NfcWorkerEventDetectReaderLost, nfc_worker->context); - reader_no_data_received_cnt = 0; - reader_no_data_notified = true; - } - FURI_LOG_D(TAG, "No data from reader"); - continue; - } - furi_delay_ms(1); - } - - rfal_platform_spi_release(); - - reader_analyzer_stop(nfc_worker->reader_analyzer); - - nfca_signal_free(nfca_signal); -} diff --git a/lib/nfc/nfc_worker.h b/lib/nfc/nfc_worker.h deleted file mode 100644 index 7733b7919..000000000 --- a/lib/nfc/nfc_worker.h +++ /dev/null @@ -1,109 +0,0 @@ -#pragma once - -#include "nfc_device.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct NfcWorker NfcWorker; - -typedef enum { - // Init states - NfcWorkerStateNone, - NfcWorkerStateReady, - // Main worker states - NfcWorkerStateRead, - NfcWorkerStateUidEmulate, - NfcWorkerStateMfUltralightEmulate, - NfcWorkerStateMfClassicEmulate, - NfcWorkerStateMfClassicWrite, - NfcWorkerStateMfClassicUpdate, - NfcWorkerStateReadMfUltralightReadAuth, - NfcWorkerStateMfClassicDictAttack, - NfcWorkerStateAnalyzeReader, - NfcWorkerStateNfcVEmulate, - NfcWorkerStateNfcVUnlock, - NfcWorkerStateNfcVUnlockAndSave, - NfcWorkerStateNfcVSniff, - // Debug - NfcWorkerStateEmulateApdu, - NfcWorkerStateField, - // Transition - NfcWorkerStateStop, -} NfcWorkerState; - -typedef enum { - // Reserve first 50 events for application events - NfcWorkerEventReserved = 50, - - // Nfc read events - NfcWorkerEventReadUidNfcB, - NfcWorkerEventReadUidNfcV, - NfcWorkerEventReadUidNfcF, - NfcWorkerEventReadUidNfcA, - NfcWorkerEventReadMfUltralight, - NfcWorkerEventReadMfDesfire, - NfcWorkerEventReadMfClassicDone, - NfcWorkerEventReadMfClassicLoadKeyCache, - NfcWorkerEventReadMfClassicDictAttackRequired, - NfcWorkerEventReadBankCard, - NfcWorkerEventReadNfcV, - - // Nfc worker common events - NfcWorkerEventSuccess, - NfcWorkerEventFail, - NfcWorkerEventAborted, - NfcWorkerEventCardDetected, - NfcWorkerEventNoCardDetected, - NfcWorkerEventWrongCardDetected, - - // Read Mifare Classic events - NfcWorkerEventNoDictFound, - NfcWorkerEventNewSector, - NfcWorkerEventNewDictKeyBatch, - NfcWorkerEventFoundKeyA, - NfcWorkerEventFoundKeyB, - NfcWorkerEventKeyAttackStart, - NfcWorkerEventKeyAttackStop, - NfcWorkerEventKeyAttackNextSector, - - // Write Mifare Classic events - NfcWorkerEventWrongCard, - - // Detect Reader events - NfcWorkerEventDetectReaderDetected, - NfcWorkerEventDetectReaderLost, - NfcWorkerEventDetectReaderMfkeyCollected, - - // Mifare Ultralight events - NfcWorkerEventMfUltralightPassKey, // NFC worker requesting manual key - NfcWorkerEventMfUltralightPwdAuth, // Reader sent auth command - NfcWorkerEventNfcVPassKey, // NFC worker requesting manual key - NfcWorkerEventNfcVCommandExecuted, - NfcWorkerEventNfcVContentChanged, -} NfcWorkerEvent; - -typedef bool (*NfcWorkerCallback)(NfcWorkerEvent event, void* context); - -NfcWorker* nfc_worker_alloc(); - -NfcWorkerState nfc_worker_get_state(NfcWorker* nfc_worker); - -void nfc_worker_free(NfcWorker* nfc_worker); - -void nfc_worker_start( - NfcWorker* nfc_worker, - NfcWorkerState state, - NfcDeviceData* dev_data, - NfcWorkerCallback callback, - void* context); - -void nfc_worker_stop(NfcWorker* nfc_worker); -void nfc_worker_nfcv_unlock(NfcWorker* nfc_worker); -void nfc_worker_nfcv_emulate(NfcWorker* nfc_worker); -void nfc_worker_nfcv_sniff(NfcWorker* nfc_worker); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/lib/nfc/nfc_worker_i.h b/lib/nfc/nfc_worker_i.h deleted file mode 100644 index d13d3c5c8..000000000 --- a/lib/nfc/nfc_worker_i.h +++ /dev/null @@ -1,60 +0,0 @@ -#pragma once - -#include "nfc_worker.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -struct NfcWorker { - FuriThread* thread; - Storage* storage; - Stream* dict_stream; - - NfcDeviceData* dev_data; - - NfcWorkerCallback callback; - void* context; - - NfcWorkerState state; - - ReaderAnalyzer* reader_analyzer; -}; - -void nfc_worker_change_state(NfcWorker* nfc_worker, NfcWorkerState state); - -int32_t nfc_worker_task(void* context); - -void nfc_worker_read(NfcWorker* nfc_worker); - -void nfc_worker_read_type(NfcWorker* nfc_worker); - -void nfc_worker_emulate_uid(NfcWorker* nfc_worker); - -void nfc_worker_emulate_mf_ultralight(NfcWorker* nfc_worker); - -void nfc_worker_emulate_mf_classic(NfcWorker* nfc_worker); - -void nfc_worker_write_mf_classic(NfcWorker* nfc_worker); - -void nfc_worker_update_mf_classic(NfcWorker* nfc_worker); - -void nfc_worker_mf_classic_dict_attack(NfcWorker* nfc_worker); - -void nfc_worker_mf_ultralight_read_auth(NfcWorker* nfc_worker); - -void nfc_worker_mf_ul_auth_attack(NfcWorker* nfc_worker); - -void nfc_worker_emulate_apdu(NfcWorker* nfc_worker); - -void nfc_worker_analyze_reader(NfcWorker* nfc_worker); diff --git a/lib/nfc/parsers/all_in_one.c b/lib/nfc/parsers/all_in_one.c deleted file mode 100644 index edcc0d0c7..000000000 --- a/lib/nfc/parsers/all_in_one.c +++ /dev/null @@ -1,103 +0,0 @@ -#include "nfc_supported_card.h" -#include "all_in_one.h" - -#include -#include - -#include - -#define ALL_IN_ONE_LAYOUT_UNKNOWN 0 -#define ALL_IN_ONE_LAYOUT_A 1 -#define ALL_IN_ONE_LAYOUT_D 2 -#define ALL_IN_ONE_LAYOUT_E2 3 -#define ALL_IN_ONE_LAYOUT_E3 4 -#define ALL_IN_ONE_LAYOUT_E5 5 -#define ALL_IN_ONE_LAYOUT_2 6 - -uint8_t all_in_one_get_layout(NfcDeviceData* dev_data) { - // I absolutely hate what's about to happen here. - - // Switch on the second half of the third byte of page 5 - FURI_LOG_I("all_in_one", "Layout byte: %02x", dev_data->mf_ul_data.data[(4 * 5) + 2]); - FURI_LOG_I( - "all_in_one", "Layout half-byte: %02x", dev_data->mf_ul_data.data[(4 * 5) + 3] & 0x0F); - switch(dev_data->mf_ul_data.data[(4 * 5) + 2] & 0x0F) { - // If it is A, the layout type is a type A layout - case 0x0A: - return ALL_IN_ONE_LAYOUT_A; - case 0x0D: - return ALL_IN_ONE_LAYOUT_D; - case 0x02: - return ALL_IN_ONE_LAYOUT_2; - default: - FURI_LOG_I( - "all_in_one", - "Unknown layout type: %d", - dev_data->mf_ul_data.data[(4 * 5) + 2] & 0x0F); - return ALL_IN_ONE_LAYOUT_UNKNOWN; - } -} - -bool all_in_one_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - UNUSED(nfc_worker); - // If this is a all_in_one pass, first 2 bytes of page 4 are 0x45 0xD9 - MfUltralightReader reader = {}; - MfUltralightData data = {}; - - if(!mf_ul_read_card(tx_rx, &reader, &data)) { - return false; - } else { - if(data.data[4 * 4] == 0x45 && data.data[4 * 4 + 1] == 0xD9) { - FURI_LOG_I("all_in_one", "Pass verified"); - return true; - } - } - return false; -} - -bool all_in_one_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - MfUltralightReader reader = {}; - MfUltralightData data = {}; - if(!mf_ul_read_card(tx_rx, &reader, &data)) { - return false; - } else { - memcpy(&nfc_worker->dev_data->mf_ul_data, &data, sizeof(data)); - FURI_LOG_I("all_in_one", "Card read"); - return true; - } -} - -bool all_in_one_parser_parse(NfcDeviceData* dev_data) { - if(dev_data->mf_ul_data.data[4 * 4] != 0x45 || dev_data->mf_ul_data.data[4 * 4 + 1] != 0xD9) { - FURI_LOG_I("all_in_one", "Pass not verified"); - return false; - } - - uint8_t ride_count = 0; - uint32_t serial = 0; - if(all_in_one_get_layout(dev_data) == ALL_IN_ONE_LAYOUT_A) { - // If the layout is A then the ride count is stored in the first byte of page 8 - ride_count = dev_data->mf_ul_data.data[4 * 8]; - } else if(all_in_one_get_layout(dev_data) == ALL_IN_ONE_LAYOUT_D) { - // If the layout is D, the ride count is stored in the second byte of page 9 - ride_count = dev_data->mf_ul_data.data[4 * 9 + 1]; - } else { - FURI_LOG_I("all_in_one", "Unknown layout: %d", all_in_one_get_layout(dev_data)); - ride_count = 137; - } - - // I hate this with a burning passion. - - // The number starts at the second half of the third byte on page 4, and is 32 bits long - // So we get the second half of the third byte, then bytes 4-6, and then the first half of the 7th byte - // B8 17 A2 A4 BD becomes 81 7A 2A 4B - serial = - (dev_data->mf_ul_data.data[4 * 4 + 2] & 0x0F) << 28 | - dev_data->mf_ul_data.data[4 * 4 + 3] << 20 | dev_data->mf_ul_data.data[4 * 4 + 4] << 12 | - dev_data->mf_ul_data.data[4 * 4 + 5] << 4 | (dev_data->mf_ul_data.data[4 * 4 + 6] >> 4); - - // Format string for rides count - furi_string_printf( - dev_data->parsed_data, "\e#All-In-One\nNumber: %lu\nRides left: %u", serial, ride_count); - return true; -} diff --git a/lib/nfc/parsers/all_in_one.h b/lib/nfc/parsers/all_in_one.h deleted file mode 100644 index 9b646d4dc..000000000 --- a/lib/nfc/parsers/all_in_one.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "nfc_supported_card.h" - -bool all_in_one_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool all_in_one_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool all_in_one_parser_parse(NfcDeviceData* dev_data); \ No newline at end of file diff --git a/lib/nfc/parsers/nfc_supported_card.c b/lib/nfc/parsers/nfc_supported_card.c deleted file mode 100644 index 153d4d3c5..000000000 --- a/lib/nfc/parsers/nfc_supported_card.c +++ /dev/null @@ -1,82 +0,0 @@ -#include "nfc_supported_card.h" - -#include "plantain_parser.h" -#include "troika_parser.h" -#include "plantain_4k_parser.h" -#include "troika_4k_parser.h" -#include "two_cities.h" -#include "all_in_one.h" -#include "opal.h" - -NfcSupportedCard nfc_supported_card[NfcSupportedCardTypeEnd] = { - [NfcSupportedCardTypePlantain] = - { - .protocol = NfcDeviceProtocolMifareClassic, - .verify = plantain_parser_verify, - .read = plantain_parser_read, - .parse = plantain_parser_parse, - }, - [NfcSupportedCardTypeTroika] = - { - .protocol = NfcDeviceProtocolMifareClassic, - .verify = troika_parser_verify, - .read = troika_parser_read, - .parse = troika_parser_parse, - }, - [NfcSupportedCardTypePlantain4K] = - { - .protocol = NfcDeviceProtocolMifareClassic, - .verify = plantain_4k_parser_verify, - .read = plantain_4k_parser_read, - .parse = plantain_4k_parser_parse, - }, - [NfcSupportedCardTypeTroika4K] = - { - .protocol = NfcDeviceProtocolMifareClassic, - .verify = troika_4k_parser_verify, - .read = troika_4k_parser_read, - .parse = troika_4k_parser_parse, - }, - [NfcSupportedCardTypeTwoCities] = - { - .protocol = NfcDeviceProtocolMifareClassic, - .verify = two_cities_parser_verify, - .read = two_cities_parser_read, - .parse = two_cities_parser_parse, - }, - [NfcSupportedCardTypeAllInOne] = - { - .protocol = NfcDeviceProtocolMifareUl, - .verify = all_in_one_parser_verify, - .read = all_in_one_parser_read, - .parse = all_in_one_parser_parse, - }, - [NfcSupportedCardTypeOpal] = - { - .protocol = NfcDeviceProtocolMifareDesfire, - .verify = stub_parser_verify_read, - .read = stub_parser_verify_read, - .parse = opal_parser_parse, - }, - -}; - -bool nfc_supported_card_verify_and_parse(NfcDeviceData* dev_data) { - furi_assert(dev_data); - - bool card_parsed = false; - for(size_t i = 0; i < COUNT_OF(nfc_supported_card); i++) { - if(nfc_supported_card[i].parse(dev_data)) { - card_parsed = true; - break; - } - } - - return card_parsed; -} - -bool stub_parser_verify_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - UNUSED(nfc_worker); - UNUSED(tx_rx); - return false; -} diff --git a/lib/nfc/parsers/nfc_supported_card.h b/lib/nfc/parsers/nfc_supported_card.h deleted file mode 100644 index 2e8c48a87..000000000 --- a/lib/nfc/parsers/nfc_supported_card.h +++ /dev/null @@ -1,47 +0,0 @@ -#pragma once - -#include -#include "../nfc_worker.h" -#include "../nfc_device.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - NfcSupportedCardTypePlantain, - NfcSupportedCardTypeTroika, - NfcSupportedCardTypePlantain4K, - NfcSupportedCardTypeTroika4K, - NfcSupportedCardTypeTwoCities, - NfcSupportedCardTypeAllInOne, - NfcSupportedCardTypeOpal, - - NfcSupportedCardTypeEnd, -} NfcSupportedCardType; - -typedef bool (*NfcSupportedCardVerify)(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -typedef bool (*NfcSupportedCardRead)(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -typedef bool (*NfcSupportedCardParse)(NfcDeviceData* dev_data); - -typedef struct { - NfcProtocol protocol; - NfcSupportedCardVerify verify; - NfcSupportedCardRead read; - NfcSupportedCardParse parse; -} NfcSupportedCard; - -extern NfcSupportedCard nfc_supported_card[NfcSupportedCardTypeEnd]; - -bool nfc_supported_card_verify_and_parse(NfcDeviceData* dev_data); - -// stub_parser_verify_read does nothing, and always reports that it does not -// support the card. This is needed for DESFire card parsers which can't -// provide keys, and only use NfcSupportedCard->parse. -bool stub_parser_verify_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/lib/nfc/parsers/opal.c b/lib/nfc/parsers/opal.c deleted file mode 100644 index 2a6b5d122..000000000 --- a/lib/nfc/parsers/opal.c +++ /dev/null @@ -1,204 +0,0 @@ -/* - * opal.c - Parser for Opal card (Sydney, Australia). - * - * Copyright 2023 Michael Farrell - * - * This will only read "standard" MIFARE DESFire-based Opal cards. Free travel - * cards (including School Opal cards, veteran, vision-impaired persons and - * TfNSW employees' cards) and single-trip tickets are MIFARE Ultralight C - * cards and not supported. - * - * Reference: https://github.com/metrodroid/metrodroid/wiki/Opal - * - * Note: The card values are all little-endian (like Flipper), but the above - * reference was originally written based on Java APIs, which are big-endian. - * This implementation presumes a little-endian system. - * - * 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. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -#include "nfc_supported_card.h" -#include "opal.h" - -#include -#include -#include - -#include - -static const uint8_t opal_aid[3] = {0x31, 0x45, 0x53}; -static const char* opal_modes[5] = - {"Rail / Metro", "Ferry / Light Rail", "Bus", "Unknown mode", "Manly Ferry"}; -static const char* opal_usages[14] = { - "New / Unused", - "Tap on: new journey", - "Tap on: transfer from same mode", - "Tap on: transfer from other mode", - "", // Manly Ferry: new journey - "", // Manly Ferry: transfer from ferry - "", // Manly Ferry: transfer from other - "Tap off: distance fare", - "Tap off: flat fare", - "Automated tap off: failed to tap off", - "Tap off: end of trip without start", - "Tap off: reversal", - "Tap on: rejected", - "Unknown usage", -}; - -// Opal file 0x7 structure. Assumes a little-endian CPU. -typedef struct __attribute__((__packed__)) { - uint32_t serial : 32; - uint8_t check_digit : 4; - bool blocked : 1; - uint16_t txn_number : 16; - int32_t balance : 21; - uint16_t days : 15; - uint16_t minutes : 11; - uint8_t mode : 3; - uint16_t usage : 4; - bool auto_topup : 1; - uint8_t weekly_journeys : 4; - uint16_t checksum : 16; -} OpalFile; - -static_assert(sizeof(OpalFile) == 16); - -// Converts an Opal timestamp to FuriHalRtcDateTime. -// -// Opal measures days since 1980-01-01 and minutes since midnight, and presumes -// all days are 1440 minutes. -void opal_date_time_to_furi(uint16_t days, uint16_t minutes, FuriHalRtcDateTime* out) { - if(!out) return; - uint16_t diy; - out->year = 1980; - out->month = 1; - // 1980-01-01 is a Tuesday - out->weekday = ((days + 1) % 7) + 1; - out->hour = minutes / 60; - out->minute = minutes % 60; - out->second = 0; - - // What year is it? - for(;;) { - diy = furi_hal_rtc_get_days_per_year(out->year); - if(days < diy) break; - days -= diy; - out->year++; - } - - // 1-index the day of the year - days++; - // What month is it? - bool is_leap = furi_hal_rtc_is_leap_year(out->year); - - for(;;) { - uint8_t dim = furi_hal_rtc_get_days_per_month(is_leap, out->month); - if(days <= dim) break; - days -= dim; - out->month++; - } - - out->day = days; -} - -bool opal_parser_parse(NfcDeviceData* dev_data) { - if(dev_data->protocol != NfcDeviceProtocolMifareDesfire) { - return false; - } - - MifareDesfireApplication* app = mf_df_get_application(&dev_data->mf_df_data, &opal_aid); - if(app == NULL) { - return false; - } - MifareDesfireFile* f = mf_df_get_file(app, 0x07); - if(f == NULL || f->type != MifareDesfireFileTypeStandard || f->settings.data.size != 16 || - !f->contents) { - return false; - } - - OpalFile* o = (OpalFile*)f->contents; - - uint8_t serial2 = o->serial / 10000000; - uint16_t serial3 = (o->serial / 1000) % 10000; - uint16_t serial4 = (o->serial % 1000); - - if(o->check_digit > 9) { - return false; - } - - char* sign = ""; - if(o->balance < 0) { - // Negative balance. Make this a positive value again and record the - // sign separately, because then we can handle balances of -99..-1 - // cents, as the "dollars" division below would result in a positive - // zero value. - o->balance = abs(o->balance); //-V1081 - sign = "-"; - } - uint8_t cents = o->balance % 100; - int32_t dollars = o->balance / 100; - - FuriHalRtcDateTime timestamp; - opal_date_time_to_furi(o->days, o->minutes, ×tamp); - - if(o->mode >= 3) { - // 3..7 are "reserved", but we use 4 to indicate the Manly Ferry. - o->mode = 3; - } - - if(o->usage >= 4 && o->usage <= 6) { - // Usages 4..6 associated with the Manly Ferry, which correspond to - // usages 1..3 for other modes. - o->usage -= 3; - o->mode = 4; - } - - const char* mode_str = (o->mode <= 4 ? opal_modes[o->mode] : opal_modes[3]); //-V547 - const char* usage_str = (o->usage <= 12 ? opal_usages[o->usage] : opal_usages[13]); - - furi_string_printf( - dev_data->parsed_data, - "\e#Opal: $%s%ld.%02hu\n3085 22%02hhu %04hu %03hu%01hhu\n%s, %s\n", - sign, - dollars, - cents, - serial2, - serial3, - serial4, - o->check_digit, - mode_str, - usage_str); - FuriString* timestamp_str = furi_string_alloc(); - locale_format_date(timestamp_str, ×tamp, locale_get_date_format(), "-"); - furi_string_cat(dev_data->parsed_data, timestamp_str); - furi_string_cat_str(dev_data->parsed_data, " at "); - - locale_format_time(timestamp_str, ×tamp, locale_get_time_format(), false); - furi_string_cat(dev_data->parsed_data, timestamp_str); - - furi_string_free(timestamp_str); - furi_string_cat_printf( - dev_data->parsed_data, - "\nWeekly journeys: %hhu, Txn #%hu\n", - o->weekly_journeys, - o->txn_number); - - if(o->auto_topup) { - furi_string_cat_str(dev_data->parsed_data, "Auto-topup enabled\n"); - } - if(o->blocked) { - furi_string_cat_str(dev_data->parsed_data, "Card blocked\n"); - } - return true; -} diff --git a/lib/nfc/parsers/opal.h b/lib/nfc/parsers/opal.h deleted file mode 100644 index 42caf9a17..000000000 --- a/lib/nfc/parsers/opal.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once - -#include "nfc_supported_card.h" - -bool opal_parser_parse(NfcDeviceData* dev_data); diff --git a/lib/nfc/parsers/plantain_4k_parser.c b/lib/nfc/parsers/plantain_4k_parser.c deleted file mode 100644 index 19da0b5eb..000000000 --- a/lib/nfc/parsers/plantain_4k_parser.c +++ /dev/null @@ -1,124 +0,0 @@ -#include "nfc_supported_card.h" - -#include -#include - -#include - -static const MfClassicAuthContext plantain_keys_4k[] = { - {.sector = 0, .key_a = 0xFFFFFFFFFFFF, .key_b = 0xFFFFFFFFFFFF}, - {.sector = 1, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 2, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 3, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 4, .key_a = 0xe56ac127dd45, .key_b = 0x19fc84a3784b}, - {.sector = 5, .key_a = 0x77dabc9825e1, .key_b = 0x9764fec3154a}, - {.sector = 6, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 7, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 8, .key_a = 0x26973ea74321, .key_b = 0xd27058c6e2c7}, - {.sector = 9, .key_a = 0xeb0a8ff88ade, .key_b = 0x578a9ada41e3}, - {.sector = 10, .key_a = 0xea0fd73cb149, .key_b = 0x29c35fa068fb}, - {.sector = 11, .key_a = 0xc76bf71a2509, .key_b = 0x9ba241db3f56}, - {.sector = 12, .key_a = 0xacffffffffff, .key_b = 0x71f3a315ad26}, - {.sector = 13, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 14, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 15, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 16, .key_a = 0x72f96bdd3714, .key_b = 0x462225cd34cf}, - {.sector = 17, .key_a = 0x044ce1872bc3, .key_b = 0x8c90c70cff4a}, - {.sector = 18, .key_a = 0xbc2d1791dec1, .key_b = 0xca96a487de0b}, - {.sector = 19, .key_a = 0x8791b2ccb5c4, .key_b = 0xc956c3b80da3}, - {.sector = 20, .key_a = 0x8e26e45e7d65, .key_b = 0x8e65b3af7d22}, - {.sector = 21, .key_a = 0x0f318130ed18, .key_b = 0x0c420a20e056}, - {.sector = 22, .key_a = 0x045ceca15535, .key_b = 0x31bec3d9e510}, - {.sector = 23, .key_a = 0x9d993c5d4ef4, .key_b = 0x86120e488abf}, - {.sector = 24, .key_a = 0xc65d4eaa645b, .key_b = 0xb69d40d1a439}, - {.sector = 25, .key_a = 0x3a8a139c20b4, .key_b = 0x8818a9c5d406}, - {.sector = 26, .key_a = 0xbaff3053b496, .key_b = 0x4b7cb25354d3}, - {.sector = 27, .key_a = 0x7413b599c4ea, .key_b = 0xb0a2AAF3A1BA}, - {.sector = 28, .key_a = 0x0ce7cd2cc72b, .key_b = 0xfa1fbb3f0f1f}, - {.sector = 29, .key_a = 0x0be5fac8b06a, .key_b = 0x6f95887a4fd3}, - {.sector = 30, .key_a = 0x0eb23cc8110b, .key_b = 0x04dc35277635}, - {.sector = 31, .key_a = 0xbc4580b7f20b, .key_b = 0xd0a4131fb290}, - {.sector = 32, .key_a = 0x7a396f0d633d, .key_b = 0xad2bdc097023}, - {.sector = 33, .key_a = 0xa3faa6daff67, .key_b = 0x7600e889adf9}, - {.sector = 34, .key_a = 0xfd8705e721b0, .key_b = 0x296fc317a513}, - {.sector = 35, .key_a = 0x22052b480d11, .key_b = 0xe19504c39461}, - {.sector = 36, .key_a = 0xa7141147d430, .key_b = 0xff16014fefc7}, - {.sector = 37, .key_a = 0x8a8d88151a00, .key_b = 0x038b5f9b5a2a}, - {.sector = 38, .key_a = 0xb27addfb64b0, .key_b = 0x152fd0c420a7}, - {.sector = 39, .key_a = 0x7259fa0197c6, .key_b = 0x5583698df085}, -}; - -bool plantain_4k_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - UNUSED(nfc_worker); - - if(nfc_worker->dev_data->mf_classic_data.type != MfClassicType4k) { - return false; - } - - uint8_t sector = 8; - uint8_t block = mf_classic_get_sector_trailer_block_num_by_sector(sector); - FURI_LOG_D("Plant4K", "Verifying sector %d", sector); - if(mf_classic_authenticate(tx_rx, block, 0x26973ea74321, MfClassicKeyA)) { - FURI_LOG_D("Plant4K", "Sector %d verified", sector); - return true; - } - return false; -} - -bool plantain_4k_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - - MfClassicReader reader = {}; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - reader.type = mf_classic_get_classic_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak); - for(size_t i = 0; i < COUNT_OF(plantain_keys_4k); i++) { - mf_classic_reader_add_sector( - &reader, - plantain_keys_4k[i].sector, - plantain_keys_4k[i].key_a, - plantain_keys_4k[i].key_b); - FURI_LOG_T("plant4k", "Added sector %d", plantain_keys_4k[i].sector); - } - for(int i = 0; i < 5; i++) { - if(mf_classic_read_card(tx_rx, &reader, &nfc_worker->dev_data->mf_classic_data) == 40) { - return true; - } - } - return false; -} - -bool plantain_4k_parser_parse(NfcDeviceData* dev_data) { - MfClassicData* data = &dev_data->mf_classic_data; - - // Verify key - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, 8); - uint64_t key = nfc_util_bytes2num(sec_tr->key_a, 6); - if(key != plantain_keys_4k[8].key_a) return false; - - // Point to block 0 of sector 4, value 0 - uint8_t* temp_ptr = &data->block[4 * 4].value[0]; - // Read first 4 bytes of block 0 of sector 4 from last to first and convert them to uint32_t - // 38 18 00 00 becomes 00 00 18 38, and equals to 6200 decimal - uint32_t balance = - ((temp_ptr[3] << 24) | (temp_ptr[2] << 16) | (temp_ptr[1] << 8) | temp_ptr[0]) / 100; - // Read card number - // Point to block 0 of sector 0, value 0 - temp_ptr = &data->block[0 * 4].value[0]; - // Read first 7 bytes of block 0 of sector 0 from last to first and convert them to uint64_t - // 04 31 16 8A 23 5C 80 becomes 80 5C 23 8A 16 31 04, and equals to 36130104729284868 decimal - uint8_t card_number_arr[7]; - for(size_t i = 0; i < 7; i++) { - card_number_arr[i] = temp_ptr[6 - i]; - } - // Copy card number to uint64_t - uint64_t card_number = 0; - for(size_t i = 0; i < 7; i++) { - card_number = (card_number << 8) | card_number_arr[i]; - } - - furi_string_printf( - dev_data->parsed_data, "\e#Plantain\nN:%llu-\nBalance:%lu\n", card_number, balance); - - return true; -} diff --git a/lib/nfc/parsers/plantain_4k_parser.h b/lib/nfc/parsers/plantain_4k_parser.h deleted file mode 100644 index 29998af15..000000000 --- a/lib/nfc/parsers/plantain_4k_parser.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "nfc_supported_card.h" - -bool plantain_4k_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool plantain_4k_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool plantain_4k_parser_parse(NfcDeviceData* dev_data); diff --git a/lib/nfc/parsers/plantain_parser.c b/lib/nfc/parsers/plantain_parser.c deleted file mode 100644 index 2e4091dda..000000000 --- a/lib/nfc/parsers/plantain_parser.c +++ /dev/null @@ -1,97 +0,0 @@ -#include "nfc_supported_card.h" - -#include -#include - -#include - -static const MfClassicAuthContext plantain_keys[] = { - {.sector = 0, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 1, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 2, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 3, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 4, .key_a = 0xe56ac127dd45, .key_b = 0x19fc84a3784b}, - {.sector = 5, .key_a = 0x77dabc9825e1, .key_b = 0x9764fec3154a}, - {.sector = 6, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 7, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 8, .key_a = 0x26973ea74321, .key_b = 0xd27058c6e2c7}, - {.sector = 9, .key_a = 0xeb0a8ff88ade, .key_b = 0x578a9ada41e3}, - {.sector = 10, .key_a = 0xea0fd73cb149, .key_b = 0x29c35fa068fb}, - {.sector = 11, .key_a = 0xc76bf71a2509, .key_b = 0x9ba241db3f56}, - {.sector = 12, .key_a = 0xacffffffffff, .key_b = 0x71f3a315ad26}, - {.sector = 13, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 14, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 15, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, -}; - -bool plantain_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - UNUSED(nfc_worker); - if(nfc_worker->dev_data->mf_classic_data.type != MfClassicType1k) { - return false; - } - - uint8_t sector = 8; - uint8_t block = mf_classic_get_sector_trailer_block_num_by_sector(sector); - FURI_LOG_D("Plant", "Verifying sector %d", sector); - if(mf_classic_authenticate(tx_rx, block, 0x26973ea74321, MfClassicKeyA)) { - FURI_LOG_D("Plant", "Sector %d verified", sector); - return true; - } - return false; -} - -bool plantain_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - - MfClassicReader reader = {}; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - reader.type = mf_classic_get_classic_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak); - for(size_t i = 0; i < COUNT_OF(plantain_keys); i++) { - mf_classic_reader_add_sector( - &reader, plantain_keys[i].sector, plantain_keys[i].key_a, plantain_keys[i].key_b); - } - - return mf_classic_read_card(tx_rx, &reader, &nfc_worker->dev_data->mf_classic_data) == 16; -} - -uint8_t plantain_calculate_luhn(uint64_t number) { - // No. - UNUSED(number); - return 0; -} - -bool plantain_parser_parse(NfcDeviceData* dev_data) { - MfClassicData* data = &dev_data->mf_classic_data; - - // Verify key - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, 8); - uint64_t key = nfc_util_bytes2num(sec_tr->key_a, 6); - if(key != plantain_keys[8].key_a) return false; - - // Point to block 0 of sector 4, value 0 - uint8_t* temp_ptr = &data->block[4 * 4].value[0]; - // Read first 4 bytes of block 0 of sector 4 from last to first and convert them to uint32_t - // 38 18 00 00 becomes 00 00 18 38, and equals to 6200 decimal - uint32_t balance = - ((temp_ptr[3] << 24) | (temp_ptr[2] << 16) | (temp_ptr[1] << 8) | temp_ptr[0]) / 100; - // Read card number - // Point to block 0 of sector 0, value 0 - temp_ptr = &data->block[0 * 4].value[0]; - // Read first 7 bytes of block 0 of sector 0 from last to first and convert them to uint64_t - // 04 31 16 8A 23 5C 80 becomes 80 5C 23 8A 16 31 04, and equals to 36130104729284868 decimal - uint8_t card_number_arr[7]; - for(size_t i = 0; i < 7; i++) { - card_number_arr[i] = temp_ptr[6 - i]; - } - // Copy card number to uint64_t - uint64_t card_number = 0; - for(size_t i = 0; i < 7; i++) { - card_number = (card_number << 8) | card_number_arr[i]; - } - - furi_string_printf( - dev_data->parsed_data, "\e#Plantain\nN:%llu-\nBalance:%lu\n", card_number, balance); - - return true; -} diff --git a/lib/nfc/parsers/plantain_parser.h b/lib/nfc/parsers/plantain_parser.h deleted file mode 100644 index 1af8c5065..000000000 --- a/lib/nfc/parsers/plantain_parser.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "nfc_supported_card.h" - -bool plantain_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool plantain_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool plantain_parser_parse(NfcDeviceData* dev_data); - -uint8_t plantain_calculate_luhn(uint64_t number); diff --git a/lib/nfc/parsers/troika_4k_parser.c b/lib/nfc/parsers/troika_4k_parser.c deleted file mode 100644 index d248feb17..000000000 --- a/lib/nfc/parsers/troika_4k_parser.c +++ /dev/null @@ -1,106 +0,0 @@ -#include "nfc_supported_card.h" - -#include -#include - -static const MfClassicAuthContext troika_4k_keys[] = { - {.sector = 0, .key_a = 0xa0a1a2a3a4a5, .key_b = 0xfbf225dc5d58}, - {.sector = 1, .key_a = 0xa82607b01c0d, .key_b = 0x2910989b6880}, - {.sector = 2, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 3, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 4, .key_a = 0x73068f118c13, .key_b = 0x2b7f3253fac5}, - {.sector = 5, .key_a = 0xFBC2793D540B, .key_b = 0xd3a297dc2698}, - {.sector = 6, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 7, .key_a = 0xae3d65a3dad4, .key_b = 0x0f1c63013dbb}, - {.sector = 8, .key_a = 0xa73f5dc1d333, .key_b = 0xe35173494a81}, - {.sector = 9, .key_a = 0x69a32f1c2f19, .key_b = 0x6b8bd9860763}, - {.sector = 10, .key_a = 0x9becdf3d9273, .key_b = 0xf8493407799d}, - {.sector = 11, .key_a = 0x08b386463229, .key_b = 0x5efbaecef46b}, - {.sector = 12, .key_a = 0xcd4c61c26e3d, .key_b = 0x31c7610de3b0}, - {.sector = 13, .key_a = 0xa82607b01c0d, .key_b = 0x2910989b6880}, - {.sector = 14, .key_a = 0x0e8f64340ba4, .key_b = 0x4acec1205d75}, - {.sector = 15, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 16, .key_a = 0x6b02733bb6ec, .key_b = 0x7038cd25c408}, - {.sector = 17, .key_a = 0x403d706ba880, .key_b = 0xb39d19a280df}, - {.sector = 18, .key_a = 0xc11f4597efb5, .key_b = 0x70d901648cb9}, - {.sector = 19, .key_a = 0x0db520c78c1c, .key_b = 0x73e5b9d9d3a4}, - {.sector = 20, .key_a = 0x3ebce0925b2f, .key_b = 0x372cc880f216}, - {.sector = 21, .key_a = 0x16a27af45407, .key_b = 0x9868925175ba}, - {.sector = 22, .key_a = 0xaba208516740, .key_b = 0xce26ecb95252}, - {.sector = 23, .key_a = 0xCD64E567ABCD, .key_b = 0x8f79c4fd8a01}, - {.sector = 24, .key_a = 0x764cd061f1e6, .key_b = 0xa74332f74994}, - {.sector = 25, .key_a = 0x1cc219e9fec1, .key_b = 0xb90de525ceb6}, - {.sector = 26, .key_a = 0x2fe3cb83ea43, .key_b = 0xfba88f109b32}, - {.sector = 27, .key_a = 0x07894ffec1d6, .key_b = 0xefcb0e689db3}, - {.sector = 28, .key_a = 0x04c297b91308, .key_b = 0xc8454c154cb5}, - {.sector = 29, .key_a = 0x7a38e3511a38, .key_b = 0xab16584c972a}, - {.sector = 30, .key_a = 0x7545df809202, .key_b = 0xecf751084a80}, - {.sector = 31, .key_a = 0x5125974cd391, .key_b = 0xd3eafb5df46d}, - {.sector = 32, .key_a = 0x7a86aa203788, .key_b = 0xe41242278ca2}, - {.sector = 33, .key_a = 0xafcef64c9913, .key_b = 0x9db96dca4324}, - {.sector = 34, .key_a = 0x04eaa462f70b, .key_b = 0xac17b93e2fae}, - {.sector = 35, .key_a = 0xe734c210f27e, .key_b = 0x29ba8c3e9fda}, - {.sector = 36, .key_a = 0xd5524f591eed, .key_b = 0x5daf42861b4d}, - {.sector = 37, .key_a = 0xe4821a377b75, .key_b = 0xe8709e486465}, - {.sector = 38, .key_a = 0x518dc6eea089, .key_b = 0x97c64ac98ca4}, - {.sector = 39, .key_a = 0xbb52f8cce07f, .key_b = 0x6b6119752c70}, -}; - -bool troika_4k_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - - if(nfc_worker->dev_data->mf_classic_data.type != MfClassicType4k) { - return false; - } - - uint8_t sector = 11; - uint8_t block = mf_classic_get_sector_trailer_block_num_by_sector(sector); - FURI_LOG_D("Troika", "Verifying sector %d", sector); - if(mf_classic_authenticate(tx_rx, block, 0x08b386463229, MfClassicKeyA)) { - FURI_LOG_D("Troika", "Sector %d verified", sector); - return true; - } - return false; -} - -bool troika_4k_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - - MfClassicReader reader = {}; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - reader.type = mf_classic_get_classic_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak); - for(size_t i = 0; i < COUNT_OF(troika_4k_keys); i++) { - mf_classic_reader_add_sector( - &reader, troika_4k_keys[i].sector, troika_4k_keys[i].key_a, troika_4k_keys[i].key_b); - } - - return mf_classic_read_card(tx_rx, &reader, &nfc_worker->dev_data->mf_classic_data) == 40; -} - -bool troika_4k_parser_parse(NfcDeviceData* dev_data) { - MfClassicData* data = &dev_data->mf_classic_data; - - // Verify key - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, 4); - uint64_t key = nfc_util_bytes2num(sec_tr->key_a, 6); - if(key != troika_4k_keys[4].key_a) return false; - - // Verify card type - if(data->type != MfClassicType4k) return false; - - uint8_t* temp_ptr = &data->block[8 * 4 + 1].value[5]; - uint16_t balance = ((temp_ptr[0] << 8) | temp_ptr[1]) / 25; - temp_ptr = &data->block[8 * 4].value[2]; - uint32_t number = 0; - for(size_t i = 1; i < 5; i++) { - number <<= 8; - number |= temp_ptr[i]; - } - number >>= 4; - number |= (temp_ptr[0] & 0xf) << 28; - - furi_string_printf( - dev_data->parsed_data, "\e#Troika\nNum: %lu\nBalance: %u rur.", number, balance); - - return true; -} diff --git a/lib/nfc/parsers/troika_4k_parser.h b/lib/nfc/parsers/troika_4k_parser.h deleted file mode 100644 index c1d6f01d3..000000000 --- a/lib/nfc/parsers/troika_4k_parser.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "nfc_supported_card.h" - -bool troika_4k_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool troika_4k_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool troika_4k_parser_parse(NfcDeviceData* dev_data); diff --git a/lib/nfc/parsers/troika_parser.c b/lib/nfc/parsers/troika_parser.c deleted file mode 100644 index 6d8ae98f3..000000000 --- a/lib/nfc/parsers/troika_parser.c +++ /dev/null @@ -1,88 +0,0 @@ -#include "nfc_supported_card.h" - -#include -#include - -static const MfClassicAuthContext troika_keys[] = { - {.sector = 0, .key_a = 0xa0a1a2a3a4a5, .key_b = 0xfbf225dc5d58}, - {.sector = 1, .key_a = 0xa82607b01c0d, .key_b = 0x2910989b6880}, - {.sector = 2, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 3, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 4, .key_a = 0x73068f118c13, .key_b = 0x2b7f3253fac5}, - {.sector = 5, .key_a = 0xfbc2793d540b, .key_b = 0xd3a297dc2698}, - {.sector = 6, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 7, .key_a = 0xae3d65a3dad4, .key_b = 0x0f1c63013dba}, - {.sector = 8, .key_a = 0xa73f5dc1d333, .key_b = 0xe35173494a81}, - {.sector = 9, .key_a = 0x69a32f1c2f19, .key_b = 0x6b8bd9860763}, - {.sector = 10, .key_a = 0x9becdf3d9273, .key_b = 0xf8493407799d}, - {.sector = 11, .key_a = 0x08b386463229, .key_b = 0x5efbaecef46b}, - {.sector = 12, .key_a = 0xcd4c61c26e3d, .key_b = 0x31c7610de3b0}, - {.sector = 13, .key_a = 0xa82607b01c0d, .key_b = 0x2910989b6880}, - {.sector = 14, .key_a = 0x0e8f64340ba4, .key_b = 0x4acec1205d75}, - {.sector = 15, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, -}; - -bool troika_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - UNUSED(nfc_worker); - if(nfc_worker->dev_data->mf_classic_data.type != MfClassicType1k) { - return false; - } - - uint8_t sector = 11; - uint8_t block = mf_classic_get_sector_trailer_block_num_by_sector(sector); - FURI_LOG_D("Troika", "Verifying sector %d", sector); - if(mf_classic_authenticate(tx_rx, block, 0x08b386463229, MfClassicKeyA)) { - FURI_LOG_D("Troika", "Sector %d verified", sector); - return true; - } - return false; -} - -bool troika_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - - MfClassicReader reader = {}; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - reader.type = mf_classic_get_classic_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak); - - for(size_t i = 0; i < COUNT_OF(troika_keys); i++) { - mf_classic_reader_add_sector( - &reader, troika_keys[i].sector, troika_keys[i].key_a, troika_keys[i].key_b); - } - - return mf_classic_read_card(tx_rx, &reader, &nfc_worker->dev_data->mf_classic_data) == 16; -} - -bool troika_parser_parse(NfcDeviceData* dev_data) { - MfClassicData* data = &dev_data->mf_classic_data; - bool troika_parsed = false; - - do { - // Verify key - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, 8); - uint64_t key = nfc_util_bytes2num(sec_tr->key_a, 6); - if(key != troika_keys[8].key_a) break; - - // Verify card type - if(data->type != MfClassicType1k) break; - - // Parse data - uint8_t* temp_ptr = &data->block[8 * 4 + 1].value[5]; - uint16_t balance = ((temp_ptr[0] << 8) | temp_ptr[1]) / 25; - temp_ptr = &data->block[8 * 4].value[2]; - uint32_t number = 0; - for(size_t i = 1; i < 5; i++) { - number <<= 8; - number |= temp_ptr[i]; - } - number >>= 4; - number |= (temp_ptr[0] & 0xf) << 28; - - furi_string_printf( - dev_data->parsed_data, "\e#Troika\nNum: %lu\nBalance: %u rur.", number, balance); - troika_parsed = true; - } while(false); - - return troika_parsed; -} diff --git a/lib/nfc/parsers/troika_parser.h b/lib/nfc/parsers/troika_parser.h deleted file mode 100644 index 2aae48d29..000000000 --- a/lib/nfc/parsers/troika_parser.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "nfc_supported_card.h" - -bool troika_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool troika_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool troika_parser_parse(NfcDeviceData* dev_data); diff --git a/lib/nfc/parsers/two_cities.c b/lib/nfc/parsers/two_cities.c deleted file mode 100644 index d6d4279dd..000000000 --- a/lib/nfc/parsers/two_cities.c +++ /dev/null @@ -1,146 +0,0 @@ -#include "nfc_supported_card.h" -#include "plantain_parser.h" // For plantain-specific stuff - -#include -#include - -#include - -static const MfClassicAuthContext two_cities_keys_4k[] = { - {.sector = 0, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 1, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 2, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 3, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 4, .key_a = 0xe56ac127dd45, .key_b = 0x19fc84a3784b}, - {.sector = 5, .key_a = 0x77dabc9825e1, .key_b = 0x9764fec3154a}, - {.sector = 6, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 7, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 8, .key_a = 0xa73f5dc1d333, .key_b = 0xe35173494a81}, - {.sector = 9, .key_a = 0x69a32f1c2f19, .key_b = 0x6b8bd9860763}, - {.sector = 10, .key_a = 0xea0fd73cb149, .key_b = 0x29c35fa068fb}, - {.sector = 11, .key_a = 0xc76bf71a2509, .key_b = 0x9ba241db3f56}, - {.sector = 12, .key_a = 0xacffffffffff, .key_b = 0x71f3a315ad26}, - {.sector = 13, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 14, .key_a = 0xffffffffffff, .key_b = 0xffffffffffff}, - {.sector = 15, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 16, .key_a = 0x72f96bdd3714, .key_b = 0x462225cd34cf}, - {.sector = 17, .key_a = 0x044ce1872bc3, .key_b = 0x8c90c70cff4a}, - {.sector = 18, .key_a = 0xbc2d1791dec1, .key_b = 0xca96a487de0b}, - {.sector = 19, .key_a = 0x8791b2ccb5c4, .key_b = 0xc956c3b80da3}, - {.sector = 20, .key_a = 0x8e26e45e7d65, .key_b = 0x8e65b3af7d22}, - {.sector = 21, .key_a = 0x0f318130ed18, .key_b = 0x0c420a20e056}, - {.sector = 22, .key_a = 0x045ceca15535, .key_b = 0x31bec3d9e510}, - {.sector = 23, .key_a = 0x9d993c5d4ef4, .key_b = 0x86120e488abf}, - {.sector = 24, .key_a = 0xc65d4eaa645b, .key_b = 0xb69d40d1a439}, - {.sector = 25, .key_a = 0x3a8a139c20b4, .key_b = 0x8818a9c5d406}, - {.sector = 26, .key_a = 0xbaff3053b496, .key_b = 0x4b7cb25354d3}, - {.sector = 27, .key_a = 0x7413b599c4ea, .key_b = 0xb0a2AAF3A1BA}, - {.sector = 28, .key_a = 0x0ce7cd2cc72b, .key_b = 0xfa1fbb3f0f1f}, - {.sector = 29, .key_a = 0x0be5fac8b06a, .key_b = 0x6f95887a4fd3}, - {.sector = 30, .key_a = 0x26973ea74321, .key_b = 0xd27058c6e2c7}, - {.sector = 31, .key_a = 0xeb0a8ff88ade, .key_b = 0x578a9ada41e3}, - {.sector = 32, .key_a = 0x7a396f0d633d, .key_b = 0xad2bdc097023}, - {.sector = 33, .key_a = 0xa3faa6daff67, .key_b = 0x7600e889adf9}, - {.sector = 34, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 35, .key_a = 0x2aa05ed1856f, .key_b = 0xeaac88e5dc99}, - {.sector = 36, .key_a = 0xa7141147d430, .key_b = 0xff16014fefc7}, - {.sector = 37, .key_a = 0x8a8d88151a00, .key_b = 0x038b5f9b5a2a}, - {.sector = 38, .key_a = 0xb27addfb64b0, .key_b = 0x152fd0c420a7}, - {.sector = 39, .key_a = 0x7259fa0197c6, .key_b = 0x5583698df085}, -}; - -bool two_cities_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - UNUSED(nfc_worker); - - if(nfc_worker->dev_data->mf_classic_data.type != MfClassicType4k) { - return false; - } - - uint8_t sector = 4; - uint8_t block = mf_classic_get_sector_trailer_block_num_by_sector(sector); - FURI_LOG_D("2cities", "Verifying sector %d", sector); - if(mf_classic_authenticate(tx_rx, block, 0xe56ac127dd45, MfClassicKeyA)) { - FURI_LOG_D("2cities", "Sector %d verified", sector); - return true; - } - return false; -} - -bool two_cities_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx) { - furi_assert(nfc_worker); - - MfClassicReader reader = {}; - FuriHalNfcDevData* nfc_data = &nfc_worker->dev_data->nfc_data; - reader.type = mf_classic_get_classic_type(nfc_data->atqa[0], nfc_data->atqa[1], nfc_data->sak); - for(size_t i = 0; i < COUNT_OF(two_cities_keys_4k); i++) { - mf_classic_reader_add_sector( - &reader, - two_cities_keys_4k[i].sector, - two_cities_keys_4k[i].key_a, - two_cities_keys_4k[i].key_b); - FURI_LOG_T("2cities", "Added sector %d", two_cities_keys_4k[i].sector); - } - - return mf_classic_read_card(tx_rx, &reader, &nfc_worker->dev_data->mf_classic_data) == 40; -} - -bool two_cities_parser_parse(NfcDeviceData* dev_data) { - MfClassicData* data = &dev_data->mf_classic_data; - - // Verify key - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, 4); - uint64_t key = nfc_util_bytes2num(sec_tr->key_a, 6); - if(key != two_cities_keys_4k[4].key_a) return false; - - // ===== - // PLANTAIN - // ===== - - // Point to block 0 of sector 4, value 0 - uint8_t* temp_ptr = &data->block[4 * 4].value[0]; - // Read first 4 bytes of block 0 of sector 4 from last to first and convert them to uint32_t - // 38 18 00 00 becomes 00 00 18 38, and equals to 6200 decimal - uint32_t balance = - ((temp_ptr[3] << 24) | (temp_ptr[2] << 16) | (temp_ptr[1] << 8) | temp_ptr[0]) / 100; - // Read card number - // Point to block 0 of sector 0, value 0 - temp_ptr = &data->block[0 * 4].value[0]; - // Read first 7 bytes of block 0 of sector 0 from last to first and convert them to uint64_t - // 04 31 16 8A 23 5C 80 becomes 80 5C 23 8A 16 31 04, and equals to 36130104729284868 decimal - uint8_t card_number_arr[7]; - for(size_t i = 0; i < 7; i++) { - card_number_arr[i] = temp_ptr[6 - i]; - } - // Copy card number to uint64_t - uint64_t card_number = 0; - for(size_t i = 0; i < 7; i++) { - card_number = (card_number << 8) | card_number_arr[i]; - } - - // ===== - // --PLANTAIN-- - // ===== - // TROIKA - // ===== - - uint8_t* troika_temp_ptr = &data->block[8 * 4 + 1].value[5]; - uint16_t troika_balance = ((troika_temp_ptr[0] << 8) | troika_temp_ptr[1]) / 25; - troika_temp_ptr = &data->block[8 * 4].value[3]; - uint32_t troika_number = 0; - for(size_t i = 0; i < 4; i++) { - troika_number <<= 8; - troika_number |= troika_temp_ptr[i]; - } - troika_number >>= 4; - - furi_string_printf( - dev_data->parsed_data, - "\e#Troika+Plantain\nPN: %llu-\nPB: %lu rur.\nTN: %lu\nTB: %u rur.\n", - card_number, - balance, - troika_number, - troika_balance); - - return true; -} diff --git a/lib/nfc/parsers/two_cities.h b/lib/nfc/parsers/two_cities.h deleted file mode 100644 index e735bea8e..000000000 --- a/lib/nfc/parsers/two_cities.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include "nfc_supported_card.h" - -bool two_cities_parser_verify(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool two_cities_parser_read(NfcWorker* nfc_worker, FuriHalNfcTxRxContext* tx_rx); - -bool two_cities_parser_parse(NfcDeviceData* dev_data); diff --git a/lib/nfc/protocols/crypto1.c b/lib/nfc/protocols/crypto1.c deleted file mode 100644 index f59651cf4..000000000 --- a/lib/nfc/protocols/crypto1.c +++ /dev/null @@ -1,128 +0,0 @@ -#include "crypto1.h" -#include "nfc_util.h" -#include - -// Algorithm from https://github.com/RfidResearchGroup/proxmark3.git - -#define SWAPENDIAN(x) \ - ((x) = ((x) >> 8 & 0xff00ff) | ((x)&0xff00ff) << 8, (x) = (x) >> 16 | (x) << 16) -#define LF_POLY_ODD (0x29CE5C) -#define LF_POLY_EVEN (0x870804) - -#define BEBIT(x, n) FURI_BIT(x, (n) ^ 24) - -void crypto1_reset(Crypto1* crypto1) { - furi_assert(crypto1); - crypto1->even = 0; - crypto1->odd = 0; -} - -void crypto1_init(Crypto1* crypto1, uint64_t key) { - furi_assert(crypto1); - crypto1->even = 0; - crypto1->odd = 0; - for(int8_t i = 47; i > 0; i -= 2) { - crypto1->odd = crypto1->odd << 1 | FURI_BIT(key, (i - 1) ^ 7); - crypto1->even = crypto1->even << 1 | FURI_BIT(key, i ^ 7); - } -} - -uint32_t crypto1_filter(uint32_t in) { - uint32_t out = 0; - out = 0xf22c0 >> (in & 0xf) & 16; - out |= 0x6c9c0 >> (in >> 4 & 0xf) & 8; - out |= 0x3c8b0 >> (in >> 8 & 0xf) & 4; - out |= 0x1e458 >> (in >> 12 & 0xf) & 2; - out |= 0x0d938 >> (in >> 16 & 0xf) & 1; - return FURI_BIT(0xEC57E80A, out); -} - -uint8_t crypto1_bit(Crypto1* crypto1, uint8_t in, int is_encrypted) { - furi_assert(crypto1); - uint8_t out = crypto1_filter(crypto1->odd); - uint32_t feed = out & (!!is_encrypted); - feed ^= !!in; - feed ^= LF_POLY_ODD & crypto1->odd; - feed ^= LF_POLY_EVEN & crypto1->even; - crypto1->even = crypto1->even << 1 | (nfc_util_even_parity32(feed)); - - FURI_SWAP(crypto1->odd, crypto1->even); - return out; -} - -uint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted) { - furi_assert(crypto1); - uint8_t out = 0; - for(uint8_t i = 0; i < 8; i++) { - out |= crypto1_bit(crypto1, FURI_BIT(in, i), is_encrypted) << i; - } - return out; -} - -uint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted) { - furi_assert(crypto1); - uint32_t out = 0; - for(uint8_t i = 0; i < 32; i++) { - out |= crypto1_bit(crypto1, BEBIT(in, i), is_encrypted) << (24 ^ i); - } - return out; -} - -uint32_t prng_successor(uint32_t x, uint32_t n) { - SWAPENDIAN(x); - while(n--) x = x >> 1 | (x >> 16 ^ x >> 18 ^ x >> 19 ^ x >> 21) << 31; - - return SWAPENDIAN(x); -} - -void crypto1_decrypt( - Crypto1* crypto, - uint8_t* encrypted_data, - uint16_t encrypted_data_bits, - uint8_t* decrypted_data) { - furi_assert(crypto); - furi_assert(encrypted_data); - furi_assert(decrypted_data); - - if(encrypted_data_bits < 8) { - uint8_t decrypted_byte = 0; - decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 0)) << 0; - decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 1)) << 1; - decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 2)) << 2; - decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 3)) << 3; - decrypted_data[0] = decrypted_byte; - } else { - for(size_t i = 0; i < encrypted_data_bits / 8; i++) { - decrypted_data[i] = crypto1_byte(crypto, 0, 0) ^ encrypted_data[i]; - } - } -} - -void crypto1_encrypt( - Crypto1* crypto, - uint8_t* keystream, - uint8_t* plain_data, - uint16_t plain_data_bits, - uint8_t* encrypted_data, - uint8_t* encrypted_parity) { - furi_assert(crypto); - furi_assert(plain_data); - furi_assert(encrypted_data); - furi_assert(encrypted_parity); - - if(plain_data_bits < 8) { - encrypted_data[0] = 0; - for(size_t i = 0; i < plain_data_bits; i++) { - encrypted_data[0] |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(plain_data[0], i)) << i; - } - } else { - memset(encrypted_parity, 0, plain_data_bits / 8 + 1); - for(uint8_t i = 0; i < plain_data_bits / 8; i++) { - encrypted_data[i] = crypto1_byte(crypto, keystream ? keystream[i] : 0, 0) ^ - plain_data[i]; - encrypted_parity[i / 8] |= - (((crypto1_filter(crypto->odd) ^ nfc_util_odd_parity8(plain_data[i])) & 0x01) - << (7 - (i & 0x0007))); - } - } -} diff --git a/lib/nfc/protocols/emv.c b/lib/nfc/protocols/emv.c deleted file mode 100644 index 4c4ac856b..000000000 --- a/lib/nfc/protocols/emv.c +++ /dev/null @@ -1,444 +0,0 @@ -#include "emv.h" - -#include - -#define TAG "Emv" - -const PDOLValue pdol_term_info = {0x9F59, {0xC8, 0x80, 0x00}}; // Terminal transaction information -const PDOLValue pdol_term_type = {0x9F5A, {0x00}}; // Terminal transaction type -const PDOLValue pdol_merchant_type = {0x9F58, {0x01}}; // Merchant type indicator -const PDOLValue pdol_term_trans_qualifies = { - 0x9F66, - {0x79, 0x00, 0x40, 0x80}}; // Terminal transaction qualifiers -const PDOLValue pdol_addtnl_term_qualifies = { - 0x9F40, - {0x79, 0x00, 0x40, 0x80}}; // Terminal transaction qualifiers -const PDOLValue pdol_amount_authorise = { - 0x9F02, - {0x00, 0x00, 0x00, 0x10, 0x00, 0x00}}; // Amount, authorised -const PDOLValue pdol_amount = {0x9F03, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; // Amount -const PDOLValue pdol_country_code = {0x9F1A, {0x01, 0x24}}; // Terminal country code -const PDOLValue pdol_currency_code = {0x5F2A, {0x01, 0x24}}; // Transaction currency code -const PDOLValue pdol_term_verification = { - 0x95, - {0x00, 0x00, 0x00, 0x00, 0x00}}; // Terminal verification results -const PDOLValue pdol_transaction_date = {0x9A, {0x19, 0x01, 0x01}}; // Transaction date -const PDOLValue pdol_transaction_type = {0x9C, {0x00}}; // Transaction type -const PDOLValue pdol_transaction_cert = {0x98, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}; // Transaction cert -const PDOLValue pdol_unpredict_number = {0x9F37, {0x82, 0x3D, 0xDE, 0x7A}}; // Unpredictable number - -const PDOLValue* const pdol_values[] = { - &pdol_term_info, - &pdol_term_type, - &pdol_merchant_type, - &pdol_term_trans_qualifies, - &pdol_addtnl_term_qualifies, - &pdol_amount_authorise, - &pdol_amount, - &pdol_country_code, - &pdol_currency_code, - &pdol_term_verification, - &pdol_transaction_date, - &pdol_transaction_type, - &pdol_transaction_cert, - &pdol_unpredict_number, -}; - -static const uint8_t select_ppse_ans[] = {0x6F, 0x29, 0x84, 0x0E, 0x32, 0x50, 0x41, 0x59, 0x2E, - 0x53, 0x59, 0x53, 0x2E, 0x44, 0x44, 0x46, 0x30, 0x31, - 0xA5, 0x17, 0xBF, 0x0C, 0x14, 0x61, 0x12, 0x4F, 0x07, - 0xA0, 0x00, 0x00, 0x00, 0x03, 0x10, 0x10, 0x50, 0x04, - 0x56, 0x49, 0x53, 0x41, 0x87, 0x01, 0x01, 0x90, 0x00}; -static const uint8_t select_app_ans[] = {0x6F, 0x20, 0x84, 0x07, 0xA0, 0x00, 0x00, 0x00, 0x03, - 0x10, 0x10, 0xA5, 0x15, 0x50, 0x04, 0x56, 0x49, 0x53, - 0x41, 0x9F, 0x38, 0x0C, 0x9F, 0x66, 0x04, 0x9F, 0x02, - 0x06, 0x9F, 0x37, 0x04, 0x5F, 0x2A, 0x02, 0x90, 0x00}; -static const uint8_t pdol_ans[] = {0x77, 0x40, 0x82, 0x02, 0x20, 0x00, 0x57, 0x13, 0x55, 0x70, - 0x73, 0x83, 0x85, 0x87, 0x73, 0x31, 0xD1, 0x80, 0x22, 0x01, - 0x38, 0x84, 0x77, 0x94, 0x00, 0x00, 0x1F, 0x5F, 0x34, 0x01, - 0x00, 0x9F, 0x10, 0x07, 0x06, 0x01, 0x11, 0x03, 0x80, 0x00, - 0x00, 0x9F, 0x26, 0x08, 0x7A, 0x65, 0x7F, 0xD3, 0x52, 0x96, - 0xC9, 0x85, 0x9F, 0x27, 0x01, 0x00, 0x9F, 0x36, 0x02, 0x06, - 0x0C, 0x9F, 0x6C, 0x02, 0x10, 0x00, 0x90, 0x00}; - -static void emv_trace(FuriHalNfcTxRxContext* tx_rx, const char* message) { - if(furi_log_get_level() == FuriLogLevelTrace) { - FURI_LOG_T(TAG, "%s", message); - printf("TX: "); - for(size_t i = 0; i < tx_rx->tx_bits / 8; i++) { - printf("%02X ", tx_rx->tx_data[i]); - } - printf("\r\nRX: "); - for(size_t i = 0; i < tx_rx->rx_bits / 8; i++) { - printf("%02X ", tx_rx->rx_data[i]); - } - printf("\r\n"); - } -} - -static bool emv_decode_response(uint8_t* buff, uint16_t len, EmvApplication* app) { - uint16_t i = 0; - uint16_t tag = 0, first_byte = 0; - uint16_t tlen = 0; - bool success = false; - - while(i < len) { - first_byte = buff[i]; - if((first_byte & 31) == 31) { // 2-byte tag - tag = buff[i] << 8 | buff[i + 1]; - i++; - FURI_LOG_T(TAG, " 2-byte TLV EMV tag: %x", tag); - } else { - tag = buff[i]; - FURI_LOG_T(TAG, " 1-byte TLV EMV tag: %x", tag); - } - i++; - tlen = buff[i]; - if((tlen & 128) == 128) { // long length value - i++; - tlen = buff[i]; - FURI_LOG_T(TAG, " 2-byte TLV length: %d", tlen); - } else { - FURI_LOG_T(TAG, " 1-byte TLV length: %d", tlen); - } - i++; - if((first_byte & 32) == 32) { // "Constructed" -- contains more TLV data to parse - FURI_LOG_T(TAG, "Constructed TLV %x", tag); - if(!emv_decode_response(&buff[i], tlen, app)) { - FURI_LOG_T(TAG, "Failed to decode response for %x", tag); - // return false; - } else { - success = true; - } - } else { - switch(tag) { - case EMV_TAG_AID: - app->aid_len = tlen; - memcpy(app->aid, &buff[i], tlen); - success = true; - FURI_LOG_T(TAG, "found EMV_TAG_AID %x", tag); - break; - case EMV_TAG_PRIORITY: - memcpy(&app->priority, &buff[i], tlen); - success = true; - break; - case EMV_TAG_CARD_NAME: - memcpy(app->name, &buff[i], tlen); - app->name[tlen] = '\0'; - app->name_found = true; - success = true; - FURI_LOG_T(TAG, "found EMV_TAG_CARD_NAME %x : %s", tag, app->name); - break; - case EMV_TAG_PDOL: - memcpy(app->pdol.data, &buff[i], tlen); - app->pdol.size = tlen; - success = true; - FURI_LOG_T(TAG, "found EMV_TAG_PDOL %x (len=%d)", tag, tlen); - break; - case EMV_TAG_AFL: - memcpy(app->afl.data, &buff[i], tlen); - app->afl.size = tlen; - success = true; - FURI_LOG_T(TAG, "found EMV_TAG_AFL %x (len=%d)", tag, tlen); - break; - case EMV_TAG_TRACK_1_EQUIV: { - char track_1_equiv[80]; - memcpy(track_1_equiv, &buff[i], tlen); - track_1_equiv[tlen] = '\0'; - success = true; - FURI_LOG_T(TAG, "found EMV_TAG_TRACK_1_EQUIV %x : %s", tag, track_1_equiv); - break; - } - case EMV_TAG_TRACK_2_EQUIV: { - // 0xD0 delimits PAN from expiry (YYMM) - for(int x = 1; x < tlen; x++) { - if(buff[i + x + 1] > 0xD0) { - memcpy(app->card_number, &buff[i], x + 1); - app->card_number_len = x + 1; - app->exp_year = (buff[i + x + 1] << 4) | (buff[i + x + 2] >> 4); - app->exp_month = (buff[i + x + 2] << 4) | (buff[i + x + 3] >> 4); - break; - } - } - - // Convert 4-bit to ASCII representation - char track_2_equiv[41]; - uint8_t track_2_equiv_len = 0; - for(int x = 0; x < tlen; x++) { - char top = (buff[i + x] >> 4) + '0'; - char bottom = (buff[i + x] & 0x0F) + '0'; - track_2_equiv[x * 2] = top; - track_2_equiv_len++; - if(top == '?') break; - track_2_equiv[x * 2 + 1] = bottom; - track_2_equiv_len++; - if(bottom == '?') break; - } - track_2_equiv[track_2_equiv_len] = '\0'; - success = true; - FURI_LOG_T(TAG, "found EMV_TAG_TRACK_2_EQUIV %x : %s", tag, track_2_equiv); - break; - } - case EMV_TAG_PAN: - memcpy(app->card_number, &buff[i], tlen); - app->card_number_len = tlen; - success = true; - break; - case EMV_TAG_EXP_DATE: - app->exp_year = buff[i]; - app->exp_month = buff[i + 1]; - success = true; - break; - case EMV_TAG_CURRENCY_CODE: - app->currency_code = (buff[i] << 8 | buff[i + 1]); - success = true; - break; - case EMV_TAG_COUNTRY_CODE: - app->country_code = (buff[i] << 8 | buff[i + 1]); - success = true; - break; - } - } - i += tlen; - } - return success; -} - -static bool emv_select_ppse(FuriHalNfcTxRxContext* tx_rx, EmvApplication* app) { - bool app_aid_found = false; - const uint8_t emv_select_ppse_cmd[] = { - 0x00, 0xA4, // SELECT ppse - 0x04, 0x00, // P1:By name, P2: empty - 0x0e, // Lc: Data length - 0x32, 0x50, 0x41, 0x59, 0x2e, 0x53, 0x59, // Data string: - 0x53, 0x2e, 0x44, 0x44, 0x46, 0x30, 0x31, // 2PAY.SYS.DDF01 (PPSE) - 0x00 // Le - }; - - memcpy(tx_rx->tx_data, emv_select_ppse_cmd, sizeof(emv_select_ppse_cmd)); - tx_rx->tx_bits = sizeof(emv_select_ppse_cmd) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - - FURI_LOG_D(TAG, "Send select PPSE"); - if(furi_hal_nfc_tx_rx(tx_rx, 300)) { - emv_trace(tx_rx, "Select PPSE answer:"); - if(emv_decode_response(tx_rx->rx_data, tx_rx->rx_bits / 8, app)) { - app_aid_found = true; - } else { - FURI_LOG_E(TAG, "Failed to parse application"); - } - } else { - FURI_LOG_E(TAG, "Failed select PPSE"); - } - - return app_aid_found; -} - -static bool emv_select_app(FuriHalNfcTxRxContext* tx_rx, EmvApplication* app) { - app->app_started = false; - const uint8_t emv_select_header[] = { - 0x00, - 0xA4, // SELECT application - 0x04, - 0x00 // P1:By name, P2:First or only occurence - }; - uint16_t size = sizeof(emv_select_header); - - // Copy header - memcpy(tx_rx->tx_data, emv_select_header, size); - // Copy AID - tx_rx->tx_data[size++] = app->aid_len; - memcpy(&tx_rx->tx_data[size], app->aid, app->aid_len); - size += app->aid_len; - tx_rx->tx_data[size++] = 0x00; - tx_rx->tx_bits = size * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - - FURI_LOG_D(TAG, "Start application"); - if(furi_hal_nfc_tx_rx(tx_rx, 300)) { - emv_trace(tx_rx, "Start application answer:"); - if(emv_decode_response(tx_rx->rx_data, tx_rx->rx_bits / 8, app)) { - app->app_started = true; - } else { - FURI_LOG_E(TAG, "Failed to read PAN or PDOL"); - } - } else { - FURI_LOG_E(TAG, "Failed to start application"); - } - - return app->app_started; -} - -static uint16_t emv_prepare_pdol(APDU* dest, APDU* src) { - bool tag_found; - for(uint16_t i = 0; i < src->size; i++) { - tag_found = false; - for(uint8_t j = 0; j < sizeof(pdol_values) / sizeof(PDOLValue*); j++) { - if(src->data[i] == pdol_values[j]->tag) { - // Found tag with 1 byte length - uint8_t len = src->data[++i]; - memcpy(dest->data + dest->size, pdol_values[j]->data, len); - dest->size += len; - tag_found = true; - break; - } else if(((src->data[i] << 8) | src->data[i + 1]) == pdol_values[j]->tag) { - // Found tag with 2 byte length - i += 2; - uint8_t len = src->data[i]; - memcpy(dest->data + dest->size, pdol_values[j]->data, len); - dest->size += len; - tag_found = true; - break; - } - } - if(!tag_found) { - // Unknown tag, fill zeros - i += 2; - uint8_t len = src->data[i]; - memset(dest->data + dest->size, 0, len); - dest->size += len; - } - } - return dest->size; -} - -static bool emv_get_processing_options(FuriHalNfcTxRxContext* tx_rx, EmvApplication* app) { - bool card_num_read = false; - const uint8_t emv_gpo_header[] = {0x80, 0xA8, 0x00, 0x00}; - uint16_t size = sizeof(emv_gpo_header); - - // Copy header - memcpy(tx_rx->tx_data, emv_gpo_header, size); - APDU pdol_data = {0, {0}}; - // Prepare and copy pdol parameters - emv_prepare_pdol(&pdol_data, &app->pdol); - tx_rx->tx_data[size++] = 0x02 + pdol_data.size; - tx_rx->tx_data[size++] = 0x83; - tx_rx->tx_data[size++] = pdol_data.size; - memcpy(tx_rx->tx_data + size, pdol_data.data, pdol_data.size); - size += pdol_data.size; - tx_rx->tx_data[size++] = 0; - tx_rx->tx_bits = size * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - - FURI_LOG_D(TAG, "Get proccessing options"); - if(furi_hal_nfc_tx_rx(tx_rx, 300)) { - emv_trace(tx_rx, "Get processing options answer:"); - if(emv_decode_response(tx_rx->rx_data, tx_rx->rx_bits / 8, app)) { - if(app->card_number_len > 0) { - card_num_read = true; - } - } - } else { - FURI_LOG_E(TAG, "Failed to get processing options"); - } - - return card_num_read; -} - -static bool emv_read_sfi_record( - FuriHalNfcTxRxContext* tx_rx, - EmvApplication* app, - uint8_t sfi, - uint8_t record_num) { - bool card_num_read = false; - uint8_t sfi_param = (sfi << 3) | (1 << 2); - uint8_t emv_sfi_header[] = { - 0x00, - 0xB2, // READ RECORD - record_num, // P1:record_number - sfi_param, // P2:SFI - 0x00 // Le - }; - - memcpy(tx_rx->tx_data, emv_sfi_header, sizeof(emv_sfi_header)); - tx_rx->tx_bits = sizeof(emv_sfi_header) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - - if(furi_hal_nfc_tx_rx(tx_rx, 300)) { - emv_trace(tx_rx, "SFI record:"); - if(emv_decode_response(tx_rx->rx_data, tx_rx->rx_bits / 8, app)) { - card_num_read = true; - } - } else { - FURI_LOG_E(TAG, "Failed to read SFI record %d", record_num); - } - - return card_num_read; -} - -static bool emv_read_files(FuriHalNfcTxRxContext* tx_rx, EmvApplication* app) { - bool card_num_read = false; - - if(app->afl.size == 0) { - return false; - } - - FURI_LOG_D(TAG, "Search PAN in SFI"); - // Iterate through all files - for(size_t i = 0; i < app->afl.size; i += 4) { - uint8_t sfi = app->afl.data[i] >> 3; - uint8_t record_start = app->afl.data[i + 1]; - uint8_t record_end = app->afl.data[i + 2]; - // Iterate through all records in file - for(uint8_t record = record_start; record <= record_end; ++record) { - card_num_read |= emv_read_sfi_record(tx_rx, app, sfi, record); - } - } - - return card_num_read; -} - -bool emv_read_bank_card(FuriHalNfcTxRxContext* tx_rx, EmvApplication* emv_app) { - furi_assert(tx_rx); - furi_assert(emv_app); - bool card_num_read = false; - memset(emv_app, 0, sizeof(EmvApplication)); - - do { - if(!emv_select_ppse(tx_rx, emv_app)) break; - if(!emv_select_app(tx_rx, emv_app)) break; - if(emv_get_processing_options(tx_rx, emv_app)) { - card_num_read = true; - } else { - card_num_read = emv_read_files(tx_rx, emv_app); - } - } while(false); - - return card_num_read; -} - -bool emv_card_emulation(FuriHalNfcTxRxContext* tx_rx) { - furi_assert(tx_rx); - bool emulation_complete = false; - tx_rx->tx_bits = 0; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - - do { - FURI_LOG_D(TAG, "Read select PPSE command"); - if(!furi_hal_nfc_tx_rx(tx_rx, 300)) break; - - memcpy(tx_rx->tx_data, select_ppse_ans, sizeof(select_ppse_ans)); - tx_rx->tx_bits = sizeof(select_ppse_ans) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - FURI_LOG_D(TAG, "Send select PPSE answer and read select App command"); - if(!furi_hal_nfc_tx_rx(tx_rx, 300)) break; - - memcpy(tx_rx->tx_data, select_app_ans, sizeof(select_app_ans)); - tx_rx->tx_bits = sizeof(select_app_ans) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - FURI_LOG_D(TAG, "Send select App answer and read get PDOL command"); - if(!furi_hal_nfc_tx_rx(tx_rx, 300)) break; - - memcpy(tx_rx->tx_data, pdol_ans, sizeof(pdol_ans)); - tx_rx->tx_bits = sizeof(pdol_ans) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - FURI_LOG_D(TAG, "Send get PDOL answer"); - if(!furi_hal_nfc_tx_rx(tx_rx, 300)) break; - - emulation_complete = true; - } while(false); - - return emulation_complete; -} diff --git a/lib/nfc/protocols/emv.h b/lib/nfc/protocols/emv.h deleted file mode 100644 index c5b089fdf..000000000 --- a/lib/nfc/protocols/emv.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once - -#include - -#define MAX_APDU_LEN 255 - -#define EMV_TAG_APP_TEMPLATE 0x61 -#define EMV_TAG_AID 0x4F -#define EMV_TAG_PRIORITY 0x87 -#define EMV_TAG_PDOL 0x9F38 -#define EMV_TAG_CARD_NAME 0x50 -#define EMV_TAG_FCI 0xBF0C -#define EMV_TAG_LOG_CTRL 0x9F4D -#define EMV_TAG_TRACK_1_EQUIV 0x56 -#define EMV_TAG_TRACK_2_EQUIV 0x57 -#define EMV_TAG_PAN 0x5A -#define EMV_TAG_AFL 0x94 -#define EMV_TAG_EXP_DATE 0x5F24 -#define EMV_TAG_COUNTRY_CODE 0x5F28 -#define EMV_TAG_CURRENCY_CODE 0x9F42 -#define EMV_TAG_CARDHOLDER_NAME 0x5F20 - -typedef struct { - char name[32]; - uint8_t aid[16]; - uint16_t aid_len; - uint8_t number[10]; - uint8_t number_len; - uint8_t exp_mon; - uint8_t exp_year; - uint16_t country_code; - uint16_t currency_code; -} EmvData; - -typedef struct { - uint16_t tag; - uint8_t data[]; -} PDOLValue; - -typedef struct { - uint8_t size; - uint8_t data[MAX_APDU_LEN]; -} APDU; - -typedef struct { - uint8_t priority; - uint8_t aid[16]; - uint8_t aid_len; - bool app_started; - char name[32]; - bool name_found; - uint8_t card_number[10]; - uint8_t card_number_len; - uint8_t exp_month; - uint8_t exp_year; - uint16_t country_code; - uint16_t currency_code; - APDU pdol; - APDU afl; -} EmvApplication; - -/** Read bank card data - * @note Search EMV Application, start it, try to read AID, PAN, card name, - * expiration date, currency and country codes - * - * @param tx_rx FuriHalNfcTxRxContext instance - * @param emv_app EmvApplication instance - * - * @return true on success - */ -bool emv_read_bank_card(FuriHalNfcTxRxContext* tx_rx, EmvApplication* emv_app); - -/** Emulate bank card - * @note Answer to application selection and PDOL - * - * @param tx_rx FuriHalNfcTxRxContext instance - * - * @return true on success - */ -bool emv_card_emulation(FuriHalNfcTxRxContext* tx_rx); diff --git a/lib/nfc/protocols/felica/felica.c b/lib/nfc/protocols/felica/felica.c new file mode 100644 index 000000000..4b7c91fb6 --- /dev/null +++ b/lib/nfc/protocols/felica/felica.c @@ -0,0 +1,147 @@ +#include "felica.h" + +#include + +#include + +#define FELICA_PROTOCOL_NAME "FeliCa" +#define FELICA_DEVICE_NAME "FeliCa" + +#define FELICA_DATA_FORMAT_VERSION "Data format version" +#define FELICA_MANUFACTURE_ID "Manufacture id" +#define FELICA_MANUFACTURE_PARAMETER "Manufacture parameter" + +static const uint32_t felica_data_format_version = 1; + +const NfcDeviceBase nfc_device_felica = { + .protocol_name = FELICA_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)felica_alloc, + .free = (NfcDeviceFree)felica_free, + .reset = (NfcDeviceReset)felica_reset, + .copy = (NfcDeviceCopy)felica_copy, + .verify = (NfcDeviceVerify)felica_verify, + .load = (NfcDeviceLoad)felica_load, + .save = (NfcDeviceSave)felica_save, + .is_equal = (NfcDeviceEqual)felica_is_equal, + .get_name = (NfcDeviceGetName)felica_get_device_name, + .get_uid = (NfcDeviceGetUid)felica_get_uid, + .set_uid = (NfcDeviceSetUid)felica_set_uid, + .get_base_data = (NfcDeviceGetBaseData)felica_get_base_data, +}; + +FelicaData* felica_alloc() { + FelicaData* data = malloc(sizeof(FelicaData)); + return data; +} + +void felica_free(FelicaData* data) { + furi_assert(data); + + free(data); +} + +void felica_reset(FelicaData* data) { + memset(data, 0, sizeof(FelicaData)); +} + +void felica_copy(FelicaData* data, const FelicaData* other) { + furi_assert(data); + furi_assert(other); + + *data = *other; +} + +bool felica_verify(FelicaData* data, const FuriString* device_type) { + UNUSED(data); + UNUSED(device_type); + + return false; +} + +bool felica_load(FelicaData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + + bool parsed = false; + + do { + if(version < NFC_UNIFIED_FORMAT_VERSION) break; + + uint32_t data_format_version = 0; + if(!flipper_format_read_uint32(ff, FELICA_DATA_FORMAT_VERSION, &data_format_version, 1)) + break; + if(data_format_version != felica_data_format_version) break; + if(!flipper_format_read_hex(ff, FELICA_MANUFACTURE_ID, data->idm.data, FELICA_IDM_SIZE)) + break; + if(!flipper_format_read_hex( + ff, FELICA_MANUFACTURE_PARAMETER, data->pmm.data, FELICA_PMM_SIZE)) + break; + + parsed = true; + } while(false); + + return parsed; +} + +bool felica_save(const FelicaData* data, FlipperFormat* ff) { + furi_assert(data); + + bool saved = false; + + do { + if(!flipper_format_write_comment_cstr(ff, FELICA_PROTOCOL_NAME " specific data")) break; + if(!flipper_format_write_uint32( + ff, FELICA_DATA_FORMAT_VERSION, &felica_data_format_version, 1)) + break; + if(!flipper_format_write_hex(ff, FELICA_MANUFACTURE_ID, data->idm.data, FELICA_IDM_SIZE)) + break; + if(!flipper_format_write_hex( + ff, FELICA_MANUFACTURE_PARAMETER, data->pmm.data, FELICA_PMM_SIZE)) + break; + + saved = true; + } while(false); + + return saved; +} + +bool felica_is_equal(const FelicaData* data, const FelicaData* other) { + furi_assert(data); + furi_assert(other); + + return memcmp(data, other, sizeof(FelicaData)) == 0; +} + +const char* felica_get_device_name(const FelicaData* data, NfcDeviceNameType name_type) { + UNUSED(data); + UNUSED(name_type); + + return FELICA_DEVICE_NAME; +} + +const uint8_t* felica_get_uid(const FelicaData* data, size_t* uid_len) { + furi_assert(data); + + // Consider Manufacturer ID as UID + if(uid_len) { + *uid_len = FELICA_IDM_SIZE; + } + + return data->idm.data; +} + +bool felica_set_uid(FelicaData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + // Consider Manufacturer ID as UID + const bool uid_valid = uid_len == FELICA_IDM_SIZE; + if(uid_valid) { + memcpy(data->idm.data, uid, uid_len); + } + + return uid_valid; +} + +FelicaData* felica_get_base_data(const FelicaData* data) { + UNUSED(data); + furi_crash("No base data"); +} diff --git a/lib/nfc/protocols/felica/felica.h b/lib/nfc/protocols/felica/felica.h new file mode 100644 index 000000000..da9d2294e --- /dev/null +++ b/lib/nfc/protocols/felica/felica.h @@ -0,0 +1,77 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define FELICA_IDM_SIZE (8U) +#define FELICA_PMM_SIZE (8U) + +#define FELICA_GUARD_TIME_US (20000U) +#define FELICA_FDT_POLL_FC (10000U) +#define FELICA_POLL_POLL_MIN_US (1280U) + +#define FELICA_SYSTEM_CODE_CODE (0xFFFFU) +#define FELICA_TIME_SLOT_1 (0x00U) +#define FELICA_TIME_SLOT_2 (0x01U) +#define FELICA_TIME_SLOT_4 (0x03U) +#define FELICA_TIME_SLOT_8 (0x07U) +#define FELICA_TIME_SLOT_16 (0x0FU) + +typedef enum { + FelicaErrorNone, + FelicaErrorNotPresent, + FelicaErrorColResFailed, + FelicaErrorBufferOverflow, + FelicaErrorCommunication, + FelicaErrorFieldOff, + FelicaErrorWrongCrc, + FelicaErrorProtocol, + FelicaErrorTimeout, +} FelicaError; + +typedef struct { + uint8_t data[FELICA_IDM_SIZE]; +} FelicaIDm; + +typedef struct { + uint8_t data[FELICA_PMM_SIZE]; +} FelicaPMm; + +typedef struct { + FelicaIDm idm; + FelicaPMm pmm; +} FelicaData; + +extern const NfcDeviceBase nfc_device_felica; + +FelicaData* felica_alloc(); + +void felica_free(FelicaData* data); + +void felica_reset(FelicaData* data); + +void felica_copy(FelicaData* data, const FelicaData* other); + +bool felica_verify(FelicaData* data, const FuriString* device_type); + +bool felica_load(FelicaData* data, FlipperFormat* ff, uint32_t version); + +bool felica_save(const FelicaData* data, FlipperFormat* ff); + +bool felica_is_equal(const FelicaData* data, const FelicaData* other); + +const char* felica_get_device_name(const FelicaData* data, NfcDeviceNameType name_type); + +const uint8_t* felica_get_uid(const FelicaData* data, size_t* uid_len); + +bool felica_set_uid(FelicaData* data, const uint8_t* uid, size_t uid_len); + +FelicaData* felica_get_base_data(const FelicaData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/felica/felica_poller.c b/lib/nfc/protocols/felica/felica_poller.c new file mode 100644 index 000000000..3fc2affed --- /dev/null +++ b/lib/nfc/protocols/felica/felica_poller.c @@ -0,0 +1,117 @@ +#include "felica_poller_i.h" + +#include + +#include + +const FelicaData* felica_poller_get_data(FelicaPoller* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +static FelicaPoller* felica_poller_alloc(Nfc* nfc) { + furi_assert(nfc); + + FelicaPoller* instance = malloc(sizeof(FelicaPoller)); + instance->nfc = nfc; + instance->tx_buffer = bit_buffer_alloc(FELICA_POLLER_MAX_BUFFER_SIZE); + instance->rx_buffer = bit_buffer_alloc(FELICA_POLLER_MAX_BUFFER_SIZE); + + nfc_config(instance->nfc, NfcModePoller, NfcTechFelica); + nfc_set_guard_time_us(instance->nfc, FELICA_GUARD_TIME_US); + nfc_set_fdt_poll_fc(instance->nfc, FELICA_FDT_POLL_FC); + nfc_set_fdt_poll_poll_us(instance->nfc, FELICA_POLL_POLL_MIN_US); + instance->data = felica_alloc(); + + instance->felica_event.data = &instance->felica_event_data; + instance->general_event.protocol = NfcProtocolFelica; + instance->general_event.event_data = &instance->felica_event; + instance->general_event.instance = instance; + + return instance; +} + +static void felica_poller_free(FelicaPoller* instance) { + furi_assert(instance); + + furi_assert(instance->tx_buffer); + furi_assert(instance->rx_buffer); + furi_assert(instance->data); + + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + felica_free(instance->data); + free(instance); +} + +static void + felica_poller_set_callback(FelicaPoller* instance, NfcGenericCallback callback, void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +static NfcCommand felica_poller_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolInvalid); + furi_assert(event.event_data); + + FelicaPoller* instance = context; + NfcEvent* nfc_event = event.event_data; + NfcCommand command = NfcCommandContinue; + + if(nfc_event->type == NfcEventTypePollerReady) { + if(instance->state != FelicaPollerStateActivated) { + FelicaError error = felica_poller_async_activate(instance, instance->data); + if(error == FelicaErrorNone) { + instance->felica_event.type = FelicaPollerEventTypeReady; + instance->felica_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + } else { + instance->felica_event.type = FelicaPollerEventTypeError; + instance->felica_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + // Add delay to switch context + furi_delay_ms(100); + } + } else { + instance->felica_event.type = FelicaPollerEventTypeReady; + instance->felica_event_data.error = FelicaErrorNone; + command = instance->callback(instance->general_event, instance->context); + } + } + + return command; +} + +static bool felica_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.instance); + furi_assert(event.protocol == NfcProtocolInvalid); + + bool protocol_detected = false; + FelicaPoller* instance = context; + NfcEvent* nfc_event = event.event_data; + furi_assert(instance->state == FelicaPollerStateIdle); + + if(nfc_event->type == NfcEventTypePollerReady) { + FelicaError error = felica_poller_async_activate(instance, instance->data); + protocol_detected = (error == FelicaErrorNone); + } + + return protocol_detected; +} + +const NfcPollerBase nfc_poller_felica = { + .alloc = (NfcPollerAlloc)felica_poller_alloc, + .free = (NfcPollerFree)felica_poller_free, + .set_callback = (NfcPollerSetCallback)felica_poller_set_callback, + .run = (NfcPollerRun)felica_poller_run, + .detect = (NfcPollerDetect)felica_poller_detect, + .get_data = (NfcPollerGetData)felica_poller_get_data, +}; diff --git a/lib/nfc/protocols/felica/felica_poller.h b/lib/nfc/protocols/felica/felica_poller.h new file mode 100644 index 000000000..7d0c9525e --- /dev/null +++ b/lib/nfc/protocols/felica/felica_poller.h @@ -0,0 +1,30 @@ +#pragma once + +#include "felica.h" +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct FelicaPoller FelicaPoller; + +typedef enum { + FelicaPollerEventTypeError, + FelicaPollerEventTypeReady, +} FelicaPollerEventType; + +typedef struct { + FelicaError error; +} FelicaPollerEventData; + +typedef struct { + FelicaPollerEventType type; + FelicaPollerEventData* data; +} FelicaPollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/felica/felica_poller_defs.h b/lib/nfc/protocols/felica/felica_poller_defs.h new file mode 100644 index 000000000..fc99dc752 --- /dev/null +++ b/lib/nfc/protocols/felica/felica_poller_defs.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NfcPollerBase nfc_poller_felica; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/felica/felica_poller_i.c b/lib/nfc/protocols/felica/felica_poller_i.c new file mode 100644 index 000000000..d8015fdfa --- /dev/null +++ b/lib/nfc/protocols/felica/felica_poller_i.c @@ -0,0 +1,128 @@ +#include "felica_poller_i.h" + +#include + +#define TAG "FelicaPoller" + +static FelicaError felica_poller_process_error(NfcError error) { + switch(error) { + case NfcErrorNone: + return FelicaErrorNone; + case NfcErrorTimeout: + return FelicaErrorTimeout; + default: + return FelicaErrorNotPresent; + } +} + +static FelicaError felica_poller_frame_exchange( + FelicaPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + + const size_t tx_bytes = bit_buffer_get_size_bytes(tx_buffer); + furi_assert(tx_bytes <= bit_buffer_get_capacity_bytes(instance->tx_buffer) - FELICA_CRC_SIZE); + + felica_crc_append(instance->tx_buffer); + + FelicaError ret = FelicaErrorNone; + + do { + NfcError error = + nfc_poller_trx(instance->nfc, instance->tx_buffer, instance->rx_buffer, fwt); + if(error != NfcErrorNone) { + ret = felica_poller_process_error(error); + break; + } + + bit_buffer_copy(rx_buffer, instance->rx_buffer); + if(!felica_crc_check(instance->rx_buffer)) { + ret = FelicaErrorWrongCrc; + break; + } + + felica_crc_trim(rx_buffer); + } while(false); + + return ret; +} + +FelicaError felica_poller_async_polling( + FelicaPoller* instance, + const FelicaPollerPollingCommand* cmd, + FelicaPollerPollingResponse* resp) { + furi_assert(instance); + furi_assert(cmd); + furi_assert(resp); + + FelicaError error = FelicaErrorNone; + + do { + bit_buffer_set_size_bytes(instance->tx_buffer, 2); + // Set frame len + bit_buffer_set_byte( + instance->tx_buffer, 0, sizeof(FelicaPollerPollingCommand) + FELICA_CRC_SIZE); + // Set command code + bit_buffer_set_byte(instance->tx_buffer, 1, FELICA_POLLER_CMD_POLLING_REQ_CODE); + // Set other data + bit_buffer_append_bytes( + instance->tx_buffer, (uint8_t*)cmd, sizeof(FelicaPollerPollingCommand)); + + error = felica_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, FELICA_POLLER_POLLING_FWT); + + if(error != FelicaErrorNone) break; + if(bit_buffer_get_byte(instance->rx_buffer, 1) != FELICA_POLLER_CMD_POLLING_RESP_CODE) { + error = FelicaErrorProtocol; + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) < + sizeof(FelicaIDm) + sizeof(FelicaPMm) + 1) { + error = FelicaErrorProtocol; + break; + } + + bit_buffer_write_bytes_mid(instance->rx_buffer, resp->idm.data, 2, sizeof(FelicaIDm)); + bit_buffer_write_bytes_mid( + instance->rx_buffer, resp->pmm.data, sizeof(FelicaIDm) + 2, sizeof(FelicaPMm)); + + } while(false); + + return error; +} + +FelicaError felica_poller_async_activate(FelicaPoller* instance, FelicaData* data) { + furi_assert(instance); + + felica_reset(data); + + FelicaError ret; + + do { + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + // Send Polling command + const FelicaPollerPollingCommand polling_cmd = { + .system_code = FELICA_SYSTEM_CODE_CODE, + .request_code = 0, + .time_slot = FELICA_TIME_SLOT_1, + }; + FelicaPollerPollingResponse polling_resp = {}; + + ret = felica_poller_async_polling(instance, &polling_cmd, &polling_resp); + + if(ret != FelicaErrorNone) { + FURI_LOG_T(TAG, "Activation failed error: %d", ret); + break; + } + + data->idm = polling_resp.idm; + data->pmm = polling_resp.pmm; + instance->state = FelicaPollerStateActivated; + } while(false); + + return ret; +} diff --git a/lib/nfc/protocols/felica/felica_poller_i.h b/lib/nfc/protocols/felica/felica_poller_i.h new file mode 100644 index 000000000..e12f01472 --- /dev/null +++ b/lib/nfc/protocols/felica/felica_poller_i.h @@ -0,0 +1,60 @@ +#pragma once + +#include "felica_poller.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define FELICA_POLLER_MAX_BUFFER_SIZE (256U) + +#define FELICA_POLLER_POLLING_FWT (200000U) + +#define FELICA_POLLER_CMD_POLLING_REQ_CODE (0x00U) +#define FELICA_POLLER_CMD_POLLING_RESP_CODE (0x01U) + +typedef enum { + FelicaPollerStateIdle, + FelicaPollerStateActivated, +} FelicaPollerState; + +struct FelicaPoller { + Nfc* nfc; + FelicaPollerState state; + FelicaData* data; + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + + NfcGenericEvent general_event; + FelicaPollerEvent felica_event; + FelicaPollerEventData felica_event_data; + NfcGenericCallback callback; + void* context; +}; + +typedef struct { + uint16_t system_code; + uint8_t request_code; + uint8_t time_slot; +} FelicaPollerPollingCommand; + +typedef struct { + FelicaIDm idm; + FelicaPMm pmm; + uint8_t request_data[2]; +} FelicaPollerPollingResponse; + +const FelicaData* felica_poller_get_data(FelicaPoller* instance); + +FelicaError felica_poller_async_polling( + FelicaPoller* instance, + const FelicaPollerPollingCommand* cmd, + FelicaPollerPollingResponse* resp); + +FelicaError felica_poller_async_activate(FelicaPoller* instance, FelicaData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a.c b/lib/nfc/protocols/iso14443_3a/iso14443_3a.c new file mode 100644 index 000000000..96d0b3953 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a.c @@ -0,0 +1,186 @@ +#include "iso14443_3a.h" + +#include +#include + +#define ISO14443A_ATS_BIT (1U << 5) + +#define ISO14443_3A_PROTOCOL_NAME_LEGACY "UID" +#define ISO14443_3A_PROTOCOL_NAME "ISO14443-3A" +#define ISO14443_3A_DEVICE_NAME "ISO14443-3A (Unknown)" + +#define ISO14443_3A_ATQA_KEY "ATQA" +#define ISO14443_3A_SAK_KEY "SAK" + +const NfcDeviceBase nfc_device_iso14443_3a = { + .protocol_name = ISO14443_3A_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)iso14443_3a_alloc, + .free = (NfcDeviceFree)iso14443_3a_free, + .reset = (NfcDeviceReset)iso14443_3a_reset, + .copy = (NfcDeviceCopy)iso14443_3a_copy, + .verify = (NfcDeviceVerify)iso14443_3a_verify, + .load = (NfcDeviceLoad)iso14443_3a_load, + .save = (NfcDeviceSave)iso14443_3a_save, + .is_equal = (NfcDeviceEqual)iso14443_3a_is_equal, + .get_name = (NfcDeviceGetName)iso14443_3a_get_device_name, + .get_uid = (NfcDeviceGetUid)iso14443_3a_get_uid, + .set_uid = (NfcDeviceSetUid)iso14443_3a_set_uid, + .get_base_data = (NfcDeviceGetBaseData)iso14443_3a_get_base_data, +}; + +Iso14443_3aData* iso14443_3a_alloc() { + Iso14443_3aData* data = malloc(sizeof(Iso14443_3aData)); + return data; +} + +void iso14443_3a_free(Iso14443_3aData* data) { + furi_assert(data); + + free(data); +} + +void iso14443_3a_reset(Iso14443_3aData* data) { + furi_assert(data); + memset(data, 0, sizeof(Iso14443_3aData)); +} + +void iso14443_3a_copy(Iso14443_3aData* data, const Iso14443_3aData* other) { + furi_assert(data); + furi_assert(other); + + *data = *other; +} + +bool iso14443_3a_verify(Iso14443_3aData* data, const FuriString* device_type) { + UNUSED(data); + return furi_string_equal(device_type, ISO14443_3A_PROTOCOL_NAME_LEGACY); +} + +bool iso14443_3a_load(Iso14443_3aData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + + bool parsed = false; + + do { + // Common to all format versions + if(!flipper_format_read_hex(ff, ISO14443_3A_ATQA_KEY, data->atqa, 2)) break; + if(!flipper_format_read_hex(ff, ISO14443_3A_SAK_KEY, &data->sak, 1)) break; + + if(version > NFC_LSB_ATQA_FORMAT_VERSION) { + // Swap ATQA bytes for newer versions + FURI_SWAP(data->atqa[0], data->atqa[1]); + } + + parsed = true; + } while(false); + + return parsed; +} + +bool iso14443_3a_save(const Iso14443_3aData* data, FlipperFormat* ff) { + furi_assert(data); + + bool saved = false; + + do { + // Save ATQA in MSB order for correct companion apps display + const uint8_t atqa[2] = {data->atqa[1], data->atqa[0]}; + if(!flipper_format_write_comment_cstr(ff, ISO14443_3A_PROTOCOL_NAME " specific data")) + break; + + // Write ATQA and SAK + if(!flipper_format_write_hex(ff, ISO14443_3A_ATQA_KEY, atqa, 2)) break; + if(!flipper_format_write_hex(ff, ISO14443_3A_SAK_KEY, &data->sak, 1)) break; + saved = true; + } while(false); + + return saved; +} + +bool iso14443_3a_is_equal(const Iso14443_3aData* data, const Iso14443_3aData* other) { + furi_assert(data); + furi_assert(other); + + return memcmp(data, other, sizeof(Iso14443_3aData)) == 0; +} + +const char* iso14443_3a_get_device_name(const Iso14443_3aData* data, NfcDeviceNameType name_type) { + UNUSED(data); + UNUSED(name_type); + return ISO14443_3A_DEVICE_NAME; +} + +const uint8_t* iso14443_3a_get_uid(const Iso14443_3aData* data, size_t* uid_len) { + furi_assert(data); + + if(uid_len) { + *uid_len = data->uid_len; + } + + return data->uid; +} + +bool iso14443_3a_set_uid(Iso14443_3aData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + const bool uid_valid = uid_len == ISO14443_3A_UID_4_BYTES || + uid_len == ISO14443_3A_UID_7_BYTES || + uid_len == ISO14443_3A_UID_10_BYTES; + + if(uid_valid) { + memcpy(data->uid, uid, uid_len); + data->uid_len = uid_len; + } + + return uid_valid; +} + +Iso14443_3aData* iso14443_3a_get_base_data(const Iso14443_3aData* data) { + UNUSED(data); + furi_crash("No base data"); +} + +uint32_t iso14443_3a_get_cuid(const Iso14443_3aData* data) { + furi_assert(data); + + uint32_t cuid = 0; + const uint8_t* cuid_start = data->uid; + if(data->uid_len == ISO14443_3A_UID_7_BYTES) { + cuid_start = &data->uid[3]; + } + cuid = (cuid_start[0] << 24) | (cuid_start[1] << 16) | (cuid_start[2] << 8) | (cuid_start[3]); + + return cuid; +} + +bool iso14443_3a_supports_iso14443_4(const Iso14443_3aData* data) { + furi_assert(data); + + return data->sak & ISO14443A_ATS_BIT; +} + +uint8_t iso14443_3a_get_sak(const Iso14443_3aData* data) { + furi_assert(data); + + return data->sak; +} + +void iso14443_3a_get_atqa(const Iso14443_3aData* data, uint8_t atqa[2]) { + furi_assert(data); + furi_assert(atqa); + + memcpy(atqa, data->atqa, sizeof(data->atqa)); +} + +void iso14443_3a_set_sak(Iso14443_3aData* data, uint8_t sak) { + furi_assert(data); + + data->sak = sak; +} + +void iso14443_3a_set_atqa(Iso14443_3aData* data, const uint8_t atqa[2]) { + furi_assert(data); + furi_assert(atqa); + + memcpy(data->atqa, atqa, sizeof(data->atqa)); +} diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a.h b/lib/nfc/protocols/iso14443_3a/iso14443_3a.h new file mode 100644 index 000000000..005626e62 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a.h @@ -0,0 +1,107 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ISO14443_3A_UID_4_BYTES (4U) +#define ISO14443_3A_UID_7_BYTES (7U) +#define ISO14443_3A_UID_10_BYTES (10U) +#define ISO14443_3A_MAX_UID_SIZE ISO14443_3A_UID_10_BYTES + +#define ISO14443_3A_GUARD_TIME_US (5000) +#define ISO14443_3A_FDT_POLL_FC (1620) +#define ISO14443_3A_FDT_LISTEN_FC (1172) +#define ISO14443_3A_POLLER_MASK_RX_FS ((ISO14443_3A_FDT_LISTEN_FC) / 2) +#define ISO14443_3A_POLL_POLL_MIN_US (1100) + +typedef enum { + Iso14443_3aErrorNone, + Iso14443_3aErrorNotPresent, + Iso14443_3aErrorColResFailed, + Iso14443_3aErrorBufferOverflow, + Iso14443_3aErrorCommunication, + Iso14443_3aErrorFieldOff, + Iso14443_3aErrorWrongCrc, + Iso14443_3aErrorTimeout, +} Iso14443_3aError; + +typedef struct { + uint8_t sens_resp[2]; +} Iso14443_3aSensResp; + +typedef struct { + uint8_t sel_cmd; + uint8_t sel_par; + uint8_t data[4]; // max data bit is 32 +} Iso14443_3aSddReq; + +typedef struct { + uint8_t nfcid[4]; + uint8_t bss; +} Iso14443_3aSddResp; + +typedef struct { + uint8_t sel_cmd; + uint8_t sel_par; + uint8_t nfcid[4]; + uint8_t bcc; +} Iso14443_3aSelReq; + +typedef struct { + uint8_t sak; +} Iso14443_3aSelResp; + +typedef struct { + uint8_t uid[ISO14443_3A_MAX_UID_SIZE]; + uint8_t uid_len; + uint8_t atqa[2]; + uint8_t sak; +} Iso14443_3aData; + +Iso14443_3aData* iso14443_3a_alloc(); + +void iso14443_3a_free(Iso14443_3aData* data); + +void iso14443_3a_reset(Iso14443_3aData* data); + +void iso14443_3a_copy(Iso14443_3aData* data, const Iso14443_3aData* other); + +bool iso14443_3a_verify(Iso14443_3aData* data, const FuriString* device_type); + +bool iso14443_3a_load(Iso14443_3aData* data, FlipperFormat* ff, uint32_t version); + +bool iso14443_3a_save(const Iso14443_3aData* data, FlipperFormat* ff); + +bool iso14443_3a_is_equal(const Iso14443_3aData* data, const Iso14443_3aData* other); + +const char* iso14443_3a_get_device_name(const Iso14443_3aData* data, NfcDeviceNameType name_type); + +const uint8_t* iso14443_3a_get_uid(const Iso14443_3aData* data, size_t* uid_len); + +bool iso14443_3a_set_uid(Iso14443_3aData* data, const uint8_t* uid, size_t uid_len); + +Iso14443_3aData* iso14443_3a_get_base_data(const Iso14443_3aData* data); + +uint32_t iso14443_3a_get_cuid(const Iso14443_3aData* data); + +// Getters and tests + +bool iso14443_3a_supports_iso14443_4(const Iso14443_3aData* data); + +uint8_t iso14443_3a_get_sak(const Iso14443_3aData* data); + +void iso14443_3a_get_atqa(const Iso14443_3aData* data, uint8_t atqa[2]); + +// Setters + +void iso14443_3a_set_sak(Iso14443_3aData* data, uint8_t sak); + +void iso14443_3a_set_atqa(Iso14443_3aData* data, const uint8_t atqa[2]); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_device_defs.h b/lib/nfc/protocols/iso14443_3a/iso14443_3a_device_defs.h new file mode 100644 index 000000000..8a736dfa7 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_device_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcDeviceBase nfc_device_iso14443_3a; diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener.c b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener.c new file mode 100644 index 000000000..89d96f6fc --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener.c @@ -0,0 +1,127 @@ +#include "iso14443_3a_listener_i.h" + +#include "nfc/protocols/nfc_listener_base.h" +#include "nfc/helpers/iso14443_crc.h" + +#include +#include + +#define TAG "Iso14443_3aListener" + +#define ISO14443_3A_LISTENER_MAX_BUFFER_SIZE (256) + +static bool iso14443_3a_listener_halt_received(BitBuffer* buf) { + bool halt_cmd_received = false; + + do { + if(bit_buffer_get_size_bytes(buf) != 4) break; + if(!iso14443_crc_check(Iso14443CrcTypeA, buf)) break; + if(bit_buffer_get_byte(buf, 0) != 0x50) break; + if(bit_buffer_get_byte(buf, 1) != 0x00) break; + halt_cmd_received = true; + } while(false); + + return halt_cmd_received; +} + +Iso14443_3aListener* iso14443_3a_listener_alloc(Nfc* nfc, Iso14443_3aData* data) { + furi_assert(nfc); + + Iso14443_3aListener* instance = malloc(sizeof(Iso14443_3aListener)); + instance->nfc = nfc; + instance->data = data; + instance->tx_buffer = bit_buffer_alloc(ISO14443_3A_LISTENER_MAX_BUFFER_SIZE); + + instance->iso14443_3a_event.data = &instance->iso14443_3a_event_data; + instance->generic_event.protocol = NfcProtocolIso14443_3a; + instance->generic_event.instance = instance; + instance->generic_event.event_data = &instance->iso14443_3a_event; + + nfc_set_fdt_listen_fc(instance->nfc, ISO14443_3A_FDT_LISTEN_FC); + nfc_config(instance->nfc, NfcModeListener, NfcTechIso14443a); + nfc_iso14443a_listener_set_col_res_data( + instance->nfc, + instance->data->uid, + instance->data->uid_len, + instance->data->atqa, + instance->data->sak); + + return instance; +} + +void iso14443_3a_listener_free(Iso14443_3aListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + furi_assert(instance->tx_buffer); + + bit_buffer_free(instance->tx_buffer); + free(instance); +} + +void iso14443_3a_listener_set_callback( + Iso14443_3aListener* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + + instance->callback = callback; + instance->context = context; +} + +const Iso14443_3aData* iso14443_3a_listener_get_data(Iso14443_3aListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +NfcCommand iso14443_3a_listener_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolInvalid); + furi_assert(event.event_data); + + Iso14443_3aListener* instance = context; + NfcEvent* nfc_event = event.event_data; + NfcCommand command = NfcCommandContinue; + + if(nfc_event->type == NfcEventTypeListenerActivated) { + instance->state = Iso14443_3aListenerStateActive; + } else if(nfc_event->type == NfcEventTypeFieldOff) { + instance->state = Iso14443_3aListenerStateIdle; + if(instance->callback) { + instance->iso14443_3a_event.type = Iso14443_3aListenerEventTypeFieldOff; + instance->callback(instance->generic_event, instance->context); + } + command = NfcCommandSleep; + } else if(nfc_event->type == NfcEventTypeRxEnd) { + if(iso14443_3a_listener_halt_received(nfc_event->data.buffer)) { + if(instance->callback) { + instance->iso14443_3a_event.type = Iso14443_3aListenerEventTypeHalted; + instance->callback(instance->generic_event, instance->context); + } + command = NfcCommandSleep; + } else { + if(iso14443_crc_check(Iso14443CrcTypeA, nfc_event->data.buffer)) { + instance->iso14443_3a_event.type = + Iso14443_3aListenerEventTypeReceivedStandardFrame; + iso14443_crc_trim(nfc_event->data.buffer); + } else { + instance->iso14443_3a_event.type = Iso14443_3aListenerEventTypeReceivedData; + } + instance->iso14443_3a_event_data.buffer = nfc_event->data.buffer; + if(instance->callback) { + command = instance->callback(instance->generic_event, instance->context); + } + } + } + + return command; +} + +const NfcListenerBase nfc_listener_iso14443_3a = { + .alloc = (NfcListenerAlloc)iso14443_3a_listener_alloc, + .free = (NfcListenerFree)iso14443_3a_listener_free, + .set_callback = (NfcListenerSetCallback)iso14443_3a_listener_set_callback, + .get_data = (NfcListenerGetData)iso14443_3a_listener_get_data, + .run = (NfcListenerRun)iso14443_3a_listener_run, +}; diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener.h b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener.h new file mode 100644 index 000000000..8a550ca0a --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener.h @@ -0,0 +1,31 @@ +#pragma once + +#include "iso14443_3a.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso14443_3aListener Iso14443_3aListener; + +typedef enum { + Iso14443_3aListenerEventTypeFieldOff, + Iso14443_3aListenerEventTypeHalted, + + Iso14443_3aListenerEventTypeReceivedStandardFrame, + Iso14443_3aListenerEventTypeReceivedData, +} Iso14443_3aListenerEventType; + +typedef struct { + BitBuffer* buffer; +} Iso14443_3aListenerEventData; + +typedef struct { + Iso14443_3aListenerEventType type; + Iso14443_3aListenerEventData* data; +} Iso14443_3aListenerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener_defs.h b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener_defs.h new file mode 100644 index 000000000..b4fccec74 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcListenerBase nfc_listener_iso14443_3a; diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener_i.c b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener_i.c new file mode 100644 index 000000000..46501503c --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener_i.c @@ -0,0 +1,73 @@ +#include "iso14443_3a_listener_i.h" + +#include "nfc/helpers/iso14443_crc.h" + +#define TAG "Iso14443_3aListener" + +static Iso14443_3aError iso14443_3a_listener_process_nfc_error(NfcError error) { + Iso14443_3aError ret = Iso14443_3aErrorNone; + + if(error == NfcErrorNone) { + ret = Iso14443_3aErrorNone; + } else if(error == NfcErrorTimeout) { + ret = Iso14443_3aErrorTimeout; + } else { + ret = Iso14443_3aErrorFieldOff; + } + + return ret; +} + +Iso14443_3aError + iso14443_3a_listener_tx(Iso14443_3aListener* instance, const BitBuffer* tx_buffer) { + furi_assert(instance); + furi_assert(tx_buffer); + + Iso14443_3aError ret = Iso14443_3aErrorNone; + NfcError error = nfc_listener_tx(instance->nfc, tx_buffer); + if(error != NfcErrorNone) { + FURI_LOG_W(TAG, "Tx error: %d", error); + ret = iso14443_3a_listener_process_nfc_error(error); + } + + return ret; +} + +Iso14443_3aError iso14443_3a_listener_tx_with_custom_parity( + Iso14443_3aListener* instance, + const BitBuffer* tx_buffer) { + furi_assert(instance); + furi_assert(tx_buffer); + + Iso14443_3aError ret = Iso14443_3aErrorNone; + NfcError error = nfc_iso14443a_listener_tx_custom_parity(instance->nfc, tx_buffer); + if(error != NfcErrorNone) { + FURI_LOG_W(TAG, "Tx error: %d", error); + ret = iso14443_3a_listener_process_nfc_error(error); + } + + return ret; +}; + +Iso14443_3aError iso14443_3a_listener_send_standard_frame( + Iso14443_3aListener* instance, + const BitBuffer* tx_buffer) { + furi_assert(instance); + furi_assert(tx_buffer); + furi_assert(instance->tx_buffer); + + Iso14443_3aError ret = Iso14443_3aErrorNone; + do { + bit_buffer_copy(instance->tx_buffer, tx_buffer); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_buffer); + + NfcError error = nfc_listener_tx(instance->nfc, instance->tx_buffer); + if(error != NfcErrorNone) { + FURI_LOG_W(TAG, "Tx error: %d", error); + ret = iso14443_3a_listener_process_nfc_error(error); + break; + } + } while(false); + + return ret; +} diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener_i.h b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener_i.h new file mode 100644 index 000000000..0113a1cb8 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_listener_i.h @@ -0,0 +1,42 @@ +#pragma once + +#include "iso14443_3a_listener.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Iso14443_3aListenerStateIdle, + Iso14443_3aListenerStateActive, +} Iso14443_3aListenerState; + +struct Iso14443_3aListener { + Nfc* nfc; + Iso14443_3aData* data; + Iso14443_3aListenerState state; + + BitBuffer* tx_buffer; + + NfcGenericEvent generic_event; + Iso14443_3aListenerEvent iso14443_3a_event; + Iso14443_3aListenerEventData iso14443_3a_event_data; + NfcGenericCallback callback; + void* context; +}; + +Iso14443_3aError + iso14443_3a_listener_tx(Iso14443_3aListener* instance, const BitBuffer* tx_buffer); + +Iso14443_3aError iso14443_3a_listener_tx_with_custom_parity( + Iso14443_3aListener* instance, + const BitBuffer* tx_buffer); + +Iso14443_3aError iso14443_3a_listener_send_standard_frame( + Iso14443_3aListener* instance, + const BitBuffer* tx_buffer); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller.c b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller.c new file mode 100644 index 000000000..880092c33 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller.c @@ -0,0 +1,128 @@ +#include "iso14443_3a_poller_i.h" + +#include + +#include + +#define TAG "ISO14443_3A" + +const Iso14443_3aData* iso14443_3a_poller_get_data(Iso14443_3aPoller* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +static Iso14443_3aPoller* iso14443_3a_poller_alloc(Nfc* nfc) { + furi_assert(nfc); + + Iso14443_3aPoller* instance = malloc(sizeof(Iso14443_3aPoller)); + instance->nfc = nfc; + instance->tx_buffer = bit_buffer_alloc(ISO14443_3A_POLLER_MAX_BUFFER_SIZE); + instance->rx_buffer = bit_buffer_alloc(ISO14443_3A_POLLER_MAX_BUFFER_SIZE); + + nfc_config(instance->nfc, NfcModePoller, NfcTechIso14443a); + nfc_set_guard_time_us(instance->nfc, ISO14443_3A_GUARD_TIME_US); + nfc_set_fdt_poll_fc(instance->nfc, ISO14443_3A_FDT_POLL_FC); + nfc_set_fdt_poll_poll_us(instance->nfc, ISO14443_3A_POLL_POLL_MIN_US); + instance->data = iso14443_3a_alloc(); + + instance->iso14443_3a_event.data = &instance->iso14443_3a_event_data; + instance->general_event.protocol = NfcProtocolIso14443_3a; + instance->general_event.event_data = &instance->iso14443_3a_event; + instance->general_event.instance = instance; + + return instance; +} + +static void iso14443_3a_poller_free_new(Iso14443_3aPoller* iso14443_3a_poller) { + furi_assert(iso14443_3a_poller); + + Iso14443_3aPoller* instance = iso14443_3a_poller; + furi_assert(instance->tx_buffer); + furi_assert(instance->rx_buffer); + furi_assert(instance->data); + + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + iso14443_3a_free(instance->data); + free(instance); +} + +static void iso14443_3a_poller_set_callback( + Iso14443_3aPoller* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +static NfcCommand iso14443_3a_poller_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolInvalid); + furi_assert(event.event_data); + + Iso14443_3aPoller* instance = context; + NfcEvent* nfc_event = event.event_data; + NfcCommand command = NfcCommandContinue; + + if(nfc_event->type == NfcEventTypePollerReady) { + if(instance->state != Iso14443_3aPollerStateActivated) { + Iso14443_3aData data = {}; + Iso14443_3aError error = iso14443_3a_poller_async_activate(instance, &data); + if(error == Iso14443_3aErrorNone) { + instance->state = Iso14443_3aPollerStateActivated; + instance->iso14443_3a_event.type = Iso14443_3aPollerEventTypeReady; + instance->iso14443_3a_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + } else { + instance->iso14443_3a_event.type = Iso14443_3aPollerEventTypeError; + instance->iso14443_3a_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + // Add delay to switch context + furi_delay_ms(100); + } + } else { + instance->iso14443_3a_event.type = Iso14443_3aPollerEventTypeReady; + instance->iso14443_3a_event_data.error = Iso14443_3aErrorNone; + command = instance->callback(instance->general_event, instance->context); + } + } + + if(command == NfcCommandReset) { + instance->state = Iso14443_3aPollerStateIdle; + } + + return command; +} + +static bool iso14443_3a_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.instance); + furi_assert(event.protocol == NfcProtocolInvalid); + + bool protocol_detected = false; + Iso14443_3aPoller* instance = context; + NfcEvent* nfc_event = event.event_data; + furi_assert(instance->state == Iso14443_3aPollerStateIdle); + + if(nfc_event->type == NfcEventTypePollerReady) { + Iso14443_3aError error = iso14443_3a_poller_async_activate(instance, NULL); + protocol_detected = (error == Iso14443_3aErrorNone); + } + + return protocol_detected; +} + +const NfcPollerBase nfc_poller_iso14443_3a = { + .alloc = (NfcPollerAlloc)iso14443_3a_poller_alloc, + .free = (NfcPollerFree)iso14443_3a_poller_free_new, + .set_callback = (NfcPollerSetCallback)iso14443_3a_poller_set_callback, + .run = (NfcPollerRun)iso14443_3a_poller_run, + .detect = (NfcPollerDetect)iso14443_3a_poller_detect, + .get_data = (NfcPollerGetData)iso14443_3a_poller_get_data, +}; diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller.h b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller.h new file mode 100644 index 000000000..385cd5225 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller.h @@ -0,0 +1,42 @@ +#pragma once + +#include "iso14443_3a.h" +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso14443_3aPoller Iso14443_3aPoller; + +typedef enum { + Iso14443_3aPollerEventTypeError, + Iso14443_3aPollerEventTypeReady, +} Iso14443_3aPollerEventType; + +typedef struct { + Iso14443_3aError error; +} Iso14443_3aPollerEventData; + +typedef struct { + Iso14443_3aPollerEventType type; + Iso14443_3aPollerEventData* data; +} Iso14443_3aPollerEvent; + +Iso14443_3aError iso14443_3a_poller_txrx( + Iso14443_3aPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt); + +Iso14443_3aError iso14443_3a_poller_send_standard_frame( + Iso14443_3aPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_defs.h b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_defs.h new file mode 100644 index 000000000..1bcc684b4 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcPollerBase nfc_poller_iso14443_3a; diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_i.c b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_i.c new file mode 100644 index 000000000..3434dc8e3 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_i.c @@ -0,0 +1,293 @@ +#include "iso14443_3a_poller_i.h" + +#include + +#include "nfc/helpers/iso14443_crc.h" + +#define TAG "ISO14443_3A" + +static Iso14443_3aError iso14443_3a_poller_process_error(NfcError error) { + Iso14443_3aError ret = Iso14443_3aErrorNone; + if(error == NfcErrorNone) { + ret = Iso14443_3aErrorNone; + } else if(error == NfcErrorTimeout) { + ret = Iso14443_3aErrorTimeout; + } else { + ret = Iso14443_3aErrorNotPresent; + } + return ret; +} + +static Iso14443_3aError iso14443_3a_poller_standard_frame_exchange( + Iso14443_3aPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + furi_assert(tx_buffer); + furi_assert(rx_buffer); + + uint16_t tx_bytes = bit_buffer_get_size_bytes(tx_buffer); + furi_assert(tx_bytes <= bit_buffer_get_capacity_bytes(instance->tx_buffer) - 2); + + bit_buffer_copy(instance->tx_buffer, tx_buffer); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_buffer); + Iso14443_3aError ret = Iso14443_3aErrorNone; + + do { + NfcError error = + nfc_poller_trx(instance->nfc, instance->tx_buffer, instance->rx_buffer, fwt); + if(error != NfcErrorNone) { + ret = iso14443_3a_poller_process_error(error); + break; + } + + bit_buffer_copy(rx_buffer, instance->rx_buffer); + if(!iso14443_crc_check(Iso14443CrcTypeA, instance->rx_buffer)) { + ret = Iso14443_3aErrorWrongCrc; + break; + } + + iso14443_crc_trim(rx_buffer); + } while(false); + + return ret; +} + +Iso14443_3aError iso14443_3a_poller_check_presence(Iso14443_3aPoller* instance) { + furi_assert(instance); + furi_assert(instance->nfc); + + NfcError error = NfcErrorNone; + Iso14443_3aError ret = Iso14443_3aErrorNone; + do { + error = nfc_iso14443a_poller_trx_short_frame( + instance->nfc, + NfcIso14443aShortFrameSensReq, + instance->rx_buffer, + ISO14443_3A_FDT_LISTEN_FC); + if(error != NfcErrorNone) { + ret = iso14443_3a_poller_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != sizeof(instance->col_res.sens_resp)) { + ret = Iso14443_3aErrorCommunication; + break; + } + } while(false); + + return ret; +} + +Iso14443_3aError iso14443_3a_poller_halt(Iso14443_3aPoller* instance) { + furi_assert(instance); + furi_assert(instance->nfc); + furi_assert(instance->tx_buffer); + + uint8_t halt_cmd[2] = {0x50, 0x00}; + bit_buffer_copy_bytes(instance->tx_buffer, halt_cmd, sizeof(halt_cmd)); + + iso14443_3a_poller_standard_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ISO14443_3A_FDT_LISTEN_FC); + + instance->state = Iso14443_3aPollerStateIdle; + return Iso14443_3aErrorNone; +} + +Iso14443_3aError iso14443_3a_poller_async_activate( + Iso14443_3aPoller* instance, + Iso14443_3aData* iso14443_3a_data) { + furi_assert(instance); + furi_assert(instance->nfc); + furi_assert(instance->tx_buffer); + furi_assert(instance->rx_buffer); + + // Reset Iso14443_3a poller state + memset(&instance->col_res, 0, sizeof(instance->col_res)); + memset(instance->data, 0, sizeof(Iso14443_3aData)); + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + // Halt if necessary + if(instance->state != Iso14443_3aPollerStateIdle) { + iso14443_3a_poller_halt(instance); + instance->state = Iso14443_3aPollerStateIdle; + } + + NfcError error = NfcErrorNone; + Iso14443_3aError ret = Iso14443_3aErrorNone; + + bool activated = false; + do { + error = nfc_iso14443a_poller_trx_short_frame( + instance->nfc, + NfcIso14443aShortFrameSensReq, + instance->rx_buffer, + ISO14443_3A_FDT_LISTEN_FC); + if(error != NfcErrorNone) { + ret = Iso14443_3aErrorNotPresent; + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != sizeof(instance->col_res.sens_resp)) { + FURI_LOG_W(TAG, "Wrong sens response size"); + ret = Iso14443_3aErrorCommunication; + break; + } + bit_buffer_write_bytes( + instance->rx_buffer, + &instance->col_res.sens_resp, + sizeof(instance->col_res.sens_resp)); + memcpy( + instance->data->atqa, + &instance->col_res.sens_resp, + sizeof(instance->col_res.sens_resp)); + + instance->state = Iso14443_3aPollerStateColResInProgress; + instance->col_res.cascade_level = 0; + instance->col_res.state = Iso14443_3aPollerColResStateStateNewCascade; + + while(instance->state == Iso14443_3aPollerStateColResInProgress) { + if(instance->col_res.state == Iso14443_3aPollerColResStateStateNewCascade) { + bit_buffer_set_size_bytes(instance->tx_buffer, 2); + bit_buffer_set_byte( + instance->tx_buffer, + 0, + ISO14443_3A_POLLER_SEL_CMD(instance->col_res.cascade_level)); + bit_buffer_set_byte(instance->tx_buffer, 1, ISO14443_3A_POLLER_SEL_PAR(2, 0)); + error = nfc_iso14443a_poller_trx_sdd_frame( + instance->nfc, + instance->tx_buffer, + instance->rx_buffer, + ISO14443_3A_FDT_LISTEN_FC); + if(error != NfcErrorNone) { + FURI_LOG_E(TAG, "Sdd request failed: %d", error); + instance->state = Iso14443_3aPollerStateColResFailed; + ret = Iso14443_3aErrorColResFailed; + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != 5) { + FURI_LOG_E(TAG, "Sdd response wrong length"); + instance->state = Iso14443_3aPollerStateColResFailed; + ret = Iso14443_3aErrorColResFailed; + break; + } + bit_buffer_write_bytes( + instance->rx_buffer, &instance->col_res.sdd_resp, sizeof(Iso14443_3aSddResp)); + instance->col_res.state = Iso14443_3aPollerColResStateStateSelectCascade; + } else if(instance->col_res.state == Iso14443_3aPollerColResStateStateSelectCascade) { + instance->col_res.sel_req.sel_cmd = + ISO14443_3A_POLLER_SEL_CMD(instance->col_res.cascade_level); + instance->col_res.sel_req.sel_par = ISO14443_3A_POLLER_SEL_PAR(7, 0); + memcpy( + instance->col_res.sel_req.nfcid, + instance->col_res.sdd_resp.nfcid, + sizeof(instance->col_res.sdd_resp.nfcid)); + instance->col_res.sel_req.bcc = instance->col_res.sdd_resp.bss; + bit_buffer_copy_bytes( + instance->tx_buffer, + (uint8_t*)&instance->col_res.sel_req, + sizeof(instance->col_res.sel_req)); + ret = iso14443_3a_poller_send_standard_frame( + instance, instance->tx_buffer, instance->rx_buffer, ISO14443_3A_FDT_LISTEN_FC); + if(ret != Iso14443_3aErrorNone) { + FURI_LOG_E(TAG, "Sel request failed: %d", ret); + instance->state = Iso14443_3aPollerStateColResFailed; + ret = Iso14443_3aErrorColResFailed; + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != + sizeof(instance->col_res.sel_resp)) { + FURI_LOG_E(TAG, "Sel response wrong length"); + instance->state = Iso14443_3aPollerStateColResFailed; + ret = Iso14443_3aErrorColResFailed; + break; + } + bit_buffer_write_bytes( + instance->rx_buffer, + &instance->col_res.sel_resp, + sizeof(instance->col_res.sel_resp)); + FURI_LOG_T(TAG, "Sel resp: %02X", instance->col_res.sel_resp.sak); + if(instance->col_res.sel_req.nfcid[0] == ISO14443_3A_POLLER_SDD_CL) { + // Copy part of UID + memcpy( + &instance->data->uid[instance->data->uid_len], + &instance->col_res.sel_req.nfcid[1], + 3); + instance->data->uid_len += 3; + instance->col_res.cascade_level++; + instance->col_res.state = Iso14443_3aPollerColResStateStateNewCascade; + } else { + FURI_LOG_T(TAG, "Col resolution complete"); + instance->data->sak = instance->col_res.sel_resp.sak; + memcpy( + &instance->data->uid[instance->data->uid_len], + &instance->col_res.sel_req.nfcid[0], + 4); + instance->data->uid_len += 4; + instance->col_res.state = Iso14443_3aPollerColResStateStateSuccess; + instance->state = Iso14443_3aPollerStateActivated; + } + } + } + + activated = (instance->state == Iso14443_3aPollerStateActivated); + } while(false); + + if(activated && iso14443_3a_data) { + *iso14443_3a_data = *instance->data; + } + + return ret; +} + +Iso14443_3aError iso14443_3a_poller_txrx_custom_parity( + Iso14443_3aPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + furi_assert(tx_buffer); + furi_assert(rx_buffer); + + Iso14443_3aError ret = Iso14443_3aErrorNone; + NfcError error = + nfc_iso14443a_poller_trx_custom_parity(instance->nfc, tx_buffer, rx_buffer, fwt); + if(error != NfcErrorNone) { + ret = iso14443_3a_poller_process_error(error); + } + + return ret; +} + +Iso14443_3aError iso14443_3a_poller_txrx( + Iso14443_3aPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + furi_assert(tx_buffer); + furi_assert(rx_buffer); + + Iso14443_3aError ret = Iso14443_3aErrorNone; + NfcError error = nfc_poller_trx(instance->nfc, tx_buffer, rx_buffer, fwt); + if(error != NfcErrorNone) { + ret = iso14443_3a_poller_process_error(error); + } + + return ret; +} + +Iso14443_3aError iso14443_3a_poller_send_standard_frame( + Iso14443_3aPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + furi_assert(tx_buffer); + furi_assert(rx_buffer); + + Iso14443_3aError ret = + iso14443_3a_poller_standard_frame_exchange(instance, tx_buffer, rx_buffer, fwt); + + return ret; +} diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_i.h b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_i.h new file mode 100644 index 000000000..063ef1556 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_i.h @@ -0,0 +1,81 @@ +#pragma once + +#include "iso14443_3a_poller.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ISO14443_3A_POLLER_MAX_BUFFER_SIZE (512U) + +#define ISO14443_3A_POLLER_SEL_CMD(cascade_lvl) (0x93 + 2 * (cascade_lvl)) +#define ISO14443_3A_POLLER_SEL_PAR(bytes, bits) (((bytes) << 4 & 0xf0U) | ((bits)&0x0fU)) +#define ISO14443_3A_POLLER_SDD_CL (0x88U) + +typedef enum { + Iso14443_3aPollerColResStateStateIdle, + Iso14443_3aPollerColResStateStateNewCascade, + Iso14443_3aPollerColResStateStateSelectCascade, + Iso14443_3aPollerColResStateStateSuccess, + Iso14443_3aPollerColResStateStateFail, +} Iso14443_3aPollerColResState; + +typedef struct { + Iso14443_3aPollerColResState state; + Iso14443_3aSensResp sens_resp; + Iso14443_3aSddReq sdd_req; + Iso14443_3aSddResp sdd_resp; + Iso14443_3aSelReq sel_req; + Iso14443_3aSelResp sel_resp; + uint8_t cascade_level; +} Iso14443_3aPollerColRes; + +typedef enum { + Iso14443_3aPollerStateIdle, + Iso14443_3aPollerStateColResInProgress, + Iso14443_3aPollerStateColResFailed, + Iso14443_3aPollerStateActivated, +} Iso14443_3aPollerState; + +typedef enum { + Iso14443_3aPollerConfigStateIdle, + Iso14443_3aPollerConfigStateDone, +} Iso14443_3aPollerConfigState; + +struct Iso14443_3aPoller { + Nfc* nfc; + Iso14443_3aPollerState state; + Iso14443_3aPollerConfigState config_state; + Iso14443_3aPollerColRes col_res; + Iso14443_3aData* data; + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + + NfcGenericEvent general_event; + Iso14443_3aPollerEvent iso14443_3a_event; + Iso14443_3aPollerEventData iso14443_3a_event_data; + NfcGenericCallback callback; + void* context; +}; + +const Iso14443_3aData* iso14443_3a_poller_get_data(Iso14443_3aPoller* instance); + +Iso14443_3aError iso14443_3a_poller_check_presence(Iso14443_3aPoller* instance); + +Iso14443_3aError iso14443_3a_poller_async_activate( + Iso14443_3aPoller* instance, + Iso14443_3aData* iso14443_3a_data); + +Iso14443_3aError iso14443_3a_poller_halt(Iso14443_3aPoller* instance); + +Iso14443_3aError iso14443_3a_poller_txrx_custom_parity( + Iso14443_3aPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_sync_api.c b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_sync_api.c new file mode 100644 index 000000000..2bab1a881 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_sync_api.c @@ -0,0 +1,58 @@ +#include "iso14443_3a_poller_sync_api.h" + +#include "iso14443_3a_poller_i.h" +#include + +#include + +#define ISO14443_3A_POLLER_FLAG_COMMAND_COMPLETE (1UL << 0) + +typedef struct { + Iso14443_3aPoller* instance; + FuriThreadId thread_id; + Iso14443_3aError error; + Iso14443_3aData data; +} Iso14443_3aPollerContext; + +NfcCommand iso14443_3a_poller_read_callback(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.instance); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + + Iso14443_3aPollerContext* poller_context = context; + Iso14443_3aPoller* iso14443_3a_poller = event.instance; + Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + iso14443_3a_copy(&poller_context->data, iso14443_3a_poller->data); + } + poller_context->error = iso14443_3a_event->data->error; + + furi_thread_flags_set(poller_context->thread_id, ISO14443_3A_POLLER_FLAG_COMMAND_COMPLETE); + + return NfcCommandStop; +} + +Iso14443_3aError iso14443_3a_poller_read(Nfc* nfc, Iso14443_3aData* iso14443_3a_data) { + furi_assert(nfc); + furi_assert(iso14443_3a_data); + + Iso14443_3aPollerContext poller_context = {}; + poller_context.thread_id = furi_thread_get_current_id(); + + NfcPoller* poller = nfc_poller_alloc(nfc, NfcProtocolIso14443_3a); + nfc_poller_start(poller, iso14443_3a_poller_read_callback, &poller_context); + furi_thread_flags_wait( + ISO14443_3A_POLLER_FLAG_COMMAND_COMPLETE, FuriFlagWaitAny, FuriWaitForever); + furi_thread_flags_clear(ISO14443_3A_POLLER_FLAG_COMMAND_COMPLETE); + + nfc_poller_stop(poller); + nfc_poller_free(poller); + + if(poller_context.error == Iso14443_3aErrorNone) { + *iso14443_3a_data = poller_context.data; + } + + return poller_context.error; +} \ No newline at end of file diff --git a/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_sync_api.h b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_sync_api.h new file mode 100644 index 000000000..ed17ff432 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_sync_api.h @@ -0,0 +1,14 @@ +#pragma once + +#include "iso14443_3a.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +Iso14443_3aError iso14443_3a_poller_read(Nfc* nfc, Iso14443_3aData* iso14443_3a_data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b.c b/lib/nfc/protocols/iso14443_3b/iso14443_3b.c new file mode 100644 index 000000000..fd81e390d --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b.c @@ -0,0 +1,223 @@ +#include "iso14443_3b_i.h" + +#include +#include + +#include +#include + +#define ISO14443_3B_PROTOCOL_NAME "ISO14443-3B" +#define ISO14443_3B_DEVICE_NAME "ISO14443-3B (Unknown)" + +#define ISO14443_3B_APP_DATA_KEY "Application data" +#define ISO14443_3B_PROTOCOL_INFO_KEY "Protocol info" + +#define ISO14443_3B_FDT_POLL_DEFAULT_FC (ISO14443_3B_FDT_POLL_FC) + +const NfcDeviceBase nfc_device_iso14443_3b = { + .protocol_name = ISO14443_3B_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)iso14443_3b_alloc, + .free = (NfcDeviceFree)iso14443_3b_free, + .reset = (NfcDeviceReset)iso14443_3b_reset, + .copy = (NfcDeviceCopy)iso14443_3b_copy, + .verify = (NfcDeviceVerify)iso14443_3b_verify, + .load = (NfcDeviceLoad)iso14443_3b_load, + .save = (NfcDeviceSave)iso14443_3b_save, + .is_equal = (NfcDeviceEqual)iso14443_3b_is_equal, + .get_name = (NfcDeviceGetName)iso14443_3b_get_device_name, + .get_uid = (NfcDeviceGetUid)iso14443_3b_get_uid, + .set_uid = (NfcDeviceSetUid)iso14443_3b_set_uid, + .get_base_data = (NfcDeviceGetBaseData)iso14443_3b_get_base_data, +}; + +Iso14443_3bData* iso14443_3b_alloc() { + Iso14443_3bData* data = malloc(sizeof(Iso14443_3bData)); + return data; +} + +void iso14443_3b_free(Iso14443_3bData* data) { + furi_assert(data); + + free(data); +} + +void iso14443_3b_reset(Iso14443_3bData* data) { + memset(data, 0, sizeof(Iso14443_3bData)); +} + +void iso14443_3b_copy(Iso14443_3bData* data, const Iso14443_3bData* other) { + furi_assert(data); + furi_assert(other); + + *data = *other; +} + +bool iso14443_3b_verify(Iso14443_3bData* data, const FuriString* device_type) { + UNUSED(data); + UNUSED(device_type); + // No support for old ISO14443-3B + return false; +} + +bool iso14443_3b_load(Iso14443_3bData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + + bool parsed = false; + + do { + if(version < NFC_UNIFIED_FORMAT_VERSION) break; + + if(!flipper_format_read_hex( + ff, ISO14443_3B_APP_DATA_KEY, data->app_data, ISO14443_3B_APP_DATA_SIZE)) + break; + if(!flipper_format_read_hex( + ff, + ISO14443_3B_PROTOCOL_INFO_KEY, + (uint8_t*)&data->protocol_info, + sizeof(Iso14443_3bProtocolInfo))) + break; + + parsed = true; + } while(false); + + return parsed; +} + +bool iso14443_3b_save(const Iso14443_3bData* data, FlipperFormat* ff) { + furi_assert(data); + + bool saved = false; + + do { + if(!flipper_format_write_comment_cstr(ff, ISO14443_3B_PROTOCOL_NAME " specific data")) + break; + if(!flipper_format_write_hex( + ff, ISO14443_3B_APP_DATA_KEY, data->app_data, ISO14443_3B_APP_DATA_SIZE)) + break; + if(!flipper_format_write_hex( + ff, + ISO14443_3B_PROTOCOL_INFO_KEY, + (uint8_t*)&data->protocol_info, + sizeof(Iso14443_3bProtocolInfo))) + break; + saved = true; + } while(false); + + return saved; +} + +bool iso14443_3b_is_equal(const Iso14443_3bData* data, const Iso14443_3bData* other) { + furi_assert(data); + furi_assert(other); + + return memcmp(data, other, sizeof(Iso14443_3bData)) == 0; +} + +const char* iso14443_3b_get_device_name(const Iso14443_3bData* data, NfcDeviceNameType name_type) { + UNUSED(data); + UNUSED(name_type); + + return ISO14443_3B_DEVICE_NAME; +} + +const uint8_t* iso14443_3b_get_uid(const Iso14443_3bData* data, size_t* uid_len) { + furi_assert(data); + furi_assert(uid_len); + + *uid_len = ISO14443_3B_UID_SIZE; + return data->uid; +} + +bool iso14443_3b_set_uid(Iso14443_3bData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + const bool uid_valid = uid_len == ISO14443_3B_UID_SIZE; + + if(uid_valid) { + memcpy(data->uid, uid, uid_len); + } + + return uid_valid; +} + +Iso14443_3bData* iso14443_3b_get_base_data(const Iso14443_3bData* data) { + UNUSED(data); + furi_crash("No base data"); +} + +bool iso14443_3b_supports_iso14443_4(const Iso14443_3bData* data) { + furi_assert(data); + + return data->protocol_info.protocol_type == 0x01; +} + +bool iso14443_3b_supports_bit_rate(const Iso14443_3bData* data, Iso14443_3bBitRate bit_rate) { + furi_assert(data); + + const uint8_t capability = data->protocol_info.bit_rate_capability; + + switch(bit_rate) { + case Iso14443_3bBitRateBoth106Kbit: + return capability == ISO14443_3B_BIT_RATE_BOTH_106KBIT; + case Iso14443_3bBitRatePiccToPcd212Kbit: + return capability & ISO14443_3B_BIT_RATE_PICC_TO_PCD_212KBIT; + case Iso14443_3bBitRatePiccToPcd424Kbit: + return capability & ISO14443_3B_BIT_RATE_PICC_TO_PCD_424KBIT; + case Iso14443_3bBitRatePiccToPcd848Kbit: + return capability & ISO14443_3B_BIT_RATE_PICC_TO_PCD_848KBIT; + case Iso14443_3bBitRatePcdToPicc212Kbit: + return capability & ISO14443_3B_BIT_RATE_PCD_TO_PICC_212KBIT; + case Iso14443_3bBitRatePcdToPicc424Kbit: + return capability & ISO14443_3B_BIT_RATE_PCD_TO_PICC_424KBIT; + case Iso14443_3bBitRatePcdToPicc848Kbit: + return capability & ISO14443_3B_BIT_RATE_PCD_TO_PICC_848KBIT; + default: + return false; + } +} + +bool iso14443_3b_supports_frame_option(const Iso14443_3bData* data, Iso14443_3bFrameOption option) { + furi_assert(data); + + switch(option) { + case Iso14443_3bFrameOptionNad: + return data->protocol_info.fo & ISO14443_3B_FRAME_OPTION_NAD; + case Iso14443_3bFrameOptionCid: + return data->protocol_info.fo & ISO14443_3B_FRAME_OPTION_CID; + default: + return false; + } +} + +const uint8_t* iso14443_3b_get_application_data(const Iso14443_3bData* data, size_t* data_size) { + furi_assert(data); + furi_assert(data_size); + + *data_size = ISO14443_3B_APP_DATA_SIZE; + return data->app_data; +} + +uint16_t iso14443_3b_get_frame_size_max(const Iso14443_3bData* data) { + furi_assert(data); + + const uint8_t fs_bits = data->protocol_info.max_frame_size; + + if(fs_bits < 5) { + return fs_bits * 8 + 16; + } else if(fs_bits == 5) { + return 64; + } else if(fs_bits == 6) { + return 96; + } else if(fs_bits < 13) { + return 128U << (fs_bits - 7); + } else { + return 0; + } +} + +uint32_t iso14443_3b_get_fwt_fc_max(const Iso14443_3bData* data) { + furi_assert(data); + + const uint8_t fwi = data->protocol_info.fwi; + return fwi < 0x0F ? 4096UL << fwi : ISO14443_3B_FDT_POLL_DEFAULT_FC; +} diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b.h b/lib/nfc/protocols/iso14443_3b/iso14443_3b.h new file mode 100644 index 000000000..848e610c3 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b.h @@ -0,0 +1,83 @@ +#pragma once + +#include + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Iso14443_3bErrorNone, + Iso14443_3bErrorNotPresent, + Iso14443_3bErrorColResFailed, + Iso14443_3bErrorBufferOverflow, + Iso14443_3bErrorCommunication, + Iso14443_3bErrorFieldOff, + Iso14443_3bErrorWrongCrc, + Iso14443_3bErrorTimeout, +} Iso14443_3bError; + +typedef enum { + Iso14443_3bBitRateBoth106Kbit, + Iso14443_3bBitRatePiccToPcd212Kbit, + Iso14443_3bBitRatePiccToPcd424Kbit, + Iso14443_3bBitRatePiccToPcd848Kbit, + Iso14443_3bBitRatePcdToPicc212Kbit, + Iso14443_3bBitRatePcdToPicc424Kbit, + Iso14443_3bBitRatePcdToPicc848Kbit, +} Iso14443_3bBitRate; + +typedef enum { + Iso14443_3bFrameOptionNad, + Iso14443_3bFrameOptionCid, +} Iso14443_3bFrameOption; + +typedef struct Iso14443_3bData Iso14443_3bData; + +// Virtual methods + +Iso14443_3bData* iso14443_3b_alloc(); + +void iso14443_3b_free(Iso14443_3bData* data); + +void iso14443_3b_reset(Iso14443_3bData* data); + +void iso14443_3b_copy(Iso14443_3bData* data, const Iso14443_3bData* other); + +bool iso14443_3b_verify(Iso14443_3bData* data, const FuriString* device_type); + +bool iso14443_3b_load(Iso14443_3bData* data, FlipperFormat* ff, uint32_t version); + +bool iso14443_3b_save(const Iso14443_3bData* data, FlipperFormat* ff); + +bool iso14443_3b_is_equal(const Iso14443_3bData* data, const Iso14443_3bData* other); + +const char* iso14443_3b_get_device_name(const Iso14443_3bData* data, NfcDeviceNameType name_type); + +const uint8_t* iso14443_3b_get_uid(const Iso14443_3bData* data, size_t* uid_len); + +bool iso14443_3b_set_uid(Iso14443_3bData* data, const uint8_t* uid, size_t uid_len); + +Iso14443_3bData* iso14443_3b_get_base_data(const Iso14443_3bData* data); + +// Getters and tests + +bool iso14443_3b_supports_iso14443_4(const Iso14443_3bData* data); + +bool iso14443_3b_supports_bit_rate(const Iso14443_3bData* data, Iso14443_3bBitRate bit_rate); + +bool iso14443_3b_supports_frame_option(const Iso14443_3bData* data, Iso14443_3bFrameOption option); + +const uint8_t* iso14443_3b_get_application_data(const Iso14443_3bData* data, size_t* data_size); + +uint16_t iso14443_3b_get_frame_size_max(const Iso14443_3bData* data); + +uint32_t iso14443_3b_get_fwt_fc_max(const Iso14443_3bData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b_device_defs.h b/lib/nfc/protocols/iso14443_3b/iso14443_3b_device_defs.h new file mode 100644 index 000000000..6c33900da --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b_device_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcDeviceBase nfc_device_iso14443_3b; diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b_i.c b/lib/nfc/protocols/iso14443_3b/iso14443_3b_i.c new file mode 100644 index 000000000..cac7ed826 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b_i.c @@ -0,0 +1 @@ +#include "iso14443_3b_i.h" diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b_i.h b/lib/nfc/protocols/iso14443_3b/iso14443_3b_i.h new file mode 100644 index 000000000..f4ff36bd7 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b_i.h @@ -0,0 +1,37 @@ +#pragma once + +#include "iso14443_3b.h" + +#define ISO14443_3B_UID_SIZE (4U) +#define ISO14443_3B_APP_DATA_SIZE (4U) + +#define ISO14443_3B_GUARD_TIME_US (5000U) +#define ISO14443_3B_FDT_POLL_FC (9000U) +#define ISO14443_3B_POLL_POLL_MIN_US (1280U) + +#define ISO14443_3B_BIT_RATE_BOTH_106KBIT (0U << 0) +#define ISO14443_3B_BIT_RATE_PCD_TO_PICC_212KBIT (1U << 0) +#define ISO14443_3B_BIT_RATE_PCD_TO_PICC_424KBIT (1U << 1) +#define ISO14443_3B_BIT_RATE_PCD_TO_PICC_848KBIT (1U << 2) +#define ISO14443_3B_BIT_RATE_PICC_TO_PCD_212KBIT (1U << 4) +#define ISO14443_3B_BIT_RATE_PICC_TO_PCD_424KBIT (1U << 5) +#define ISO14443_3B_BIT_RATE_PICC_TO_PCD_848KBIT (1U << 6) +#define ISO14443_3B_BIT_RATE_BOTH_SAME_COMPULSORY (1U << 7) + +#define ISO14443_3B_FRAME_OPTION_NAD (1U << 1) +#define ISO14443_3B_FRAME_OPTION_CID (1U << 0) + +typedef struct { + uint8_t bit_rate_capability; + uint8_t protocol_type : 4; + uint8_t max_frame_size : 4; + uint8_t fo : 2; + uint8_t adc : 2; + uint8_t fwi : 4; +} Iso14443_3bProtocolInfo; + +struct Iso14443_3bData { + uint8_t uid[ISO14443_3B_UID_SIZE]; + uint8_t app_data[ISO14443_3B_APP_DATA_SIZE]; + Iso14443_3bProtocolInfo protocol_info; +}; diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller.c b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller.c new file mode 100644 index 000000000..9507f28c4 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller.c @@ -0,0 +1,121 @@ +#include "iso14443_3b_poller_i.h" + +#include + +#include + +#define TAG "ISO14443_3bPoller" + +const Iso14443_3bData* iso14443_3b_poller_get_data(Iso14443_3bPoller* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +static Iso14443_3bPoller* iso14443_3b_poller_alloc(Nfc* nfc) { + furi_assert(nfc); + + Iso14443_3bPoller* instance = malloc(sizeof(Iso14443_3bPoller)); + instance->nfc = nfc; + instance->tx_buffer = bit_buffer_alloc(ISO14443_3B_POLLER_MAX_BUFFER_SIZE); + instance->rx_buffer = bit_buffer_alloc(ISO14443_3B_POLLER_MAX_BUFFER_SIZE); + + nfc_config(instance->nfc, NfcModePoller, NfcTechIso14443b); + nfc_set_guard_time_us(instance->nfc, ISO14443_3B_GUARD_TIME_US); + nfc_set_fdt_poll_fc(instance->nfc, ISO14443_3B_FDT_POLL_FC); + nfc_set_fdt_poll_poll_us(instance->nfc, ISO14443_3B_POLL_POLL_MIN_US); + instance->data = iso14443_3b_alloc(); + + instance->iso14443_3b_event.data = &instance->iso14443_3b_event_data; + instance->general_event.protocol = NfcProtocolIso14443_3b; + instance->general_event.event_data = &instance->iso14443_3b_event; + instance->general_event.instance = instance; + + return instance; +} + +static void iso14443_3b_poller_free(Iso14443_3bPoller* instance) { + furi_assert(instance); + + furi_assert(instance->tx_buffer); + furi_assert(instance->rx_buffer); + furi_assert(instance->data); + + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + iso14443_3b_free(instance->data); + free(instance); +} + +static void iso14443_3b_poller_set_callback( + Iso14443_3bPoller* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +static NfcCommand iso14443_3b_poller_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolInvalid); + furi_assert(event.event_data); + + Iso14443_3bPoller* instance = context; + NfcEvent* nfc_event = event.event_data; + NfcCommand command = NfcCommandContinue; + + if(nfc_event->type == NfcEventTypePollerReady) { + if(instance->state != Iso14443_3bPollerStateActivated) { + Iso14443_3bError error = iso14443_3b_poller_async_activate(instance, instance->data); + if(error == Iso14443_3bErrorNone) { + instance->iso14443_3b_event.type = Iso14443_3bPollerEventTypeReady; + instance->iso14443_3b_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + } else { + instance->iso14443_3b_event.type = Iso14443_3bPollerEventTypeError; + instance->iso14443_3b_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + // Add delay to switch context + furi_delay_ms(100); + } + } else { + instance->iso14443_3b_event.type = Iso14443_3bPollerEventTypeReady; + instance->iso14443_3b_event_data.error = Iso14443_3bErrorNone; + command = instance->callback(instance->general_event, instance->context); + } + } + + return command; +} + +static bool iso14443_3b_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.instance); + furi_assert(event.protocol == NfcProtocolInvalid); + + bool protocol_detected = false; + Iso14443_3bPoller* instance = context; + NfcEvent* nfc_event = event.event_data; + furi_assert(instance->state == Iso14443_3bPollerStateIdle); + + if(nfc_event->type == NfcEventTypePollerReady) { + Iso14443_3bError error = iso14443_3b_poller_async_activate(instance, instance->data); + protocol_detected = (error == Iso14443_3bErrorNone); + } + + return protocol_detected; +} + +const NfcPollerBase nfc_poller_iso14443_3b = { + .alloc = (NfcPollerAlloc)iso14443_3b_poller_alloc, + .free = (NfcPollerFree)iso14443_3b_poller_free, + .set_callback = (NfcPollerSetCallback)iso14443_3b_poller_set_callback, + .run = (NfcPollerRun)iso14443_3b_poller_run, + .detect = (NfcPollerDetect)iso14443_3b_poller_detect, + .get_data = (NfcPollerGetData)iso14443_3b_poller_get_data, +}; diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller.h b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller.h new file mode 100644 index 000000000..d25d9dbe9 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller.h @@ -0,0 +1,30 @@ +#pragma once + +#include "iso14443_3b.h" +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso14443_3bPoller Iso14443_3bPoller; + +typedef enum { + Iso14443_3bPollerEventTypeError, + Iso14443_3bPollerEventTypeReady, +} Iso14443_3bPollerEventType; + +typedef struct { + Iso14443_3bError error; +} Iso14443_3bPollerEventData; + +typedef struct { + Iso14443_3bPollerEventType type; + Iso14443_3bPollerEventData* data; +} Iso14443_3bPollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller_defs.h b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller_defs.h new file mode 100644 index 000000000..60225310a --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcPollerBase nfc_poller_iso14443_3b; diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller_i.c b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller_i.c new file mode 100644 index 000000000..95668ccf2 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller_i.c @@ -0,0 +1,194 @@ +#include "iso14443_3b_poller_i.h" + +#include + +#define TAG "Iso14443_3bPoller" + +#define ISO14443_3B_ATTRIB_FRAME_SIZE_256 (0x08) + +static Iso14443_3bError iso14443_3b_poller_process_error(NfcError error) { + switch(error) { + case NfcErrorNone: + return Iso14443_3bErrorNone; + case NfcErrorTimeout: + return Iso14443_3bErrorTimeout; + default: + return Iso14443_3bErrorNotPresent; + } +} + +static Iso14443_3bError iso14443_3b_poller_prepare_trx(Iso14443_3bPoller* instance) { + furi_assert(instance); + + if(instance->state == Iso14443_3bPollerStateIdle) { + return iso14443_3b_poller_async_activate(instance, NULL); + } + + return Iso14443_3bErrorNone; +} + +static Iso14443_3bError iso14443_3b_poller_frame_exchange( + Iso14443_3bPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + + const size_t tx_bytes = bit_buffer_get_size_bytes(tx_buffer); + furi_assert( + tx_bytes <= bit_buffer_get_capacity_bytes(instance->tx_buffer) - ISO14443_CRC_SIZE); + + bit_buffer_copy(instance->tx_buffer, tx_buffer); + iso14443_crc_append(Iso14443CrcTypeB, instance->tx_buffer); + + Iso14443_3bError ret = Iso14443_3bErrorNone; + + do { + NfcError error = + nfc_poller_trx(instance->nfc, instance->tx_buffer, instance->rx_buffer, fwt); + if(error != NfcErrorNone) { + ret = iso14443_3b_poller_process_error(error); + break; + } + + bit_buffer_copy(rx_buffer, instance->rx_buffer); + if(!iso14443_crc_check(Iso14443CrcTypeB, instance->rx_buffer)) { + ret = Iso14443_3bErrorWrongCrc; + break; + } + + iso14443_crc_trim(rx_buffer); + } while(false); + + return ret; +} + +Iso14443_3bError + iso14443_3b_poller_async_activate(Iso14443_3bPoller* instance, Iso14443_3bData* data) { + furi_assert(instance); + furi_assert(instance->nfc); + + iso14443_3b_reset(data); + + Iso14443_3bError ret; + + do { + instance->state = Iso14443_3bPollerStateColResInProgress; + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + // Send REQB + bit_buffer_append_byte(instance->tx_buffer, 0x05); + bit_buffer_append_byte(instance->tx_buffer, 0x00); + bit_buffer_append_byte(instance->tx_buffer, 0x08); + + ret = iso14443_3b_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ISO14443_3B_FDT_POLL_FC); + if(ret != Iso14443_3bErrorNone) { + instance->state = Iso14443_3bPollerStateColResFailed; + break; + } + + typedef struct { + uint8_t flag; + uint8_t uid[ISO14443_3B_UID_SIZE]; + uint8_t app_data[ISO14443_3B_APP_DATA_SIZE]; + Iso14443_3bProtocolInfo protocol_info; + } Iso14443_3bAtqBLayout; + + if(bit_buffer_get_size_bytes(instance->rx_buffer) != sizeof(Iso14443_3bAtqBLayout)) { + FURI_LOG_D(TAG, "Unexpected REQB response"); + instance->state = Iso14443_3bPollerStateColResFailed; + ret = Iso14443_3bErrorCommunication; + break; + } + + instance->state = Iso14443_3bPollerStateActivationInProgress; + + const Iso14443_3bAtqBLayout* atqb = + (const Iso14443_3bAtqBLayout*)bit_buffer_get_data(instance->rx_buffer); + + memcpy(data->uid, atqb->uid, ISO14443_3B_UID_SIZE); + memcpy(data->app_data, atqb->app_data, ISO14443_3B_APP_DATA_SIZE); + + data->protocol_info = atqb->protocol_info; + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + // Send ATTRIB + bit_buffer_append_byte(instance->tx_buffer, 0x1d); + bit_buffer_append_bytes(instance->tx_buffer, data->uid, ISO14443_3B_UID_SIZE); + bit_buffer_append_byte(instance->tx_buffer, 0x00); + bit_buffer_append_byte(instance->tx_buffer, ISO14443_3B_ATTRIB_FRAME_SIZE_256); + bit_buffer_append_byte(instance->tx_buffer, 0x01); + bit_buffer_append_byte(instance->tx_buffer, 0x00); + + ret = iso14443_3b_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, iso14443_3b_get_fwt_fc_max(data)); + if(ret != Iso14443_3bErrorNone) { + instance->state = Iso14443_3bPollerStateActivationFailed; + break; + } + + if(bit_buffer_get_size_bytes(instance->rx_buffer) != 1 || + bit_buffer_get_byte(instance->rx_buffer, 0) != 0) { + FURI_LOG_D(TAG, "Unexpected ATTRIB response"); + instance->state = Iso14443_3bPollerStateActivationFailed; + ret = Iso14443_3bErrorCommunication; + break; + } + + instance->state = Iso14443_3bPollerStateActivated; + } while(false); + + return ret; +} + +Iso14443_3bError iso14443_3b_poller_halt(Iso14443_3bPoller* instance) { + furi_assert(instance); + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + bit_buffer_append_byte(instance->tx_buffer, 0x50); + bit_buffer_append_bytes(instance->tx_buffer, instance->data->uid, ISO14443_3B_UID_SIZE); + + Iso14443_3bError ret; + + do { + ret = iso14443_3b_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ISO14443_3B_FDT_POLL_FC); + if(ret != Iso14443_3bErrorNone) { + break; + } + + if(bit_buffer_get_size_bytes(instance->rx_buffer) != sizeof(uint8_t) || + bit_buffer_get_byte(instance->rx_buffer, 0) != 0) { + ret = Iso14443_3bErrorCommunication; + break; + } + + instance->state = Iso14443_3bPollerStateIdle; + } while(false); + + return ret; +} + +Iso14443_3bError iso14443_3b_poller_send_frame( + Iso14443_3bPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer) { + Iso14443_3bError ret; + + do { + ret = iso14443_3b_poller_prepare_trx(instance); + if(ret != Iso14443_3bErrorNone) break; + + ret = iso14443_3b_poller_frame_exchange( + instance, tx_buffer, rx_buffer, iso14443_3b_get_fwt_fc_max(instance->data)); + } while(false); + + return ret; +} diff --git a/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller_i.h b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller_i.h new file mode 100644 index 000000000..5821d6373 --- /dev/null +++ b/lib/nfc/protocols/iso14443_3b/iso14443_3b_poller_i.h @@ -0,0 +1,49 @@ +#pragma once + +#include "iso14443_3b_poller.h" +#include "iso14443_3b_i.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ISO14443_3B_POLLER_MAX_BUFFER_SIZE (256U) + +typedef enum { + Iso14443_3bPollerStateIdle, + Iso14443_3bPollerStateColResInProgress, + Iso14443_3bPollerStateColResFailed, + Iso14443_3bPollerStateActivationInProgress, + Iso14443_3bPollerStateActivationFailed, + Iso14443_3bPollerStateActivated, +} Iso14443_3bPollerState; + +struct Iso14443_3bPoller { + Nfc* nfc; + Iso14443_3bPollerState state; + Iso14443_3bData* data; + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + + NfcGenericEvent general_event; + Iso14443_3bPollerEvent iso14443_3b_event; + Iso14443_3bPollerEventData iso14443_3b_event_data; + NfcGenericCallback callback; + void* context; +}; + +const Iso14443_3bData* iso14443_3b_poller_get_data(Iso14443_3bPoller* instance); + +Iso14443_3bError + iso14443_3b_poller_async_activate(Iso14443_3bPoller* instance, Iso14443_3bData* data); + +Iso14443_3bError iso14443_3b_poller_halt(Iso14443_3bPoller* instance); + +Iso14443_3bError iso14443_3b_poller_send_frame( + Iso14443_3bPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a.c b/lib/nfc/protocols/iso14443_4a/iso14443_4a.c new file mode 100644 index 000000000..9c2a530d5 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a.c @@ -0,0 +1,300 @@ +#include "iso14443_4a_i.h" + +#include + +#define ISO14443_4A_PROTOCOL_NAME "ISO14443-4A" +#define ISO14443_4A_DEVICE_NAME "ISO14443-4A (Unknown)" + +#define ISO14443_4A_T0_KEY "T0" +#define ISO14443_4A_TA1_KEY "TA(1)" +#define ISO14443_4A_TB1_KEY "TB(1)" +#define ISO14443_4A_TC1_KEY "TC(1)" +#define ISO14443_4A_T1_TK_KEY "T1...Tk" + +#define ISO14443_4A_FDT_DEFAULT_FC ISO14443_3A_FDT_POLL_FC + +typedef enum { + Iso14443_4aInterfaceByteTA1, + Iso14443_4aInterfaceByteTB1, + Iso14443_4aInterfaceByteTC1, +} Iso14443_4aInterfaceByte; + +const NfcDeviceBase nfc_device_iso14443_4a = { + .protocol_name = ISO14443_4A_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)iso14443_4a_alloc, + .free = (NfcDeviceFree)iso14443_4a_free, + .reset = (NfcDeviceReset)iso14443_4a_reset, + .copy = (NfcDeviceCopy)iso14443_4a_copy, + .verify = (NfcDeviceVerify)iso14443_4a_verify, + .load = (NfcDeviceLoad)iso14443_4a_load, + .save = (NfcDeviceSave)iso14443_4a_save, + .is_equal = (NfcDeviceEqual)iso14443_4a_is_equal, + .get_name = (NfcDeviceGetName)iso14443_4a_get_device_name, + .get_uid = (NfcDeviceGetUid)iso14443_4a_get_uid, + .set_uid = (NfcDeviceSetUid)iso14443_4a_set_uid, + .get_base_data = (NfcDeviceGetBaseData)iso14443_4a_get_base_data, +}; + +Iso14443_4aData* iso14443_4a_alloc() { + Iso14443_4aData* data = malloc(sizeof(Iso14443_4aData)); + + data->iso14443_3a_data = iso14443_3a_alloc(); + data->ats_data.t1_tk = simple_array_alloc(&simple_array_config_uint8_t); + + return data; +} + +void iso14443_4a_free(Iso14443_4aData* data) { + furi_assert(data); + + simple_array_free(data->ats_data.t1_tk); + iso14443_3a_free(data->iso14443_3a_data); + + free(data); +} + +void iso14443_4a_reset(Iso14443_4aData* data) { + furi_assert(data); + + iso14443_3a_reset(data->iso14443_3a_data); + + data->ats_data.tl = 1; + data->ats_data.t0 = 0; + data->ats_data.ta_1 = 0; + data->ats_data.tb_1 = 0; + data->ats_data.tc_1 = 0; + + simple_array_reset(data->ats_data.t1_tk); +} + +void iso14443_4a_copy(Iso14443_4aData* data, const Iso14443_4aData* other) { + furi_assert(data); + furi_assert(other); + + iso14443_3a_copy(data->iso14443_3a_data, other->iso14443_3a_data); + + data->ats_data.tl = other->ats_data.tl; + data->ats_data.t0 = other->ats_data.t0; + data->ats_data.ta_1 = other->ats_data.ta_1; + data->ats_data.tb_1 = other->ats_data.tb_1; + data->ats_data.tc_1 = other->ats_data.tc_1; + + simple_array_copy(data->ats_data.t1_tk, other->ats_data.t1_tk); +} + +bool iso14443_4a_verify(Iso14443_4aData* data, const FuriString* device_type) { + UNUSED(data); + UNUSED(device_type); + + // Empty, unified file format only + return false; +} + +bool iso14443_4a_load(Iso14443_4aData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + + bool parsed = false; + + do { + if(!iso14443_3a_load(data->iso14443_3a_data, ff, version)) break; + + Iso14443_4aAtsData* ats_data = &data->ats_data; + + ats_data->tl = 1; + + if(flipper_format_key_exist(ff, ISO14443_4A_T0_KEY)) { + if(!flipper_format_read_hex(ff, ISO14443_4A_T0_KEY, &ats_data->t0, 1)) break; + ++ats_data->tl; + } + + if(ats_data->t0 & ISO14443_4A_ATS_T0_TA1) { + if(!flipper_format_key_exist(ff, ISO14443_4A_TA1_KEY)) break; + if(!flipper_format_read_hex(ff, ISO14443_4A_TA1_KEY, &ats_data->ta_1, 1)) break; + ++ats_data->tl; + } + if(ats_data->t0 & ISO14443_4A_ATS_T0_TB1) { + if(!flipper_format_key_exist(ff, ISO14443_4A_TB1_KEY)) break; + if(!flipper_format_read_hex(ff, ISO14443_4A_TB1_KEY, &ats_data->tb_1, 1)) break; + ++ats_data->tl; + } + if(ats_data->t0 & ISO14443_4A_ATS_T0_TC1) { + if(!flipper_format_key_exist(ff, ISO14443_4A_TC1_KEY)) break; + if(!flipper_format_read_hex(ff, ISO14443_4A_TC1_KEY, &ats_data->tc_1, 1)) break; + ++ats_data->tl; + } + + if(flipper_format_key_exist(ff, ISO14443_4A_T1_TK_KEY)) { + uint32_t t1_tk_size; + if(!flipper_format_get_value_count(ff, ISO14443_4A_T1_TK_KEY, &t1_tk_size)) break; + + if(t1_tk_size > 0) { + simple_array_init(ats_data->t1_tk, t1_tk_size); + if(!flipper_format_read_hex( + ff, + ISO14443_4A_T1_TK_KEY, + simple_array_get_data(ats_data->t1_tk), + t1_tk_size)) + break; + ats_data->tl += t1_tk_size; + } + } + parsed = true; + } while(false); + + return parsed; +} + +bool iso14443_4a_save(const Iso14443_4aData* data, FlipperFormat* ff) { + furi_assert(data); + + bool saved = false; + + do { + if(!iso14443_3a_save(data->iso14443_3a_data, ff)) break; + if(!flipper_format_write_comment_cstr(ff, ISO14443_4A_PROTOCOL_NAME " specific data")) + break; + + const Iso14443_4aAtsData* ats_data = &data->ats_data; + + if(ats_data->tl > 1) { + if(!flipper_format_write_hex(ff, ISO14443_4A_T0_KEY, &ats_data->t0, 1)) break; + + if(ats_data->t0 & ISO14443_4A_ATS_T0_TA1) { + if(!flipper_format_write_hex(ff, ISO14443_4A_TA1_KEY, &ats_data->ta_1, 1)) break; + } + if(ats_data->t0 & ISO14443_4A_ATS_T0_TB1) { + if(!flipper_format_write_hex(ff, ISO14443_4A_TB1_KEY, &ats_data->tb_1, 1)) break; + } + if(ats_data->t0 & ISO14443_4A_ATS_T0_TC1) { + if(!flipper_format_write_hex(ff, ISO14443_4A_TC1_KEY, &ats_data->tc_1, 1)) break; + } + + const uint32_t t1_tk_size = simple_array_get_count(ats_data->t1_tk); + if(t1_tk_size > 0) { + if(!flipper_format_write_hex( + ff, + ISO14443_4A_T1_TK_KEY, + simple_array_cget_data(ats_data->t1_tk), + t1_tk_size)) + break; + } + } + saved = true; + } while(false); + + return saved; +} + +bool iso14443_4a_is_equal(const Iso14443_4aData* data, const Iso14443_4aData* other) { + return iso14443_3a_is_equal(data->iso14443_3a_data, other->iso14443_3a_data); +} + +const char* iso14443_4a_get_device_name(const Iso14443_4aData* data, NfcDeviceNameType name_type) { + UNUSED(data); + UNUSED(name_type); + return ISO14443_4A_DEVICE_NAME; +} + +const uint8_t* iso14443_4a_get_uid(const Iso14443_4aData* data, size_t* uid_len) { + return iso14443_3a_get_uid(data->iso14443_3a_data, uid_len); +} + +bool iso14443_4a_set_uid(Iso14443_4aData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + return iso14443_3a_set_uid(data->iso14443_3a_data, uid, uid_len); +} + +Iso14443_3aData* iso14443_4a_get_base_data(const Iso14443_4aData* data) { + furi_assert(data); + + return data->iso14443_3a_data; +} + +uint16_t iso14443_4a_get_frame_size_max(const Iso14443_4aData* data) { + furi_assert(data); + + const uint8_t fsci = data->ats_data.t0 & 0x0F; + + if(fsci < 5) { + return fsci * 8 + 16; + } else if(fsci == 5) { + return 64; + } else if(fsci == 6) { + return 96; + } else if(fsci < 13) { + return 128U << (fsci - 7); + } else { + return 0; + } +} + +uint32_t iso14443_4a_get_fwt_fc_max(const Iso14443_4aData* data) { + furi_assert(data); + + uint32_t fwt_fc_max = ISO14443_4A_FDT_DEFAULT_FC; + + do { + if(!(data->ats_data.tl > 1)) break; + if(!(data->ats_data.t0 & ISO14443_4A_ATS_T0_TB1)) break; + + const uint8_t fwi = data->ats_data.tb_1 >> 4; + if(fwi == 0x0F) break; + + fwt_fc_max = 4096UL << fwi; + } while(false); + + return fwt_fc_max; +} + +const uint8_t* iso14443_4a_get_historical_bytes(const Iso14443_4aData* data, uint32_t* count) { + furi_assert(data); + furi_assert(count); + + *count = simple_array_get_count(data->ats_data.t1_tk); + return simple_array_cget_data(data->ats_data.t1_tk); +} + +bool iso14443_4a_supports_bit_rate(const Iso14443_4aData* data, Iso14443_4aBitRate bit_rate) { + furi_assert(data); + + if(!(data->ats_data.t0 & ISO14443_4A_ATS_T0_TA1)) + return bit_rate == Iso14443_4aBitRateBoth106Kbit; + + const uint8_t ta_1 = data->ats_data.ta_1; + + switch(bit_rate) { + case Iso14443_4aBitRateBoth106Kbit: + return ta_1 == ISO14443_4A_ATS_TA1_BOTH_SAME_COMPULSORY; + case Iso14443_4aBitRatePiccToPcd212Kbit: + return ta_1 & ISO14443_4A_ATS_TA1_PCD_TO_PICC_212KBIT; + case Iso14443_4aBitRatePiccToPcd424Kbit: + return ta_1 & ISO14443_4A_ATS_TA1_PCD_TO_PICC_424KBIT; + case Iso14443_4aBitRatePiccToPcd848Kbit: + return ta_1 & ISO14443_4A_ATS_TA1_PCD_TO_PICC_848KBIT; + case Iso14443_4aBitRatePcdToPicc212Kbit: + return ta_1 & ISO14443_4A_ATS_TA1_PICC_TO_PCD_212KBIT; + case Iso14443_4aBitRatePcdToPicc424Kbit: + return ta_1 & ISO14443_4A_ATS_TA1_PICC_TO_PCD_424KBIT; + case Iso14443_4aBitRatePcdToPicc848Kbit: + return ta_1 & ISO14443_4A_ATS_TA1_PICC_TO_PCD_848KBIT; + default: + return false; + } +} + +bool iso14443_4a_supports_frame_option(const Iso14443_4aData* data, Iso14443_4aFrameOption option) { + furi_assert(data); + + const Iso14443_4aAtsData* ats_data = &data->ats_data; + if(!(ats_data->t0 & ISO14443_4A_ATS_T0_TC1)) return false; + + switch(option) { + case Iso14443_4aFrameOptionNad: + return ats_data->tc_1 & ISO14443_4A_ATS_TC1_NAD; + case Iso14443_4aFrameOptionCid: + return ats_data->tc_1 & ISO14443_4A_ATS_TC1_CID; + default: + return false; + } +} diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a.h b/lib/nfc/protocols/iso14443_4a/iso14443_4a.h new file mode 100644 index 000000000..9580c1404 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a.h @@ -0,0 +1,73 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Iso14443_4aErrorNone, + Iso14443_4aErrorNotPresent, + Iso14443_4aErrorProtocol, + Iso14443_4aErrorTimeout, +} Iso14443_4aError; + +typedef enum { + Iso14443_4aBitRateBoth106Kbit, + Iso14443_4aBitRatePiccToPcd212Kbit, + Iso14443_4aBitRatePiccToPcd424Kbit, + Iso14443_4aBitRatePiccToPcd848Kbit, + Iso14443_4aBitRatePcdToPicc212Kbit, + Iso14443_4aBitRatePcdToPicc424Kbit, + Iso14443_4aBitRatePcdToPicc848Kbit, +} Iso14443_4aBitRate; + +typedef enum { + Iso14443_4aFrameOptionNad, + Iso14443_4aFrameOptionCid, +} Iso14443_4aFrameOption; + +typedef struct Iso14443_4aData Iso14443_4aData; + +// Virtual methods + +Iso14443_4aData* iso14443_4a_alloc(); + +void iso14443_4a_free(Iso14443_4aData* data); + +void iso14443_4a_reset(Iso14443_4aData* data); + +void iso14443_4a_copy(Iso14443_4aData* data, const Iso14443_4aData* other); + +bool iso14443_4a_verify(Iso14443_4aData* data, const FuriString* device_type); + +bool iso14443_4a_load(Iso14443_4aData* data, FlipperFormat* ff, uint32_t version); + +bool iso14443_4a_save(const Iso14443_4aData* data, FlipperFormat* ff); + +bool iso14443_4a_is_equal(const Iso14443_4aData* data, const Iso14443_4aData* other); + +const char* iso14443_4a_get_device_name(const Iso14443_4aData* data, NfcDeviceNameType name_type); + +const uint8_t* iso14443_4a_get_uid(const Iso14443_4aData* data, size_t* uid_len); + +bool iso14443_4a_set_uid(Iso14443_4aData* data, const uint8_t* uid, size_t uid_len); + +Iso14443_3aData* iso14443_4a_get_base_data(const Iso14443_4aData* data); + +// Getters & Tests + +uint16_t iso14443_4a_get_frame_size_max(const Iso14443_4aData* data); + +uint32_t iso14443_4a_get_fwt_fc_max(const Iso14443_4aData* data); + +const uint8_t* iso14443_4a_get_historical_bytes(const Iso14443_4aData* data, uint32_t* count); + +bool iso14443_4a_supports_bit_rate(const Iso14443_4aData* data, Iso14443_4aBitRate bit_rate); + +bool iso14443_4a_supports_frame_option(const Iso14443_4aData* data, Iso14443_4aFrameOption option); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_device_defs.h b/lib/nfc/protocols/iso14443_4a/iso14443_4a_device_defs.h new file mode 100644 index 000000000..db372f810 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_device_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcDeviceBase nfc_device_iso14443_4a; diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_i.c b/lib/nfc/protocols/iso14443_4a/iso14443_4a_i.c new file mode 100644 index 000000000..f6e3acc5c --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_i.c @@ -0,0 +1,71 @@ +#include "iso14443_4a_i.h" + +bool iso14443_4a_ats_parse(Iso14443_4aAtsData* data, const BitBuffer* buf) { + bool can_parse = false; + + do { + const size_t buf_size = bit_buffer_get_size_bytes(buf); + if(buf_size == 0) break; + + size_t current_index = 0; + + const uint8_t tl = bit_buffer_get_byte(buf, current_index++); + if(tl != buf_size) break; + + data->tl = tl; + + if(tl > 1) { + const uint8_t t0 = bit_buffer_get_byte(buf, current_index++); + + const bool has_ta_1 = t0 & ISO14443_4A_ATS_T0_TA1; + const bool has_tb_1 = t0 & ISO14443_4A_ATS_T0_TB1; + const bool has_tc_1 = t0 & ISO14443_4A_ATS_T0_TC1; + + const uint8_t buf_size_min = + 2 + (has_ta_1 ? 1 : 0) + (has_tb_1 ? 1 : 0) + (has_tc_1 ? 1 : 0); + + if(buf_size < buf_size_min) break; + + data->t0 = t0; + + if(has_ta_1) { + data->ta_1 = bit_buffer_get_byte(buf, current_index++); + } + if(has_tb_1) { + data->tb_1 = bit_buffer_get_byte(buf, current_index++); + } + if(has_tc_1) { + data->tc_1 = bit_buffer_get_byte(buf, current_index++); + } + + const uint8_t t1_tk_size = buf_size - buf_size_min; + + if(t1_tk_size > 0) { + simple_array_init(data->t1_tk, t1_tk_size); + bit_buffer_write_bytes_mid( + buf, simple_array_get_data(data->t1_tk), current_index, t1_tk_size); + } + } + + can_parse = true; + } while(false); + + return can_parse; +} + +Iso14443_4aError iso14443_4a_process_error(Iso14443_3aError error) { + switch(error) { + case Iso14443_3aErrorNone: + return Iso14443_4aErrorNone; + case Iso14443_3aErrorNotPresent: + return Iso14443_4aErrorNotPresent; + case Iso14443_3aErrorColResFailed: + case Iso14443_3aErrorCommunication: + case Iso14443_3aErrorWrongCrc: + return Iso14443_4aErrorProtocol; + case Iso14443_3aErrorTimeout: + return Iso14443_4aErrorTimeout; + default: + return Iso14443_4aErrorProtocol; + } +} diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_i.h b/lib/nfc/protocols/iso14443_4a/iso14443_4a_i.h new file mode 100644 index 000000000..e45fb90cc --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_i.h @@ -0,0 +1,42 @@ +#pragma once + +#include "iso14443_4a.h" + +#include + +#define ISO14443_4A_CMD_READ_ATS (0xE0) + +// ATS bit definitions +#define ISO14443_4A_ATS_T0_TA1 (1U << 4) +#define ISO14443_4A_ATS_T0_TB1 (1U << 5) +#define ISO14443_4A_ATS_T0_TC1 (1U << 6) + +#define ISO14443_4A_ATS_TA1_BOTH_106KBIT (0U << 0) +#define ISO14443_4A_ATS_TA1_PCD_TO_PICC_212KBIT (1U << 0) +#define ISO14443_4A_ATS_TA1_PCD_TO_PICC_424KBIT (1U << 1) +#define ISO14443_4A_ATS_TA1_PCD_TO_PICC_848KBIT (1U << 2) +#define ISO14443_4A_ATS_TA1_PICC_TO_PCD_212KBIT (1U << 4) +#define ISO14443_4A_ATS_TA1_PICC_TO_PCD_424KBIT (1U << 5) +#define ISO14443_4A_ATS_TA1_PICC_TO_PCD_848KBIT (1U << 6) +#define ISO14443_4A_ATS_TA1_BOTH_SAME_COMPULSORY (1U << 7) + +#define ISO14443_4A_ATS_TC1_NAD (1U << 0) +#define ISO14443_4A_ATS_TC1_CID (1U << 1) + +typedef struct { + uint8_t tl; + uint8_t t0; + uint8_t ta_1; + uint8_t tb_1; + uint8_t tc_1; + SimpleArray* t1_tk; +} Iso14443_4aAtsData; + +struct Iso14443_4aData { + Iso14443_3aData* iso14443_3a_data; + Iso14443_4aAtsData ats_data; +}; + +bool iso14443_4a_ats_parse(Iso14443_4aAtsData* data, const BitBuffer* buf); + +Iso14443_4aError iso14443_4a_process_error(Iso14443_3aError error); diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener.c b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener.c new file mode 100644 index 000000000..95612bf54 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener.c @@ -0,0 +1,99 @@ +#include "iso14443_4a_listener_i.h" + +#include +#include + +#define TAG "Iso14443_4aListener" + +#define ISO14443_4A_LISTENER_BUF_SIZE (256U) + +static Iso14443_4aListener* + iso14443_4a_listener_alloc(Iso14443_3aListener* iso14443_3a_listener, Iso14443_4aData* data) { + furi_assert(iso14443_3a_listener); + + Iso14443_4aListener* instance = malloc(sizeof(Iso14443_4aListener)); + instance->iso14443_3a_listener = iso14443_3a_listener; + instance->data = data; + + instance->tx_buffer = bit_buffer_alloc(ISO14443_4A_LISTENER_BUF_SIZE); + + instance->iso14443_4a_event.data = &instance->iso14443_4a_event_data; + instance->generic_event.protocol = NfcProtocolIso14443_4a; + instance->generic_event.instance = instance; + instance->generic_event.event_data = &instance->iso14443_4a_event; + + return instance; +} + +static void iso14443_4a_listener_free(Iso14443_4aListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + furi_assert(instance->tx_buffer); + + bit_buffer_free(instance->tx_buffer); + free(instance); +} + +static void iso14443_4a_listener_set_callback( + Iso14443_4aListener* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + + instance->callback = callback; + instance->context = context; +} + +static const Iso14443_4aData* iso14443_4a_listener_get_data(Iso14443_4aListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +static NfcCommand iso14443_4a_listener_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + furi_assert(event.event_data); + + Iso14443_4aListener* instance = context; + Iso14443_3aListenerEvent* iso14443_3a_event = event.event_data; + BitBuffer* rx_buffer = iso14443_3a_event->data->buffer; + NfcCommand command = NfcCommandContinue; + + if(iso14443_3a_event->type == Iso14443_3aListenerEventTypeReceivedStandardFrame) { + if(instance->state == Iso14443_4aListenerStateIdle) { + if(bit_buffer_get_size_bytes(rx_buffer) == 2 && + bit_buffer_get_byte(rx_buffer, 0) == ISO14443_4A_CMD_READ_ATS) { + if(iso14443_4a_listener_send_ats(instance, &instance->data->ats_data) != + Iso14443_4aErrorNone) { + command = NfcCommandContinue; + } else { + instance->state = Iso14443_4aListenerStateActive; + } + } + } else { + instance->iso14443_4a_event.type = Iso14443_4aListenerEventTypeReceivedData; + instance->iso14443_4a_event.data->buffer = rx_buffer; + + if(instance->callback) { + command = instance->callback(instance->generic_event, instance->context); + } + } + } else if( + iso14443_3a_event->type == Iso14443_3aListenerEventTypeHalted || + iso14443_3a_event->type == Iso14443_3aListenerEventTypeFieldOff) { + instance->state = Iso14443_4aListenerStateIdle; + command = NfcCommandContinue; + } + + return command; +} + +const NfcListenerBase nfc_listener_iso14443_4a = { + .alloc = (NfcListenerAlloc)iso14443_4a_listener_alloc, + .free = (NfcListenerFree)iso14443_4a_listener_free, + .set_callback = (NfcListenerSetCallback)iso14443_4a_listener_set_callback, + .get_data = (NfcListenerGetData)iso14443_4a_listener_get_data, + .run = (NfcListenerRun)iso14443_4a_listener_run, +}; diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener.h b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener.h new file mode 100644 index 000000000..ba649847b --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +#include "iso14443_4a.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso14443_4aListener Iso14443_4aListener; + +typedef enum { + Iso14443_4aListenerEventTypeHalted, + Iso14443_4aListenerEventTypeReceivedData, +} Iso14443_4aListenerEventType; + +typedef struct { + BitBuffer* buffer; +} Iso14443_4aListenerEventData; + +typedef struct { + Iso14443_4aListenerEventType type; + Iso14443_4aListenerEventData* data; +} Iso14443_4aListenerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener_defs.h b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener_defs.h new file mode 100644 index 000000000..ef70a5e14 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcListenerBase nfc_listener_iso14443_4a; diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener_i.c b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener_i.c new file mode 100644 index 000000000..8590c22ad --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener_i.c @@ -0,0 +1,32 @@ +#include "iso14443_4a_listener_i.h" + +#include + +Iso14443_4aError + iso14443_4a_listener_send_ats(Iso14443_4aListener* instance, const Iso14443_4aAtsData* data) { + bit_buffer_reset(instance->tx_buffer); + bit_buffer_append_byte(instance->tx_buffer, data->tl); + + if(data->tl > 1) { + bit_buffer_append_byte(instance->tx_buffer, data->t0); + if(data->t0 & ISO14443_4A_ATS_T0_TA1) { + bit_buffer_append_byte(instance->tx_buffer, data->ta_1); + } + if(data->t0 & ISO14443_4A_ATS_T0_TB1) { + bit_buffer_append_byte(instance->tx_buffer, data->tb_1); + } + if(data->t0 & ISO14443_4A_ATS_T0_TC1) { + bit_buffer_append_byte(instance->tx_buffer, data->tc_1); + } + + const uint32_t t1_tk_size = simple_array_get_count(data->t1_tk); + if(t1_tk_size != 0) { + bit_buffer_append_bytes( + instance->tx_buffer, simple_array_cget_data(data->t1_tk), t1_tk_size); + } + } + + const Iso14443_3aError error = iso14443_3a_listener_send_standard_frame( + instance->iso14443_3a_listener, instance->tx_buffer); + return iso14443_4a_process_error(error); +} diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener_i.h b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener_i.h new file mode 100644 index 000000000..d4e884f6f --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_listener_i.h @@ -0,0 +1,36 @@ +#pragma once + +#include + +#include "iso14443_4a_listener.h" +#include "iso14443_4a_i.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Iso14443_4aListenerStateIdle, + Iso14443_4aListenerStateActive, +} Iso14443_4aListenerState; + +struct Iso14443_4aListener { + Iso14443_3aListener* iso14443_3a_listener; + Iso14443_4aData* data; + Iso14443_4aListenerState state; + + BitBuffer* tx_buffer; + + NfcGenericEvent generic_event; + Iso14443_4aListenerEvent iso14443_4a_event; + Iso14443_4aListenerEventData iso14443_4a_event_data; + NfcGenericCallback callback; + void* context; +}; + +Iso14443_4aError + iso14443_4a_listener_send_ats(Iso14443_4aListener* instance, const Iso14443_4aAtsData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller.c b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller.c new file mode 100644 index 000000000..c07cc6b7f --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller.c @@ -0,0 +1,154 @@ +#include "iso14443_4a_poller_i.h" + +#include + +#include + +#define TAG "Iso14443_4aPoller" + +#define ISO14443_4A_POLLER_BUF_SIZE (256U) + +typedef NfcCommand (*Iso14443_4aPollerStateHandler)(Iso14443_4aPoller* instance); + +const Iso14443_4aData* iso14443_4a_poller_get_data(Iso14443_4aPoller* instance) { + furi_assert(instance); + + return instance->data; +} + +static Iso14443_4aPoller* iso14443_4a_poller_alloc(Iso14443_3aPoller* iso14443_3a_poller) { + Iso14443_4aPoller* instance = malloc(sizeof(Iso14443_4aPoller)); + instance->iso14443_3a_poller = iso14443_3a_poller; + instance->data = iso14443_4a_alloc(); + instance->iso14443_4_layer = iso14443_4_layer_alloc(); + instance->tx_buffer = bit_buffer_alloc(ISO14443_4A_POLLER_BUF_SIZE); + instance->rx_buffer = bit_buffer_alloc(ISO14443_4A_POLLER_BUF_SIZE); + + instance->iso14443_4a_event.data = &instance->iso14443_4a_event_data; + + instance->general_event.protocol = NfcProtocolIso14443_4a; + instance->general_event.event_data = &instance->iso14443_4a_event; + instance->general_event.instance = instance; + + return instance; +} + +static void iso14443_4a_poller_free(Iso14443_4aPoller* instance) { + furi_assert(instance); + + iso14443_4a_free(instance->data); + iso14443_4_layer_free(instance->iso14443_4_layer); + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + free(instance); +} + +static NfcCommand iso14443_4a_poller_handler_idle(Iso14443_4aPoller* instance) { + iso14443_3a_copy( + instance->data->iso14443_3a_data, + iso14443_3a_poller_get_data(instance->iso14443_3a_poller)); + + iso14443_4_layer_reset(instance->iso14443_4_layer); + + instance->poller_state = Iso14443_4aPollerStateReadAts; + return NfcCommandContinue; +} + +static NfcCommand iso14443_4a_poller_handler_read_ats(Iso14443_4aPoller* instance) { + Iso14443_4aError error = + iso14443_4a_poller_async_read_ats(instance, &instance->data->ats_data); + if(error == Iso14443_4aErrorNone) { + FURI_LOG_D(TAG, "Read ATS success"); + instance->poller_state = Iso14443_4aPollerStateReady; + } else { + FURI_LOG_D(TAG, "Failed to read ATS"); + instance->poller_state = Iso14443_4aPollerStateError; + } + + return NfcCommandContinue; +} + +static NfcCommand iso14443_4a_poller_handler_error(Iso14443_4aPoller* instance) { + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + instance->iso14443_4a_event_data.error = instance->error; + NfcCommand command = instance->callback(instance->general_event, instance->context); + instance->poller_state = Iso14443_4aPollerStateIdle; + return command; +} + +static NfcCommand iso14443_4a_poller_handler_ready(Iso14443_4aPoller* instance) { + instance->iso14443_4a_event.type = Iso14443_4aPollerEventTypeReady; + NfcCommand command = instance->callback(instance->general_event, instance->context); + return command; +} + +static const Iso14443_4aPollerStateHandler + iso14443_4a_poller_state_handler[Iso14443_4aPollerStateNum] = { + [Iso14443_4aPollerStateIdle] = iso14443_4a_poller_handler_idle, + [Iso14443_4aPollerStateReadAts] = iso14443_4a_poller_handler_read_ats, + [Iso14443_4aPollerStateError] = iso14443_4a_poller_handler_error, + [Iso14443_4aPollerStateReady] = iso14443_4a_poller_handler_ready, +}; + +static void iso14443_4a_poller_set_callback( + Iso14443_4aPoller* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +static NfcCommand iso14443_4a_poller_run(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_3a); + + Iso14443_4aPoller* instance = context; + furi_assert(instance); + furi_assert(instance->callback); + + Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + furi_assert(iso14443_3a_event); + + NfcCommand command = NfcCommandContinue; + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + command = iso14443_4a_poller_state_handler[instance->poller_state](instance); + } else if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeError) { + instance->iso14443_4a_event.type = Iso14443_4aPollerEventTypeError; + command = instance->callback(instance->general_event, instance->context); + } + + return command; +} + +static bool iso14443_4a_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_3a); + + const Iso14443_4aPoller* instance = context; + furi_assert(instance); + + const Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + furi_assert(iso14443_3a_event); + iso14443_3a_copy( + instance->data->iso14443_3a_data, + iso14443_3a_poller_get_data(instance->iso14443_3a_poller)); + + bool protocol_detected = false; + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + protocol_detected = iso14443_3a_supports_iso14443_4(instance->data->iso14443_3a_data); + } + + return protocol_detected; +} + +const NfcPollerBase nfc_poller_iso14443_4a = { + .alloc = (NfcPollerAlloc)iso14443_4a_poller_alloc, + .free = (NfcPollerFree)iso14443_4a_poller_free, + .set_callback = (NfcPollerSetCallback)iso14443_4a_poller_set_callback, + .run = (NfcPollerRun)iso14443_4a_poller_run, + .detect = (NfcPollerDetect)iso14443_4a_poller_detect, + .get_data = (NfcPollerGetData)iso14443_4a_poller_get_data, +}; diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller.h b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller.h new file mode 100644 index 000000000..b224299e0 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +#include "iso14443_4a.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso14443_4aPoller Iso14443_4aPoller; + +typedef enum { + Iso14443_4aPollerEventTypeError, + Iso14443_4aPollerEventTypeReady, +} Iso14443_4aPollerEventType; + +typedef struct { + Iso14443_4aError error; +} Iso14443_4aPollerEventData; + +typedef struct { + Iso14443_4aPollerEventType type; + Iso14443_4aPollerEventData* data; +} Iso14443_4aPollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller_defs.h b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller_defs.h new file mode 100644 index 000000000..aa6216674 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcPollerBase nfc_poller_iso14443_4a; diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller_i.c b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller_i.c new file mode 100644 index 000000000..7221e2aa9 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller_i.c @@ -0,0 +1,83 @@ +#include "iso14443_4a_poller_i.h" + +#include + +#include "iso14443_4a_i.h" + +#define TAG "Iso14443_4aPoller" + +#define ISO14443_4A_FSDI_256 (0x8U) + +Iso14443_4aError iso14443_4a_poller_halt(Iso14443_4aPoller* instance) { + furi_assert(instance); + + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + instance->poller_state = Iso14443_4aPollerStateIdle; + + return Iso14443_4aErrorNone; +} + +Iso14443_4aError + iso14443_4a_poller_async_read_ats(Iso14443_4aPoller* instance, Iso14443_4aAtsData* data) { + furi_assert(instance); + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_append_byte(instance->tx_buffer, ISO14443_4A_CMD_READ_ATS); + bit_buffer_append_byte(instance->tx_buffer, ISO14443_4A_FSDI_256 << 4); + + Iso14443_4aError error = Iso14443_4aErrorNone; + + do { + const Iso14443_3aError iso14443_3a_error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + ISO14443_4A_POLLER_ATS_FWT_FC); + + if(iso14443_3a_error != Iso14443_3aErrorNone) { + FURI_LOG_E(TAG, "ATS request failed"); + error = iso14443_4a_process_error(iso14443_3a_error); + break; + + } else if(!iso14443_4a_ats_parse(data, instance->rx_buffer)) { + FURI_LOG_E(TAG, "Failed to parse ATS response"); + error = Iso14443_4aErrorProtocol; + break; + } + + } while(false); + + return error; +} + +Iso14443_4aError iso14443_4a_poller_send_block( + Iso14443_4aPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer) { + furi_assert(instance); + + bit_buffer_reset(instance->tx_buffer); + iso14443_4_layer_encode_block(instance->iso14443_4_layer, tx_buffer, instance->tx_buffer); + + Iso14443_4aError error = Iso14443_4aErrorNone; + + do { + Iso14443_3aError iso14443_3a_error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + iso14443_4a_get_fwt_fc_max(instance->data)); + + if(iso14443_3a_error != Iso14443_3aErrorNone) { + error = iso14443_4a_process_error(iso14443_3a_error); + break; + + } else if(!iso14443_4_layer_decode_block( + instance->iso14443_4_layer, rx_buffer, instance->rx_buffer)) { + error = Iso14443_4aErrorProtocol; + break; + } + } while(false); + + return error; +} diff --git a/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller_i.h b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller_i.h new file mode 100644 index 000000000..ce878cb40 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4a/iso14443_4a_poller_i.h @@ -0,0 +1,60 @@ +#pragma once + +#include +#include + +#include "iso14443_4a_poller.h" +#include "iso14443_4a_i.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ISO14443_4A_POLLER_ATS_FWT_FC (40000) + +typedef enum { + Iso14443_4aPollerStateIdle, + Iso14443_4aPollerStateReadAts, + Iso14443_4aPollerStateError, + Iso14443_4aPollerStateReady, + + Iso14443_4aPollerStateNum, +} Iso14443_4aPollerState; + +typedef enum { + Iso14443_4aPollerSessionStateIdle, + Iso14443_4aPollerSessionStateActive, + Iso14443_4aPollerSessionStateStopRequest, +} Iso14443_4aPollerSessionState; + +struct Iso14443_4aPoller { + Iso14443_3aPoller* iso14443_3a_poller; + Iso14443_4aPollerState poller_state; + Iso14443_4aPollerSessionState session_state; + Iso14443_4aError error; + Iso14443_4aData* data; + Iso14443_4Layer* iso14443_4_layer; + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + Iso14443_4aPollerEventData iso14443_4a_event_data; + Iso14443_4aPollerEvent iso14443_4a_event; + NfcGenericEvent general_event; + NfcGenericCallback callback; + void* context; +}; + +const Iso14443_4aData* iso14443_4a_poller_get_data(Iso14443_4aPoller* instance); + +Iso14443_4aError iso14443_4a_poller_halt(Iso14443_4aPoller* instance); + +Iso14443_4aError + iso14443_4a_poller_async_read_ats(Iso14443_4aPoller* instance, Iso14443_4aAtsData* data); + +Iso14443_4aError iso14443_4a_poller_send_block( + Iso14443_4aPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b.c b/lib/nfc/protocols/iso14443_4b/iso14443_4b.c new file mode 100644 index 000000000..19f2939da --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b.c @@ -0,0 +1,94 @@ +#include "iso14443_4b_i.h" + +#include +#include + +#define ISO14443_4B_PROTOCOL_NAME "ISO14443-4B" +#define ISO14443_4B_DEVICE_NAME "ISO14443-4B (Unknown)" + +const NfcDeviceBase nfc_device_iso14443_4b = { + .protocol_name = ISO14443_4B_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)iso14443_4b_alloc, + .free = (NfcDeviceFree)iso14443_4b_free, + .reset = (NfcDeviceReset)iso14443_4b_reset, + .copy = (NfcDeviceCopy)iso14443_4b_copy, + .verify = (NfcDeviceVerify)iso14443_4b_verify, + .load = (NfcDeviceLoad)iso14443_4b_load, + .save = (NfcDeviceSave)iso14443_4b_save, + .is_equal = (NfcDeviceEqual)iso14443_4b_is_equal, + .get_name = (NfcDeviceGetName)iso14443_4b_get_device_name, + .get_uid = (NfcDeviceGetUid)iso14443_4b_get_uid, + .set_uid = (NfcDeviceSetUid)iso14443_4b_set_uid, + .get_base_data = (NfcDeviceGetBaseData)iso14443_4b_get_base_data, +}; + +Iso14443_4bData* iso14443_4b_alloc() { + Iso14443_4bData* data = malloc(sizeof(Iso14443_4bData)); + + data->iso14443_3b_data = iso14443_3b_alloc(); + return data; +} + +void iso14443_4b_free(Iso14443_4bData* data) { + furi_assert(data); + + iso14443_3b_free(data->iso14443_3b_data); + free(data); +} + +void iso14443_4b_reset(Iso14443_4bData* data) { + furi_assert(data); + + iso14443_3b_reset(data->iso14443_3b_data); +} + +void iso14443_4b_copy(Iso14443_4bData* data, const Iso14443_4bData* other) { + furi_assert(data); + furi_assert(other); + + iso14443_3b_copy(data->iso14443_3b_data, other->iso14443_3b_data); +} + +bool iso14443_4b_verify(Iso14443_4bData* data, const FuriString* device_type) { + UNUSED(data); + UNUSED(device_type); + + // Empty, unified file format only + return false; +} + +bool iso14443_4b_load(Iso14443_4bData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + return iso14443_3b_load(data->iso14443_3b_data, ff, version); +} + +bool iso14443_4b_save(const Iso14443_4bData* data, FlipperFormat* ff) { + furi_assert(data); + return iso14443_3b_save(data->iso14443_3b_data, ff); +} + +bool iso14443_4b_is_equal(const Iso14443_4bData* data, const Iso14443_4bData* other) { + return iso14443_3b_is_equal(data->iso14443_3b_data, other->iso14443_3b_data); +} + +const char* iso14443_4b_get_device_name(const Iso14443_4bData* data, NfcDeviceNameType name_type) { + UNUSED(data); + UNUSED(name_type); + return ISO14443_4B_DEVICE_NAME; +} + +const uint8_t* iso14443_4b_get_uid(const Iso14443_4bData* data, size_t* uid_len) { + return iso14443_3b_get_uid(data->iso14443_3b_data, uid_len); +} + +bool iso14443_4b_set_uid(Iso14443_4bData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + return iso14443_3b_set_uid(data->iso14443_3b_data, uid, uid_len); +} + +Iso14443_3bData* iso14443_4b_get_base_data(const Iso14443_4bData* data) { + furi_assert(data); + + return data->iso14443_3b_data; +} diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b.h b/lib/nfc/protocols/iso14443_4b/iso14443_4b.h new file mode 100644 index 000000000..1f269ed91 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b.h @@ -0,0 +1,46 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Iso14443_4bErrorNone, + Iso14443_4bErrorNotPresent, + Iso14443_4bErrorProtocol, + Iso14443_4bErrorTimeout, +} Iso14443_4bError; + +typedef struct Iso14443_4bData Iso14443_4bData; + +// Virtual methods + +Iso14443_4bData* iso14443_4b_alloc(); + +void iso14443_4b_free(Iso14443_4bData* data); + +void iso14443_4b_reset(Iso14443_4bData* data); + +void iso14443_4b_copy(Iso14443_4bData* data, const Iso14443_4bData* other); + +bool iso14443_4b_verify(Iso14443_4bData* data, const FuriString* device_type); + +bool iso14443_4b_load(Iso14443_4bData* data, FlipperFormat* ff, uint32_t version); + +bool iso14443_4b_save(const Iso14443_4bData* data, FlipperFormat* ff); + +bool iso14443_4b_is_equal(const Iso14443_4bData* data, const Iso14443_4bData* other); + +const char* iso14443_4b_get_device_name(const Iso14443_4bData* data, NfcDeviceNameType name_type); + +const uint8_t* iso14443_4b_get_uid(const Iso14443_4bData* data, size_t* uid_len); + +bool iso14443_4b_set_uid(Iso14443_4bData* data, const uint8_t* uid, size_t uid_len); + +Iso14443_3bData* iso14443_4b_get_base_data(const Iso14443_4bData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b_device_defs.h b/lib/nfc/protocols/iso14443_4b/iso14443_4b_device_defs.h new file mode 100644 index 000000000..8185c9aee --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b_device_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcDeviceBase nfc_device_iso14443_4b; diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b_i.c b/lib/nfc/protocols/iso14443_4b/iso14443_4b_i.c new file mode 100644 index 000000000..1df880640 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b_i.c @@ -0,0 +1,18 @@ +#include "iso14443_4b_i.h" + +Iso14443_4bError iso14443_4b_process_error(Iso14443_3bError error) { + switch(error) { + case Iso14443_3bErrorNone: + return Iso14443_4bErrorNone; + case Iso14443_3bErrorNotPresent: + return Iso14443_4bErrorNotPresent; + case Iso14443_3bErrorColResFailed: + case Iso14443_3bErrorCommunication: + case Iso14443_3bErrorWrongCrc: + return Iso14443_4bErrorProtocol; + case Iso14443_3bErrorTimeout: + return Iso14443_4bErrorTimeout; + default: + return Iso14443_4bErrorProtocol; + } +} diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b_i.h b/lib/nfc/protocols/iso14443_4b/iso14443_4b_i.h new file mode 100644 index 000000000..6090c0393 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b_i.h @@ -0,0 +1,9 @@ +#pragma once + +#include "iso14443_4b.h" + +struct Iso14443_4bData { + Iso14443_3bData* iso14443_3b_data; +}; + +Iso14443_4bError iso14443_4b_process_error(Iso14443_3bError error); diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller.c b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller.c new file mode 100644 index 000000000..1030ebfb6 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller.c @@ -0,0 +1,138 @@ +#include "iso14443_4b_poller_i.h" + +#include + +#include + +#define TAG "Iso14443_4bPoller" + +#define ISO14443_4A_POLLER_BUF_SIZE (256U) + +typedef NfcCommand (*Iso14443_4bPollerStateHandler)(Iso14443_4bPoller* instance); + +const Iso14443_4bData* iso14443_4b_poller_get_data(Iso14443_4bPoller* instance) { + furi_assert(instance); + + return instance->data; +} + +static Iso14443_4bPoller* iso14443_4b_poller_alloc(Iso14443_3bPoller* iso14443_3b_poller) { + Iso14443_4bPoller* instance = malloc(sizeof(Iso14443_4bPoller)); + instance->iso14443_3b_poller = iso14443_3b_poller; + instance->data = iso14443_4b_alloc(); + instance->iso14443_4_layer = iso14443_4_layer_alloc(); + instance->tx_buffer = bit_buffer_alloc(ISO14443_4A_POLLER_BUF_SIZE); + instance->rx_buffer = bit_buffer_alloc(ISO14443_4A_POLLER_BUF_SIZE); + + instance->iso14443_4b_event.data = &instance->iso14443_4b_event_data; + + instance->general_event.protocol = NfcProtocolIso14443_4b; + instance->general_event.event_data = &instance->iso14443_4b_event; + instance->general_event.instance = instance; + + return instance; +} + +static void iso14443_4b_poller_free(Iso14443_4bPoller* instance) { + furi_assert(instance); + + iso14443_4b_free(instance->data); + iso14443_4_layer_free(instance->iso14443_4_layer); + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + free(instance); +} + +static NfcCommand iso14443_4b_poller_handler_idle(Iso14443_4bPoller* instance) { + iso14443_3b_copy( + instance->data->iso14443_3b_data, + iso14443_3b_poller_get_data(instance->iso14443_3b_poller)); + + iso14443_4_layer_reset(instance->iso14443_4_layer); + instance->poller_state = Iso14443_4bPollerStateReady; + return NfcCommandContinue; +} + +static NfcCommand iso14443_4b_poller_handler_error(Iso14443_4bPoller* instance) { + iso14443_3b_poller_halt(instance->iso14443_3b_poller); + instance->iso14443_4b_event_data.error = instance->error; + NfcCommand command = instance->callback(instance->general_event, instance->context); + instance->poller_state = Iso14443_4bPollerStateIdle; + return command; +} + +static NfcCommand iso14443_4b_poller_handler_ready(Iso14443_4bPoller* instance) { + instance->iso14443_4b_event.type = Iso14443_4bPollerEventTypeReady; + NfcCommand command = instance->callback(instance->general_event, instance->context); + return command; +} + +static const Iso14443_4bPollerStateHandler + iso14443_4b_poller_state_handler[Iso14443_4bPollerStateNum] = { + [Iso14443_4bPollerStateIdle] = iso14443_4b_poller_handler_idle, + [Iso14443_4bPollerStateError] = iso14443_4b_poller_handler_error, + [Iso14443_4bPollerStateReady] = iso14443_4b_poller_handler_ready, +}; + +static void iso14443_4b_poller_set_callback( + Iso14443_4bPoller* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +static NfcCommand iso14443_4b_poller_run(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_3b); + + Iso14443_4bPoller* instance = context; + furi_assert(instance); + furi_assert(instance->callback); + + Iso14443_3bPollerEvent* iso14443_3b_event = event.event_data; + furi_assert(iso14443_3b_event); + + NfcCommand command = NfcCommandContinue; + + if(iso14443_3b_event->type == Iso14443_3bPollerEventTypeReady) { + command = iso14443_4b_poller_state_handler[instance->poller_state](instance); + } else if(iso14443_3b_event->type == Iso14443_3bPollerEventTypeError) { + instance->iso14443_4b_event.type = Iso14443_4bPollerEventTypeError; + command = instance->callback(instance->general_event, instance->context); + } + + return command; +} + +static bool iso14443_4b_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_3b); + + const Iso14443_4bPoller* instance = context; + furi_assert(instance); + + const Iso14443_3bPollerEvent* iso14443_3b_event = event.event_data; + furi_assert(iso14443_3b_event); + iso14443_3b_copy( + instance->data->iso14443_3b_data, + iso14443_3b_poller_get_data(instance->iso14443_3b_poller)); + + bool protocol_detected = false; + + if(iso14443_3b_event->type == Iso14443_3bPollerEventTypeReady) { + protocol_detected = iso14443_3b_supports_iso14443_4(instance->data->iso14443_3b_data); + } + + return protocol_detected; +} + +const NfcPollerBase nfc_poller_iso14443_4b = { + .alloc = (NfcPollerAlloc)iso14443_4b_poller_alloc, + .free = (NfcPollerFree)iso14443_4b_poller_free, + .set_callback = (NfcPollerSetCallback)iso14443_4b_poller_set_callback, + .run = (NfcPollerRun)iso14443_4b_poller_run, + .detect = (NfcPollerDetect)iso14443_4b_poller_detect, + .get_data = (NfcPollerGetData)iso14443_4b_poller_get_data, +}; diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller.h b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller.h new file mode 100644 index 000000000..e60090c04 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +#include "iso14443_4b.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso14443_4bPoller Iso14443_4bPoller; + +typedef enum { + Iso14443_4bPollerEventTypeError, + Iso14443_4bPollerEventTypeReady, +} Iso14443_4bPollerEventType; + +typedef struct { + Iso14443_4bError error; +} Iso14443_4bPollerEventData; + +typedef struct { + Iso14443_4bPollerEventType type; + Iso14443_4bPollerEventData* data; +} Iso14443_4bPollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller_defs.h b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller_defs.h new file mode 100644 index 000000000..4388f2cf8 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcPollerBase nfc_poller_iso14443_4b; diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller_i.c b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller_i.c new file mode 100644 index 000000000..82de1d538 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller_i.c @@ -0,0 +1,45 @@ +#include "iso14443_4b_poller_i.h" + +#include + +#include "iso14443_4b_i.h" + +#define TAG "Iso14443_4bPoller" + +Iso14443_4bError iso14443_4b_poller_halt(Iso14443_4bPoller* instance) { + furi_assert(instance); + + iso14443_3b_poller_halt(instance->iso14443_3b_poller); + instance->poller_state = Iso14443_4bPollerStateIdle; + + return Iso14443_4bErrorNone; +} + +Iso14443_4bError iso14443_4b_poller_send_block( + Iso14443_4bPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer) { + furi_assert(instance); + + bit_buffer_reset(instance->tx_buffer); + iso14443_4_layer_encode_block(instance->iso14443_4_layer, tx_buffer, instance->tx_buffer); + + Iso14443_4bError error = Iso14443_4bErrorNone; + + do { + Iso14443_3bError iso14443_3b_error = iso14443_3b_poller_send_frame( + instance->iso14443_3b_poller, instance->tx_buffer, instance->rx_buffer); + + if(iso14443_3b_error != Iso14443_3bErrorNone) { + error = iso14443_4b_process_error(iso14443_3b_error); + break; + + } else if(!iso14443_4_layer_decode_block( + instance->iso14443_4_layer, rx_buffer, instance->rx_buffer)) { + error = Iso14443_4bErrorProtocol; + break; + } + } while(false); + + return error; +} diff --git a/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller_i.h b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller_i.h new file mode 100644 index 000000000..bd55c6188 --- /dev/null +++ b/lib/nfc/protocols/iso14443_4b/iso14443_4b_poller_i.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include + +#include "iso14443_4b_poller.h" +#include "iso14443_4b_i.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Iso14443_4bPollerStateIdle, + Iso14443_4bPollerStateError, + Iso14443_4bPollerStateReady, + + Iso14443_4bPollerStateNum, +} Iso14443_4bPollerState; + +typedef enum { + Iso14443_4bPollerSessionStateIdle, + Iso14443_4bPollerSessionStateActive, + Iso14443_4bPollerSessionStateStopRequest, +} Iso14443_4bPollerSessionState; + +struct Iso14443_4bPoller { + Iso14443_3bPoller* iso14443_3b_poller; + Iso14443_4bPollerState poller_state; + Iso14443_4bPollerSessionState session_state; + Iso14443_4bError error; + Iso14443_4bData* data; + Iso14443_4Layer* iso14443_4_layer; + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + Iso14443_4bPollerEventData iso14443_4b_event_data; + Iso14443_4bPollerEvent iso14443_4b_event; + NfcGenericEvent general_event; + NfcGenericCallback callback; + void* context; +}; + +const Iso14443_4bData* iso14443_4b_poller_get_data(Iso14443_4bPoller* instance); + +Iso14443_4bError iso14443_4b_poller_halt(Iso14443_4bPoller* instance); + +Iso14443_4bError iso14443_4b_poller_send_block( + Iso14443_4bPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3.c b/lib/nfc/protocols/iso15693_3/iso15693_3.c new file mode 100644 index 000000000..3203cbad0 --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3.c @@ -0,0 +1,358 @@ +#include "iso15693_3.h" +#include "iso15693_3_device_defs.h" + +#include + +#define ISO15693_3_PROTOCOL_NAME "ISO15693-3" +#define ISO15693_3_PROTOCOL_NAME_LEGACY "ISO15693" +#define ISO15693_3_DEVICE_NAME "ISO15693-3 (Unknown)" + +#define ISO15693_3_LOCK_DSFID_LEGACY (1U << 0) +#define ISO15693_3_LOCK_AFI_LEGACY (1U << 1) + +#define ISO15693_3_DSFID_KEY "DSFID" +#define ISO15693_3_AFI_KEY "AFI" +#define ISO15693_3_IC_REF_KEY "IC Reference" +#define ISO15693_3_BLOCK_COUNT_KEY "Block Count" +#define ISO15693_3_BLOCK_SIZE_KEY "Block Size" +#define ISO15693_3_DATA_CONTENT_KEY "Data Content" +#define ISO15693_3_LOCK_DSFID_KEY "Lock DSFID" +#define ISO15693_3_LOCK_AFI_KEY "Lock AFI" +#define ISO15693_3_SECURITY_STATUS_KEY "Security Status" + +const NfcDeviceBase nfc_device_iso15693_3 = { + .protocol_name = ISO15693_3_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)iso15693_3_alloc, + .free = (NfcDeviceFree)iso15693_3_free, + .reset = (NfcDeviceReset)iso15693_3_reset, + .copy = (NfcDeviceCopy)iso15693_3_copy, + .verify = (NfcDeviceVerify)iso15693_3_verify, + .load = (NfcDeviceLoad)iso15693_3_load, + .save = (NfcDeviceSave)iso15693_3_save, + .is_equal = (NfcDeviceEqual)iso15693_3_is_equal, + .get_name = (NfcDeviceGetName)iso15693_3_get_device_name, + .get_uid = (NfcDeviceGetUid)iso15693_3_get_uid, + .set_uid = (NfcDeviceSetUid)iso15693_3_set_uid, + .get_base_data = (NfcDeviceGetBaseData)iso15693_3_get_base_data, +}; + +Iso15693_3Data* iso15693_3_alloc() { + Iso15693_3Data* data = malloc(sizeof(Iso15693_3Data)); + + data->block_data = simple_array_alloc(&simple_array_config_uint8_t); + data->block_security = simple_array_alloc(&simple_array_config_uint8_t); + + return data; +} + +void iso15693_3_free(Iso15693_3Data* data) { + furi_assert(data); + + simple_array_free(data->block_data); + simple_array_free(data->block_security); + free(data); +} + +void iso15693_3_reset(Iso15693_3Data* data) { + furi_assert(data); + + memset(data->uid, 0, ISO15693_3_UID_SIZE); + memset(&data->system_info, 0, sizeof(Iso15693_3SystemInfo)); + memset(&data->settings, 0, sizeof(Iso15693_3Settings)); + + simple_array_reset(data->block_data); + simple_array_reset(data->block_security); +} + +void iso15693_3_copy(Iso15693_3Data* data, const Iso15693_3Data* other) { + furi_assert(data); + furi_assert(other); + + memcpy(data->uid, other->uid, ISO15693_3_UID_SIZE); + + data->system_info = other->system_info; + data->settings = other->settings; + + simple_array_copy(data->block_data, other->block_data); + simple_array_copy(data->block_security, other->block_security); +} + +bool iso15693_3_verify(Iso15693_3Data* data, const FuriString* device_type) { + UNUSED(data); + return furi_string_equal(device_type, ISO15693_3_PROTOCOL_NAME_LEGACY); +} + +static inline bool iso15693_3_load_security_legacy(Iso15693_3Data* data, FlipperFormat* ff) { + bool loaded = false; + uint8_t* legacy_data = NULL; + + do { + uint32_t value_count; + if(!flipper_format_get_value_count(ff, ISO15693_3_SECURITY_STATUS_KEY, &value_count)) + break; + if(simple_array_get_count(data->block_security) + 1 != value_count) break; + + legacy_data = malloc(value_count); + if(!flipper_format_read_hex(ff, ISO15693_3_SECURITY_STATUS_KEY, legacy_data, value_count)) + break; + + // First legacy data byte is lock bits + data->settings.lock_bits.dsfid = legacy_data[0] & ISO15693_3_LOCK_DSFID_LEGACY; + data->settings.lock_bits.afi = legacy_data[0] & ISO15693_3_LOCK_AFI_LEGACY; + + // The rest are block security + memcpy( + &legacy_data[1], + simple_array_get_data(data->block_security), + simple_array_get_count(data->block_security)); + + loaded = true; + } while(false); + + if(legacy_data) free(legacy_data); + + return loaded; +} + +static inline bool iso15693_3_load_security(Iso15693_3Data* data, FlipperFormat* ff) { + bool loaded = false; + + do { + uint32_t value_count; + if(!flipper_format_get_value_count(ff, ISO15693_3_SECURITY_STATUS_KEY, &value_count)) + break; + if(simple_array_get_count(data->block_security) != value_count) break; + if(!flipper_format_read_hex( + ff, + ISO15693_3_SECURITY_STATUS_KEY, + simple_array_get_data(data->block_security), + simple_array_get_count(data->block_security))) + break; + + loaded = true; + } while(false); + + return loaded; +} + +bool iso15693_3_load(Iso15693_3Data* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + UNUSED(version); + + bool loaded = false; + + do { + if(flipper_format_key_exist(ff, ISO15693_3_DSFID_KEY)) { + if(!flipper_format_read_hex(ff, ISO15693_3_DSFID_KEY, &data->system_info.dsfid, 1)) + break; + data->system_info.flags |= ISO15693_3_SYSINFO_FLAG_DSFID; + } + + if(flipper_format_key_exist(ff, ISO15693_3_AFI_KEY)) { + if(!flipper_format_read_hex(ff, ISO15693_3_AFI_KEY, &data->system_info.afi, 1)) break; + data->system_info.flags |= ISO15693_3_SYSINFO_FLAG_AFI; + } + + if(flipper_format_key_exist(ff, ISO15693_3_IC_REF_KEY)) { + if(!flipper_format_read_hex(ff, ISO15693_3_IC_REF_KEY, &data->system_info.ic_ref, 1)) + break; + data->system_info.flags |= ISO15693_3_SYSINFO_FLAG_IC_REF; + } + + const bool has_lock_bits = flipper_format_key_exist(ff, ISO15693_3_LOCK_DSFID_KEY) && + flipper_format_key_exist(ff, ISO15693_3_LOCK_AFI_KEY); + if(has_lock_bits) { + Iso15693_3LockBits* lock_bits = &data->settings.lock_bits; + if(!flipper_format_read_bool(ff, ISO15693_3_LOCK_DSFID_KEY, &lock_bits->dsfid, 1)) + break; + if(!flipper_format_read_bool(ff, ISO15693_3_LOCK_AFI_KEY, &lock_bits->afi, 1)) break; + } + + if(flipper_format_key_exist(ff, ISO15693_3_BLOCK_COUNT_KEY) && + flipper_format_key_exist(ff, ISO15693_3_BLOCK_SIZE_KEY)) { + uint32_t block_count; + if(!flipper_format_read_uint32(ff, ISO15693_3_BLOCK_COUNT_KEY, &block_count, 1)) break; + + data->system_info.block_count = block_count; + data->system_info.flags |= ISO15693_3_SYSINFO_FLAG_MEMORY; + + if(!flipper_format_read_hex( + ff, ISO15693_3_BLOCK_SIZE_KEY, &(data->system_info.block_size), 1)) + break; + + simple_array_init( + data->block_data, data->system_info.block_size * data->system_info.block_count); + + if(!flipper_format_read_hex( + ff, + ISO15693_3_DATA_CONTENT_KEY, + simple_array_get_data(data->block_data), + simple_array_get_count(data->block_data))) + break; + + if(flipper_format_key_exist(ff, ISO15693_3_SECURITY_STATUS_KEY)) { + simple_array_init(data->block_security, data->system_info.block_count); + + const bool security_loaded = has_lock_bits ? + iso15693_3_load_security(data, ff) : + iso15693_3_load_security_legacy(data, ff); + if(!security_loaded) break; + } + } + + loaded = true; + } while(false); + + return loaded; +} + +bool iso15693_3_save(const Iso15693_3Data* data, FlipperFormat* ff) { + furi_assert(data); + + bool saved = false; + + do { + if(!flipper_format_write_comment_cstr(ff, ISO15693_3_PROTOCOL_NAME " specific data")) + break; + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_DSFID) { + if(!flipper_format_write_comment_cstr(ff, "Data Storage Format Identifier")) break; + if(!flipper_format_write_hex(ff, ISO15693_3_DSFID_KEY, &data->system_info.dsfid, 1)) + break; + } + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_AFI) { + if(!flipper_format_write_comment_cstr(ff, "Application Family Identifier")) break; + if(!flipper_format_write_hex(ff, ISO15693_3_AFI_KEY, &data->system_info.afi, 1)) break; + } + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_IC_REF) { + if(!flipper_format_write_comment_cstr(ff, "IC Reference - Vendor specific meaning")) + break; + if(!flipper_format_write_hex(ff, ISO15693_3_IC_REF_KEY, &data->system_info.ic_ref, 1)) + break; + } + + if(!flipper_format_write_comment_cstr(ff, "Lock Bits")) break; + if(!flipper_format_write_bool( + ff, ISO15693_3_LOCK_DSFID_KEY, &data->settings.lock_bits.dsfid, 1)) + break; + if(!flipper_format_write_bool( + ff, ISO15693_3_LOCK_AFI_KEY, &data->settings.lock_bits.afi, 1)) + break; + + if(data->system_info.flags & ISO15693_3_SYSINFO_FLAG_MEMORY) { + const uint32_t block_count = data->system_info.block_count; + if(!flipper_format_write_comment_cstr( + ff, "Number of memory blocks, valid range = 1..256")) + break; + if(!flipper_format_write_uint32(ff, ISO15693_3_BLOCK_COUNT_KEY, &block_count, 1)) + break; + + if(!flipper_format_write_comment_cstr( + ff, "Size of a single memory block, valid range = 01...20 (hex)")) + break; + if(!flipper_format_write_hex( + ff, ISO15693_3_BLOCK_SIZE_KEY, &data->system_info.block_size, 1)) + break; + + if(!flipper_format_write_hex( + ff, + ISO15693_3_DATA_CONTENT_KEY, + simple_array_cget_data(data->block_data), + simple_array_get_count(data->block_data))) + break; + + if(!flipper_format_write_comment_cstr( + ff, "Block Security Status: 01 = locked, 00 = not locked")) + break; + if(!flipper_format_write_hex( + ff, + ISO15693_3_SECURITY_STATUS_KEY, + simple_array_cget_data(data->block_security), + simple_array_get_count(data->block_security))) + break; + } + saved = true; + } while(false); + + return saved; +} + +bool iso15693_3_is_equal(const Iso15693_3Data* data, const Iso15693_3Data* other) { + furi_assert(data); + furi_assert(other); + + return memcmp(data->uid, other->uid, ISO15693_3_UID_SIZE) == 0 && + memcmp(&data->settings, &other->settings, sizeof(Iso15693_3Settings)) == 0 && + memcmp(&data->system_info, &other->system_info, sizeof(Iso15693_3SystemInfo)) == 0 && + simple_array_is_equal(data->block_data, other->block_data) && + simple_array_is_equal(data->block_security, other->block_security); +} + +const char* iso15693_3_get_device_name(const Iso15693_3Data* data, NfcDeviceNameType name_type) { + UNUSED(data); + UNUSED(name_type); + + return ISO15693_3_DEVICE_NAME; +} + +const uint8_t* iso15693_3_get_uid(const Iso15693_3Data* data, size_t* uid_len) { + furi_assert(data); + + if(uid_len) *uid_len = ISO15693_3_UID_SIZE; + return data->uid; +} + +bool iso15693_3_set_uid(Iso15693_3Data* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + furi_assert(uid); + + bool uid_valid = uid_len == ISO15693_3_UID_SIZE; + + if(uid_valid) { + memcpy(data->uid, uid, uid_len); + // All ISO15693-3 cards must have this as first UID byte + data->uid[0] = 0xe0; + } + + return uid_valid; +} + +Iso15693_3Data* iso15693_3_get_base_data(const Iso15693_3Data* data) { + UNUSED(data); + furi_crash("No base data"); +} + +bool iso15693_3_is_block_locked(const Iso15693_3Data* data, uint8_t block_index) { + furi_assert(data); + furi_assert(block_index < data->system_info.block_count); + + return *(const uint8_t*)simple_array_cget(data->block_security, block_index); +} + +uint8_t iso15693_3_get_manufacturer_id(const Iso15693_3Data* data) { + furi_assert(data); + + return data->uid[1]; +} + +uint16_t iso15693_3_get_block_count(const Iso15693_3Data* data) { + furi_assert(data); + + return data->system_info.block_count; +} + +uint8_t iso15693_3_get_block_size(const Iso15693_3Data* data) { + furi_assert(data); + + return data->system_info.block_size; +} + +const uint8_t* iso15693_3_get_block_data(const Iso15693_3Data* data, uint8_t block_index) { + furi_assert(data); + furi_assert(data->system_info.block_count > block_index); + + return (const uint8_t*)simple_array_cget( + data->block_data, block_index * data->system_info.block_size); +} diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3.h b/lib/nfc/protocols/iso15693_3/iso15693_3.h new file mode 100644 index 000000000..5d4158ab9 --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3.h @@ -0,0 +1,163 @@ +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ISO15693_3_UID_SIZE (8U) + +#define ISO15693_3_GUARD_TIME_US (5000U) +#define ISO15693_3_FDT_POLL_FC (4202U) +#define ISO15693_3_FDT_LISTEN_FC (4320U) +#define ISO15693_3_POLL_POLL_MIN_US (1500U) + +#define ISO15693_3_REQ_FLAG_SUBCARRIER_1 (0U << 0) +#define ISO15693_3_REQ_FLAG_SUBCARRIER_2 (1U << 0) +#define ISO15693_3_REQ_FLAG_DATA_RATE_LO (0U << 1) +#define ISO15693_3_REQ_FLAG_DATA_RATE_HI (1U << 1) +#define ISO15693_3_REQ_FLAG_INVENTORY_T4 (0U << 2) +#define ISO15693_3_REQ_FLAG_INVENTORY_T5 (1U << 2) +#define ISO15693_3_REQ_FLAG_EXTENSION (1U << 3) + +#define ISO15693_3_REQ_FLAG_T4_SELECTED (1U << 4) +#define ISO15693_3_REQ_FLAG_T4_ADDRESSED (1U << 5) +#define ISO15693_3_REQ_FLAG_T4_OPTION (1U << 6) + +#define ISO15693_3_REQ_FLAG_T5_AFI_PRESENT (1U << 4) +#define ISO15693_3_REQ_FLAG_T5_N_SLOTS_16 (0U << 5) +#define ISO15693_3_REQ_FLAG_T5_N_SLOTS_1 (1U << 5) +#define ISO15693_3_REQ_FLAG_T5_OPTION (1U << 6) + +#define ISO15693_3_RESP_FLAG_NONE (0U) +#define ISO15693_3_RESP_FLAG_ERROR (1U << 0) +#define ISO15693_3_RESP_FLAG_EXTENSION (1U << 3) + +#define ISO15693_3_RESP_ERROR_NOT_SUPPORTED (0x01U) +#define ISO15693_3_RESP_ERROR_FORMAT (0x02U) +#define ISO15693_3_RESP_ERROR_OPTION (0x03U) +#define ISO15693_3_RESP_ERROR_UNKNOWN (0x0FU) +#define ISO15693_3_RESP_ERROR_BLOCK_UNAVAILABLE (0x10U) +#define ISO15693_3_RESP_ERROR_BLOCK_ALREADY_LOCKED (0x11U) +#define ISO15693_3_RESP_ERROR_BLOCK_LOCKED (0x12U) +#define ISO15693_3_RESP_ERROR_BLOCK_WRITE (0x13U) +#define ISO15693_3_RESP_ERROR_BLOCK_LOCK (0x14U) +#define ISO15693_3_RESP_ERROR_CUSTOM_START (0xA0U) +#define ISO15693_3_RESP_ERROR_CUSTOM_END (0xDFU) + +#define ISO15693_3_CMD_MANDATORY_START (0x01U) +#define ISO15693_3_CMD_INVENTORY (0x01U) +#define ISO15693_3_CMD_STAY_QUIET (0x02U) +#define ISO15693_3_CMD_MANDATORY_RFU (0x03U) +#define ISO15693_3_CMD_OPTIONAL_START (0x20U) +#define ISO15693_3_CMD_READ_BLOCK (0x20U) +#define ISO15693_3_CMD_WRITE_BLOCK (0x21U) +#define ISO15693_3_CMD_LOCK_BLOCK (0x22U) +#define ISO15693_3_CMD_READ_MULTI_BLOCKS (0x23U) +#define ISO15693_3_CMD_WRITE_MULTI_BLOCKS (0x24U) +#define ISO15693_3_CMD_SELECT (0x25U) +#define ISO15693_3_CMD_RESET_TO_READY (0x26U) +#define ISO15693_3_CMD_WRITE_AFI (0x27U) +#define ISO15693_3_CMD_LOCK_AFI (0x28U) +#define ISO15693_3_CMD_WRITE_DSFID (0x29U) +#define ISO15693_3_CMD_LOCK_DSFID (0x2AU) +#define ISO15693_3_CMD_GET_SYS_INFO (0x2BU) +#define ISO15693_3_CMD_GET_BLOCKS_SECURITY (0x2CU) +#define ISO15693_3_CMD_OPTIONAL_RFU (0x2DU) +#define ISO15693_3_CMD_CUSTOM_START (0xA0U) + +#define ISO15693_3_MANDATORY_COUNT (ISO15693_3_CMD_MANDATORY_RFU - ISO15693_3_CMD_MANDATORY_START) +#define ISO15693_3_OPTIONAL_COUNT (ISO15693_3_CMD_OPTIONAL_RFU - ISO15693_3_CMD_OPTIONAL_START) + +#define ISO15693_3_SYSINFO_FLAG_DSFID (1U << 0) +#define ISO15693_3_SYSINFO_FLAG_AFI (1U << 1) +#define ISO15693_3_SYSINFO_FLAG_MEMORY (1U << 2) +#define ISO15693_3_SYSINFO_FLAG_IC_REF (1U << 3) + +typedef enum { + Iso15693_3ErrorNone, + Iso15693_3ErrorNotPresent, + Iso15693_3ErrorBufferEmpty, + Iso15693_3ErrorBufferOverflow, + Iso15693_3ErrorFieldOff, + Iso15693_3ErrorWrongCrc, + Iso15693_3ErrorTimeout, + Iso15693_3ErrorFormat, + Iso15693_3ErrorIgnore, + Iso15693_3ErrorNotSupported, + Iso15693_3ErrorUidMismatch, + Iso15693_3ErrorFullyHandled, + Iso15693_3ErrorUnexpectedResponse, + Iso15693_3ErrorInternal, + Iso15693_3ErrorCustom, + Iso15693_3ErrorUnknown, +} Iso15693_3Error; + +typedef struct { + uint8_t flags; + uint8_t dsfid; + uint8_t afi; + uint8_t ic_ref; + uint16_t block_count; + uint8_t block_size; +} Iso15693_3SystemInfo; + +typedef struct { + bool dsfid; + bool afi; +} Iso15693_3LockBits; + +typedef struct { + Iso15693_3LockBits lock_bits; +} Iso15693_3Settings; + +typedef struct { + uint8_t uid[ISO15693_3_UID_SIZE]; + Iso15693_3SystemInfo system_info; + Iso15693_3Settings settings; + SimpleArray* block_data; + SimpleArray* block_security; +} Iso15693_3Data; + +Iso15693_3Data* iso15693_3_alloc(); + +void iso15693_3_free(Iso15693_3Data* data); + +void iso15693_3_reset(Iso15693_3Data* data); + +void iso15693_3_copy(Iso15693_3Data* data, const Iso15693_3Data* other); + +bool iso15693_3_verify(Iso15693_3Data* data, const FuriString* device_type); + +bool iso15693_3_load(Iso15693_3Data* data, FlipperFormat* ff, uint32_t version); + +bool iso15693_3_save(const Iso15693_3Data* data, FlipperFormat* ff); + +bool iso15693_3_is_equal(const Iso15693_3Data* data, const Iso15693_3Data* other); + +const char* iso15693_3_get_device_name(const Iso15693_3Data* data, NfcDeviceNameType name_type); + +const uint8_t* iso15693_3_get_uid(const Iso15693_3Data* data, size_t* uid_len); + +bool iso15693_3_set_uid(Iso15693_3Data* data, const uint8_t* uid, size_t uid_len); + +Iso15693_3Data* iso15693_3_get_base_data(const Iso15693_3Data* data); + +// Getters and tests + +bool iso15693_3_is_block_locked(const Iso15693_3Data* data, uint8_t block_index); + +uint8_t iso15693_3_get_manufacturer_id(const Iso15693_3Data* data); + +uint16_t iso15693_3_get_block_count(const Iso15693_3Data* data); + +uint8_t iso15693_3_get_block_size(const Iso15693_3Data* data); + +const uint8_t* iso15693_3_get_block_data(const Iso15693_3Data* data, uint8_t block_index); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_device_defs.h b/lib/nfc/protocols/iso15693_3/iso15693_3_device_defs.h new file mode 100644 index 000000000..69a73476e --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_device_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcDeviceBase nfc_device_iso15693_3; diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_i.c b/lib/nfc/protocols/iso15693_3/iso15693_3_i.c new file mode 100644 index 000000000..3d8d95c3a --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_i.c @@ -0,0 +1,263 @@ +#include "iso15693_3_i.h" + +bool iso15693_3_error_response_parse(Iso15693_3Error* error, const BitBuffer* buf) { + furi_assert(error); + + if(bit_buffer_get_size_bytes(buf) == 0) { + // YEET! + *error = Iso15693_3ErrorBufferEmpty; + return true; + } + + typedef struct { + uint8_t flags; + uint8_t error; + } ErrorResponseLayout; + + const ErrorResponseLayout* resp = (const ErrorResponseLayout*)bit_buffer_get_data(buf); + + if((resp->flags & ISO15693_3_RESP_FLAG_ERROR) == 0) { + // No error flag is set, the data does not contain an error frame + return false; + } else if(bit_buffer_get_size_bytes(buf) < sizeof(ErrorResponseLayout)) { + // Error bit is set, but not enough data to determine the error + *error = Iso15693_3ErrorUnexpectedResponse; + return true; + } else if( + resp->error >= ISO15693_3_RESP_ERROR_CUSTOM_START && + resp->error <= ISO15693_3_RESP_ERROR_CUSTOM_END) { + // Custom vendor-specific error, must be checked in the respective protocol implementation + *error = Iso15693_3ErrorCustom; + return true; + } + + switch(resp->error) { + case ISO15693_3_RESP_ERROR_NOT_SUPPORTED: + case ISO15693_3_RESP_ERROR_OPTION: + *error = Iso15693_3ErrorNotSupported; + break; + case ISO15693_3_RESP_ERROR_FORMAT: + *error = Iso15693_3ErrorFormat; + break; + case ISO15693_3_RESP_ERROR_BLOCK_UNAVAILABLE: + case ISO15693_3_RESP_ERROR_BLOCK_ALREADY_LOCKED: + case ISO15693_3_RESP_ERROR_BLOCK_LOCKED: + case ISO15693_3_RESP_ERROR_BLOCK_WRITE: + case ISO15693_3_RESP_ERROR_BLOCK_LOCK: + *error = Iso15693_3ErrorInternal; + break; + case ISO15693_3_RESP_ERROR_UNKNOWN: + default: + *error = Iso15693_3ErrorUnknown; + } + + return true; +} + +Iso15693_3Error iso15693_3_inventory_response_parse(uint8_t* data, const BitBuffer* buf) { + furi_assert(data); + + Iso15693_3Error ret = Iso15693_3ErrorNone; + + do { + if(iso15693_3_error_response_parse(&ret, buf)) break; + + typedef struct { + uint8_t flags; + uint8_t dsfid; + uint8_t uid[ISO15693_3_UID_SIZE]; + } InventoryResponseLayout; + + if(bit_buffer_get_size_bytes(buf) != sizeof(InventoryResponseLayout)) { + ret = Iso15693_3ErrorUnexpectedResponse; + break; + } + + const InventoryResponseLayout* resp = + (const InventoryResponseLayout*)bit_buffer_get_data(buf); + // Reverse UID for backward compatibility + for(uint32_t i = 0; i < ISO15693_3_UID_SIZE; ++i) { + data[i] = resp->uid[ISO15693_3_UID_SIZE - i - 1]; + } + + } while(false); + + return ret; +} + +Iso15693_3Error + iso15693_3_system_info_response_parse(Iso15693_3SystemInfo* data, const BitBuffer* buf) { + furi_assert(data); + + Iso15693_3Error ret = Iso15693_3ErrorNone; + + do { + if(iso15693_3_error_response_parse(&ret, buf)) break; + + typedef struct { + uint8_t flags; + uint8_t info_flags; + uint8_t uid[ISO15693_3_UID_SIZE]; + uint8_t extra[]; + } SystemInfoResponseLayout; + + if(bit_buffer_get_size_bytes(buf) < sizeof(SystemInfoResponseLayout)) { + ret = Iso15693_3ErrorUnexpectedResponse; + break; + } + + const SystemInfoResponseLayout* resp = + (const SystemInfoResponseLayout*)bit_buffer_get_data(buf); + + const uint8_t* extra = resp->extra; + const size_t extra_size = (resp->info_flags & ISO15693_3_SYSINFO_FLAG_DSFID ? 1 : 0) + + (resp->info_flags & ISO15693_3_SYSINFO_FLAG_AFI ? 1 : 0) + + (resp->info_flags & ISO15693_3_SYSINFO_FLAG_MEMORY ? 2 : 0) + + (resp->info_flags & ISO15693_3_SYSINFO_FLAG_IC_REF ? 1 : 0); + + if(extra_size != bit_buffer_get_size_bytes(buf) - sizeof(SystemInfoResponseLayout)) { + ret = Iso15693_3ErrorUnexpectedResponse; + break; + } + + data->flags = resp->info_flags; + + if(data->flags & ISO15693_3_SYSINFO_FLAG_DSFID) { + data->dsfid = *extra++; + } + + if(data->flags & ISO15693_3_SYSINFO_FLAG_AFI) { + data->afi = *extra++; + } + + if(data->flags & ISO15693_3_SYSINFO_FLAG_MEMORY) { + // Add 1 to get actual values + data->block_count = *extra++ + 1; + data->block_size = (*extra++ & 0x1F) + 1; + } + + if(data->flags & ISO15693_3_SYSINFO_FLAG_IC_REF) { + data->ic_ref = *extra; + } + + } while(false); + + return ret; +} + +Iso15693_3Error + iso15693_3_read_block_response_parse(uint8_t* data, uint8_t block_size, const BitBuffer* buf) { + furi_assert(data); + + Iso15693_3Error ret = Iso15693_3ErrorNone; + + do { + if(iso15693_3_error_response_parse(&ret, buf)) break; + + typedef struct { + uint8_t flags; + uint8_t block_data[]; + } ReadBlockResponseLayout; + + const size_t buf_size = bit_buffer_get_size_bytes(buf); + const size_t received_block_size = buf_size - sizeof(ReadBlockResponseLayout); + + if(buf_size <= sizeof(ReadBlockResponseLayout) || received_block_size != block_size) { + ret = Iso15693_3ErrorUnexpectedResponse; + break; + } + + const ReadBlockResponseLayout* resp = + (const ReadBlockResponseLayout*)bit_buffer_get_data(buf); + memcpy(data, resp->block_data, received_block_size); + + } while(false); + + return ret; +} + +Iso15693_3Error iso15693_3_get_block_security_response_parse( + uint8_t* data, + uint16_t block_count, + const BitBuffer* buf) { + furi_assert(data); + furi_assert(block_count); + Iso15693_3Error ret = Iso15693_3ErrorNone; + + do { + if(iso15693_3_error_response_parse(&ret, buf)) break; + + typedef struct { + uint8_t flags; + uint8_t block_security[]; + } GetBlockSecurityResponseLayout; + + const size_t buf_size = bit_buffer_get_size_bytes(buf); + const size_t received_block_count = buf_size - sizeof(GetBlockSecurityResponseLayout); + + if(buf_size <= sizeof(GetBlockSecurityResponseLayout) || + received_block_count != block_count) { + ret = Iso15693_3ErrorUnexpectedResponse; + break; + } + + const GetBlockSecurityResponseLayout* resp = + (const GetBlockSecurityResponseLayout*)bit_buffer_get_data(buf); + + memcpy(data, resp->block_security, received_block_count); + + } while(false); + + return ret; +} + +void iso15693_3_append_uid(const Iso15693_3Data* data, BitBuffer* buf) { + for(size_t i = 0; i < ISO15693_3_UID_SIZE; ++i) { + // Reverse the UID + bit_buffer_append_byte(buf, data->uid[ISO15693_3_UID_SIZE - i - 1]); + } +} + +void iso15693_3_append_block(const Iso15693_3Data* data, uint8_t block_num, BitBuffer* buf) { + furi_assert(block_num < data->system_info.block_count); + + const uint32_t block_offset = block_num * data->system_info.block_size; + const uint8_t* block_data = simple_array_cget(data->block_data, block_offset); + + bit_buffer_append_bytes(buf, block_data, data->system_info.block_size); +} + +void iso15693_3_set_block_locked(Iso15693_3Data* data, uint8_t block_index, bool locked) { + furi_assert(data); + furi_assert(block_index < data->system_info.block_count); + + *(uint8_t*)simple_array_get(data->block_security, block_index) = locked ? 1 : 0; +} + +void iso15693_3_set_block_data( + Iso15693_3Data* data, + uint8_t block_num, + const uint8_t* block_data, + size_t block_data_size) { + furi_assert(block_num < data->system_info.block_count); + furi_assert(block_data_size == data->system_info.block_size); + + const uint32_t block_offset = block_num * data->system_info.block_size; + uint8_t* block = simple_array_get(data->block_data, block_offset); + + memcpy(block, block_data, block_data_size); +} + +void iso15693_3_append_block_security( + const Iso15693_3Data* data, + uint8_t block_num, + BitBuffer* buf) { + bit_buffer_append_byte(buf, *(uint8_t*)simple_array_cget(data->block_security, block_num)); +} + +bool iso15693_3_is_equal_uid(const Iso15693_3Data* data, const uint8_t* uid) { + for(size_t i = 0; i < ISO15693_3_UID_SIZE; ++i) { + if(data->uid[i] != uid[ISO15693_3_UID_SIZE - i - 1]) return false; + } + return true; +} diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_i.h b/lib/nfc/protocols/iso15693_3/iso15693_3_i.h new file mode 100644 index 000000000..253bda7f5 --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_i.h @@ -0,0 +1,58 @@ +#pragma once + +#include "iso15693_3.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Check if the buffer contains an error frame and if it does, determine + * the error type. + * NOTE: No changes are done to the result if no error is present. + * + * @param [out] data Pointer to the resulting error value. + * @param [in] buf Data buffer to be checked + * + * @return True if data contains an error frame or is empty, false otherwise + */ +bool iso15693_3_error_response_parse(Iso15693_3Error* error, const BitBuffer* buf); + +Iso15693_3Error iso15693_3_inventory_response_parse(uint8_t* data, const BitBuffer* buf); + +Iso15693_3Error + iso15693_3_system_info_response_parse(Iso15693_3SystemInfo* data, const BitBuffer* buf); + +Iso15693_3Error + iso15693_3_read_block_response_parse(uint8_t* data, uint8_t block_size, const BitBuffer* buf); + +Iso15693_3Error iso15693_3_get_block_security_response_parse( + uint8_t* data, + uint16_t block_count, + const BitBuffer* buf); + +void iso15693_3_append_uid(const Iso15693_3Data* data, BitBuffer* buf); + +void iso15693_3_append_block(const Iso15693_3Data* data, uint8_t block_num, BitBuffer* buf); + +void iso15693_3_set_block_locked(Iso15693_3Data* data, uint8_t block_index, bool locked); + +void iso15693_3_set_block_data( + Iso15693_3Data* data, + uint8_t block_num, + const uint8_t* block_data, + size_t block_data_size); + +void iso15693_3_append_block_security( + const Iso15693_3Data* data, + uint8_t block_num, + BitBuffer* buf); + +// NOTE: the uid parameter has reversed byte order with respect to data +bool iso15693_3_is_equal_uid(const Iso15693_3Data* data, const uint8_t* uid); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_listener.c b/lib/nfc/protocols/iso15693_3/iso15693_3_listener.c new file mode 100644 index 000000000..84e750858 --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_listener.c @@ -0,0 +1,110 @@ +#include "iso15693_3_listener_i.h" + +#include + +#include +#include +#include + +#define TAG "Iso15693_3Listener" + +#define ISO15693_3_LISTENER_BUFFER_SIZE (64U) + +Iso15693_3Listener* iso15693_3_listener_alloc(Nfc* nfc, Iso15693_3Data* data) { + furi_assert(nfc); + + Iso15693_3Listener* instance = malloc(sizeof(Iso15693_3Listener)); + instance->nfc = nfc; + instance->data = data; + + instance->tx_buffer = bit_buffer_alloc(ISO15693_3_LISTENER_BUFFER_SIZE); + + instance->iso15693_3_event.data = &instance->iso15693_3_event_data; + instance->generic_event.protocol = NfcProtocolIso15693_3; + instance->generic_event.instance = instance; + instance->generic_event.event_data = &instance->iso15693_3_event; + + nfc_set_fdt_listen_fc(instance->nfc, ISO15693_3_FDT_LISTEN_FC); + nfc_config(instance->nfc, NfcModeListener, NfcTechIso15693); + + return instance; +} + +void iso15693_3_listener_free(Iso15693_3Listener* instance) { + furi_assert(instance); + + bit_buffer_free(instance->tx_buffer); + + free(instance); +} + +void iso15693_3_listener_set_callback( + Iso15693_3Listener* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + + instance->callback = callback; + instance->context = context; +} + +const Iso15693_3Data* iso15693_3_listener_get_data(Iso15693_3Listener* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +NfcCommand iso15693_3_listener_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolInvalid); + furi_assert(event.event_data); + + Iso15693_3Listener* instance = context; + NfcEvent* nfc_event = event.event_data; + NfcCommand command = NfcCommandContinue; + + if(nfc_event->type == NfcEventTypeRxEnd) { + BitBuffer* rx_buffer = nfc_event->data.buffer; + + if(iso13239_crc_check(Iso13239CrcTypeDefault, rx_buffer)) { + iso13239_crc_trim(rx_buffer); + + const Iso15693_3Error error = iso15693_3_listener_process_request(instance, rx_buffer); + + if(error == Iso15693_3ErrorNotSupported) { + if(instance->callback) { + instance->iso15693_3_event.type = Iso15693_3ListenerEventTypeCustomCommand; + instance->iso15693_3_event.data->buffer = rx_buffer; + command = instance->callback(instance->generic_event, instance->context); + } + + } else if(error == Iso15693_3ErrorUidMismatch) { + iso15693_3_listener_process_uid_mismatch(instance, rx_buffer); + } + + } else if(bit_buffer_get_size(rx_buffer) == 0) { + // Special case: Single EOF + const Iso15693_3Error error = iso15693_3_listener_process_single_eof(instance); + if(error == Iso15693_3ErrorUnexpectedResponse) { + if(instance->callback) { + instance->iso15693_3_event.type = Iso15693_3ListenerEventTypeSingleEof; + command = instance->callback(instance->generic_event, instance->context); + } + } + } else { + FURI_LOG_D( + TAG, "Wrong CRC, buffer size: %zu", bit_buffer_get_size(nfc_event->data.buffer)); + } + } + + return command; +} + +const NfcListenerBase nfc_listener_iso15693_3 = { + .alloc = (NfcListenerAlloc)iso15693_3_listener_alloc, + .free = (NfcListenerFree)iso15693_3_listener_free, + .set_callback = (NfcListenerSetCallback)iso15693_3_listener_set_callback, + .get_data = (NfcListenerGetData)iso15693_3_listener_get_data, + .run = (NfcListenerRun)iso15693_3_listener_run, +}; diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_listener.h b/lib/nfc/protocols/iso15693_3/iso15693_3_listener.h new file mode 100644 index 000000000..c69d18db4 --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_listener.h @@ -0,0 +1,30 @@ +#pragma once + +#include + +#include "iso15693_3.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso15693_3Listener Iso15693_3Listener; + +typedef enum { + Iso15693_3ListenerEventTypeFieldOff, + Iso15693_3ListenerEventTypeCustomCommand, + Iso15693_3ListenerEventTypeSingleEof, +} Iso15693_3ListenerEventType; + +typedef struct { + BitBuffer* buffer; +} Iso15693_3ListenerEventData; + +typedef struct { + Iso15693_3ListenerEventType type; + Iso15693_3ListenerEventData* data; +} Iso15693_3ListenerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_listener_defs.h b/lib/nfc/protocols/iso15693_3/iso15693_3_listener_defs.h new file mode 100644 index 000000000..93497512e --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_listener_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcListenerBase nfc_listener_iso15693_3; diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_listener_i.c b/lib/nfc/protocols/iso15693_3/iso15693_3_listener_i.c new file mode 100644 index 000000000..a8dec7ae3 --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_listener_i.c @@ -0,0 +1,883 @@ +#include "iso15693_3_listener_i.h" + +#include + +#define TAG "Iso15693_3Listener" + +typedef Iso15693_3Error (*Iso15693_3RequestHandler)( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags); + +typedef struct { + Iso15693_3RequestHandler mandatory[ISO15693_3_MANDATORY_COUNT]; + Iso15693_3RequestHandler optional[ISO15693_3_OPTIONAL_COUNT]; +} Iso15693_3ListenerHandlerTable; + +static Iso15693_3Error + iso15693_3_listener_extension_handler(Iso15693_3Listener* instance, uint32_t command, ...) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + if(instance->extension_table == NULL) break; + + Iso15693_3ExtensionHandler handler = NULL; + + if(command < ISO15693_3_CMD_MANDATORY_RFU) { + const Iso15693_3ExtensionHandler* mandatory = instance->extension_table->mandatory; + handler = mandatory[command - ISO15693_3_CMD_MANDATORY_START]; + } else if(command >= ISO15693_3_CMD_OPTIONAL_START && command < ISO15693_3_CMD_OPTIONAL_RFU) { + const Iso15693_3ExtensionHandler* optional = instance->extension_table->optional; + handler = optional[command - ISO15693_3_CMD_OPTIONAL_START]; + } + + if(handler == NULL) break; + + va_list args; + va_start(args, command); + + error = handler(instance->extension_context, args); + + va_end(args); + + } while(false); + return error; +} + +static Iso15693_3Error iso15693_3_listener_inventory_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + const bool afi_flag = flags & ISO15693_3_REQ_FLAG_T5_AFI_PRESENT; + const size_t data_size_min = sizeof(uint8_t) * (afi_flag ? 2 : 1); + + if(data_size < data_size_min) { + error = Iso15693_3ErrorFormat; + break; + } + + if(afi_flag) { + const uint8_t afi = *data++; + // When AFI flag is set, ignore non-matching requests + if(afi != instance->data->system_info.afi) break; + } + + const uint8_t mask_len = *data++; + const size_t data_size_required = data_size_min + mask_len; + + if(data_size != data_size_required) { + error = Iso15693_3ErrorFormat; + break; + } + + if(mask_len != 0) { + // TODO FL-3633: Take mask_len and mask_value into account (if present) + } + + error = iso15693_3_listener_extension_handler(instance, ISO15693_3_CMD_INVENTORY); + if(error != Iso15693_3ErrorNone) break; + + bit_buffer_append_byte(instance->tx_buffer, instance->data->system_info.dsfid); // DSFID + iso15693_3_append_uid(instance->data, instance->tx_buffer); // UID + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_stay_quiet_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(data); + UNUSED(data_size); + UNUSED(flags); + + instance->state = Iso15693_3ListenerStateQuiet; + return Iso15693_3ErrorIgnore; +} + +static Iso15693_3Error iso15693_3_listener_read_block_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + typedef struct { + uint8_t block_num; + } Iso15693_3ReadBlockRequestLayout; + + const Iso15693_3ReadBlockRequestLayout* request = + (const Iso15693_3ReadBlockRequestLayout*)data; + + if(data_size != sizeof(Iso15693_3ReadBlockRequestLayout)) { + error = Iso15693_3ErrorFormat; + break; + } + + const uint32_t block_index = request->block_num; + const uint32_t block_count_max = instance->data->system_info.block_count; + + if(block_index >= block_count_max) { + error = Iso15693_3ErrorInternal; + break; + } + + error = iso15693_3_listener_extension_handler( + instance, ISO15693_3_CMD_READ_BLOCK, block_index); + if(error != Iso15693_3ErrorNone) break; + + if(flags & ISO15693_3_REQ_FLAG_T4_OPTION) { + iso15693_3_append_block_security( + instance->data, block_index, instance->tx_buffer); // Block security (optional) + } + + iso15693_3_append_block(instance->data, block_index, instance->tx_buffer); // Block data + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_write_block_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + typedef struct { + uint8_t block_num; + uint8_t block_data[]; + } Iso15693_3WriteBlockRequestLayout; + + const Iso15693_3WriteBlockRequestLayout* request = + (const Iso15693_3WriteBlockRequestLayout*)data; + + instance->session_state.wait_for_eof = flags & ISO15693_3_REQ_FLAG_T4_OPTION; + + if(data_size <= sizeof(Iso15693_3WriteBlockRequestLayout)) { + error = Iso15693_3ErrorFormat; + break; + } + + const uint32_t block_index = request->block_num; + const uint32_t block_count_max = instance->data->system_info.block_count; + const uint32_t block_size_max = instance->data->system_info.block_size; + const size_t block_size_received = data_size - sizeof(Iso15693_3WriteBlockRequestLayout); + + if(block_index >= block_count_max) { + error = Iso15693_3ErrorInternal; + break; + } else if(block_size_received != block_size_max) { + error = Iso15693_3ErrorInternal; + break; + } else if(iso15693_3_is_block_locked(instance->data, block_index)) { + error = Iso15693_3ErrorInternal; + break; + } + + error = iso15693_3_listener_extension_handler( + instance, ISO15693_3_CMD_WRITE_BLOCK, block_index, request->block_data); + if(error != Iso15693_3ErrorNone) break; + + iso15693_3_set_block_data( + instance->data, block_index, request->block_data, block_size_received); + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_lock_block_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + typedef struct { + uint8_t block_num; + } Iso15693_3LockBlockRequestLayout; + + const Iso15693_3LockBlockRequestLayout* request = + (const Iso15693_3LockBlockRequestLayout*)data; + + instance->session_state.wait_for_eof = flags & ISO15693_3_REQ_FLAG_T4_OPTION; + + if(data_size != sizeof(Iso15693_3LockBlockRequestLayout)) { + error = Iso15693_3ErrorFormat; + break; + } + + const uint32_t block_index = request->block_num; + const uint32_t block_count_max = instance->data->system_info.block_count; + + if(block_index >= block_count_max) { + error = Iso15693_3ErrorInternal; + break; + } else if(iso15693_3_is_block_locked(instance->data, block_index)) { + error = Iso15693_3ErrorInternal; + break; + } + + error = iso15693_3_listener_extension_handler( + instance, ISO15693_3_CMD_LOCK_BLOCK, block_index); + if(error != Iso15693_3ErrorNone) break; + + iso15693_3_set_block_locked(instance->data, block_index, true); + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_read_multi_blocks_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + typedef struct { + uint8_t first_block_num; + uint8_t block_count; + } Iso15693_3ReadMultiBlocksRequestLayout; + + const Iso15693_3ReadMultiBlocksRequestLayout* request = + (const Iso15693_3ReadMultiBlocksRequestLayout*)data; + + if(data_size != sizeof(Iso15693_3ReadMultiBlocksRequestLayout)) { + error = Iso15693_3ErrorFormat; + break; + } + + const uint32_t block_index_start = request->first_block_num; + const uint32_t block_index_end = block_index_start + request->block_count; + + const uint32_t block_count = request->block_count + 1; + const uint32_t block_count_max = instance->data->system_info.block_count; + const uint32_t block_count_available = block_count_max - block_index_start; + + if(block_count > block_count_available) { + error = Iso15693_3ErrorInternal; + break; + } + + error = iso15693_3_listener_extension_handler( + instance, + ISO15693_3_CMD_READ_MULTI_BLOCKS, + (uint32_t)block_index_start, + (uint32_t)block_index_end); + if(error != Iso15693_3ErrorNone) break; + + for(uint32_t i = block_index_start; i <= block_index_end; ++i) { + if(flags & ISO15693_3_REQ_FLAG_T4_OPTION) { + iso15693_3_append_block_security( + instance->data, i, instance->tx_buffer); // Block security (optional) + } + iso15693_3_append_block(instance->data, i, instance->tx_buffer); // Block data + } + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_write_multi_blocks_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + typedef struct { + uint8_t first_block_num; + uint8_t block_count; + uint8_t block_data[]; + } Iso15693_3WriteMultiBlocksRequestLayout; + + const Iso15693_3WriteMultiBlocksRequestLayout* request = + (const Iso15693_3WriteMultiBlocksRequestLayout*)data; + + instance->session_state.wait_for_eof = flags & ISO15693_3_REQ_FLAG_T4_OPTION; + + if(data_size <= sizeof(Iso15693_3WriteMultiBlocksRequestLayout)) { + error = Iso15693_3ErrorFormat; + break; + } + + const uint32_t block_index_start = request->first_block_num; + const uint32_t block_index_end = block_index_start + request->block_count; + + const uint32_t block_count = request->block_count + 1; + const uint32_t block_count_max = instance->data->system_info.block_count; + const uint32_t block_count_available = block_count_max - block_index_start; + + const size_t block_data_size = data_size - sizeof(Iso15693_3WriteMultiBlocksRequestLayout); + const size_t block_size = block_data_size / block_count; + const size_t block_size_max = instance->data->system_info.block_size; + + if(block_count > block_count_available) { + error = Iso15693_3ErrorInternal; + break; + } else if(block_size != block_size_max) { + error = Iso15693_3ErrorInternal; + break; + } + + error = iso15693_3_listener_extension_handler( + instance, ISO15693_3_CMD_WRITE_MULTI_BLOCKS, block_index_start, block_index_end); + if(error != Iso15693_3ErrorNone) break; + + for(uint32_t i = block_index_start; i <= block_index_end; ++i) { + if(iso15693_3_is_block_locked(instance->data, i)) { + error = Iso15693_3ErrorInternal; + break; + } + } + + if(error != Iso15693_3ErrorNone) break; + + for(uint32_t i = block_index_start; i < block_count + request->first_block_num; ++i) { + const uint8_t* block_data = &request->block_data[block_size * i]; + iso15693_3_set_block_data(instance->data, i, block_data, block_size); + } + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_select_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(data); + UNUSED(data_size); + + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + if(!(flags & ISO15693_3_REQ_FLAG_T4_ADDRESSED)) { + error = Iso15693_3ErrorFormat; + break; + } + + instance->state = Iso15693_3ListenerStateSelected; + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_reset_to_ready_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(data); + UNUSED(data_size); + UNUSED(flags); + + instance->state = Iso15693_3ListenerStateReady; + return Iso15693_3ErrorNone; +} + +static Iso15693_3Error iso15693_3_listener_write_afi_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + typedef struct { + uint8_t afi; + } Iso15693_3WriteAfiRequestLayout; + + const Iso15693_3WriteAfiRequestLayout* request = + (const Iso15693_3WriteAfiRequestLayout*)data; + + instance->session_state.wait_for_eof = flags & ISO15693_3_REQ_FLAG_T4_OPTION; + + if(data_size <= sizeof(Iso15693_3WriteAfiRequestLayout)) { + error = Iso15693_3ErrorFormat; + break; + } else if(instance->data->settings.lock_bits.afi) { + error = Iso15693_3ErrorInternal; + break; + } + + error = iso15693_3_listener_extension_handler(instance, ISO15693_3_CMD_WRITE_AFI); + if(error != Iso15693_3ErrorNone) break; + + instance->data->system_info.afi = request->afi; + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_lock_afi_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(data); + UNUSED(data_size); + + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + instance->session_state.wait_for_eof = flags & ISO15693_3_REQ_FLAG_T4_OPTION; + + Iso15693_3LockBits* lock_bits = &instance->data->settings.lock_bits; + + if(lock_bits->afi) { + error = Iso15693_3ErrorInternal; + break; + } + + error = iso15693_3_listener_extension_handler(instance, ISO15693_3_CMD_LOCK_AFI); + if(error != Iso15693_3ErrorNone) break; + + lock_bits->afi = true; + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_write_dsfid_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + typedef struct { + uint8_t dsfid; + } Iso15693_3WriteDsfidRequestLayout; + + const Iso15693_3WriteDsfidRequestLayout* request = + (const Iso15693_3WriteDsfidRequestLayout*)data; + + instance->session_state.wait_for_eof = flags & ISO15693_3_REQ_FLAG_T4_OPTION; + + if(data_size <= sizeof(Iso15693_3WriteDsfidRequestLayout)) { + error = Iso15693_3ErrorFormat; + break; + } else if(instance->data->settings.lock_bits.dsfid) { + error = Iso15693_3ErrorInternal; + break; + } + + error = iso15693_3_listener_extension_handler(instance, ISO15693_3_CMD_WRITE_DSFID); + if(error != Iso15693_3ErrorNone) break; + + instance->data->system_info.dsfid = request->dsfid; + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_lock_dsfid_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(data); + UNUSED(data_size); + + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + instance->session_state.wait_for_eof = flags & ISO15693_3_REQ_FLAG_T4_OPTION; + + Iso15693_3LockBits* lock_bits = &instance->data->settings.lock_bits; + + if(lock_bits->dsfid) { + error = Iso15693_3ErrorInternal; + break; + } + + error = iso15693_3_listener_extension_handler(instance, ISO15693_3_CMD_LOCK_DSFID); + if(error != Iso15693_3ErrorNone) break; + + lock_bits->dsfid = true; + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_get_system_info_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(data); + UNUSED(data_size); + UNUSED(flags); + + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + const uint8_t system_flags = instance->data->system_info.flags; + bit_buffer_append_byte(instance->tx_buffer, system_flags); // System info flags + + iso15693_3_append_uid(instance->data, instance->tx_buffer); // UID + + if(system_flags & ISO15693_3_SYSINFO_FLAG_DSFID) { + bit_buffer_append_byte(instance->tx_buffer, instance->data->system_info.dsfid); + } + if(system_flags & ISO15693_3_SYSINFO_FLAG_AFI) { + bit_buffer_append_byte(instance->tx_buffer, instance->data->system_info.afi); + } + if(system_flags & ISO15693_3_SYSINFO_FLAG_MEMORY) { + const uint8_t memory_info[2] = { + instance->data->system_info.block_count - 1, + instance->data->system_info.block_size - 1, + }; + bit_buffer_append_bytes(instance->tx_buffer, memory_info, COUNT_OF(memory_info)); + } + if(system_flags & ISO15693_3_SYSINFO_FLAG_IC_REF) { + bit_buffer_append_byte(instance->tx_buffer, instance->data->system_info.ic_ref); + } + + } while(false); + + return error; +} + +static Iso15693_3Error iso15693_3_listener_get_multi_blocks_security_handler( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(flags); + + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + typedef struct { + uint8_t first_block_num; + uint8_t block_count; + } Iso15693_3GetMultiBlocksSecurityRequestLayout; + + const Iso15693_3GetMultiBlocksSecurityRequestLayout* request = + (const Iso15693_3GetMultiBlocksSecurityRequestLayout*)data; + + if(data_size < sizeof(Iso15693_3GetMultiBlocksSecurityRequestLayout)) { + error = Iso15693_3ErrorFormat; + break; + } + + const uint32_t block_index_start = request->first_block_num; + const uint32_t block_index_end = block_index_start + request->block_count; + + const uint32_t block_count_max = instance->data->system_info.block_count; + + if(block_index_end >= block_count_max) { + error = Iso15693_3ErrorInternal; + break; + } + + for(uint32_t i = block_index_start; i <= block_index_end; ++i) { + bit_buffer_append_byte( + instance->tx_buffer, iso15693_3_is_block_locked(instance->data, i) ? 1 : 0); + } + } while(false); + + return error; +} + +const Iso15693_3ListenerHandlerTable iso15693_3_handler_table = { + .mandatory = + { + iso15693_3_listener_inventory_handler, + iso15693_3_listener_stay_quiet_handler, + }, + .optional = + { + iso15693_3_listener_read_block_handler, + iso15693_3_listener_write_block_handler, + iso15693_3_listener_lock_block_handler, + iso15693_3_listener_read_multi_blocks_handler, + iso15693_3_listener_write_multi_blocks_handler, + iso15693_3_listener_select_handler, + iso15693_3_listener_reset_to_ready_handler, + iso15693_3_listener_write_afi_handler, + iso15693_3_listener_lock_afi_handler, + iso15693_3_listener_write_dsfid_handler, + iso15693_3_listener_lock_dsfid_handler, + iso15693_3_listener_get_system_info_handler, + iso15693_3_listener_get_multi_blocks_security_handler, + }, +}; + +static Iso15693_3Error iso15693_3_listener_handle_standard_request( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size, + uint8_t command, + uint8_t flags) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + Iso15693_3RequestHandler handler = NULL; + + if(command < ISO15693_3_CMD_MANDATORY_RFU) { + handler = iso15693_3_handler_table.mandatory[command - ISO15693_3_CMD_MANDATORY_START]; + } else if(command >= ISO15693_3_CMD_OPTIONAL_START && command < ISO15693_3_CMD_OPTIONAL_RFU) { + handler = iso15693_3_handler_table.optional[command - ISO15693_3_CMD_OPTIONAL_START]; + } + + if(handler == NULL) { + error = Iso15693_3ErrorNotSupported; + break; + } + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_RESP_FLAG_NONE); + + error = handler(instance, data, data_size, flags); + + // The request was fully handled in the protocol extension, no further action necessary + if(error == Iso15693_3ErrorFullyHandled) { + error = Iso15693_3ErrorNone; + } + + // Several commands may not require an answer + if(error == Iso15693_3ErrorFormat || error == Iso15693_3ErrorIgnore) break; + + if(error != Iso15693_3ErrorNone) { + bit_buffer_reset(instance->tx_buffer); + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_RESP_FLAG_ERROR); + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_RESP_ERROR_UNKNOWN); + } + + Iso15693_3ListenerSessionState* session_state = &instance->session_state; + + if(!session_state->wait_for_eof) { + error = iso15693_3_listener_send_frame(instance, instance->tx_buffer); + } + + } while(false); + + return error; +} + +static inline Iso15693_3Error iso15693_3_listener_handle_custom_request( + Iso15693_3Listener* instance, + const uint8_t* data, + size_t data_size) { + Iso15693_3Error error; + + do { + typedef struct { + uint8_t manufacturer; + uint8_t extra[]; + } Iso15693_3CustomRequestLayout; + + if(data_size < sizeof(Iso15693_3CustomRequestLayout)) { + error = Iso15693_3ErrorFormat; + break; + } + + const Iso15693_3CustomRequestLayout* request = (const Iso15693_3CustomRequestLayout*)data; + + if(request->manufacturer != iso15693_3_get_manufacturer_id(instance->data)) { + error = Iso15693_3ErrorIgnore; + break; + } + + // This error code will trigger the CustomCommand listener event + error = Iso15693_3ErrorNotSupported; + } while(false); + + return error; +} + +Iso15693_3Error iso15693_3_listener_set_extension_handler_table( + Iso15693_3Listener* instance, + const Iso15693_3ExtensionHandlerTable* table, + void* context) { + furi_assert(instance); + furi_assert(context); + + instance->extension_table = table; + instance->extension_context = context; + return Iso15693_3ErrorNone; +} + +Iso15693_3Error iso15693_3_listener_ready(Iso15693_3Listener* instance) { + furi_assert(instance); + instance->state = Iso15693_3ListenerStateReady; + return Iso15693_3ErrorNone; +} + +static Iso15693_3Error iso15693_3_listener_process_nfc_error(NfcError error) { + Iso15693_3Error ret = Iso15693_3ErrorNone; + + if(error == NfcErrorNone) { + ret = Iso15693_3ErrorNone; + } else if(error == NfcErrorTimeout) { + ret = Iso15693_3ErrorTimeout; + } else { + ret = Iso15693_3ErrorFieldOff; + } + + return ret; +} + +Iso15693_3Error + iso15693_3_listener_send_frame(Iso15693_3Listener* instance, const BitBuffer* tx_buffer) { + furi_assert(instance); + furi_assert(tx_buffer); + + bit_buffer_copy(instance->tx_buffer, tx_buffer); + iso13239_crc_append(Iso13239CrcTypeDefault, instance->tx_buffer); + + NfcError error = nfc_listener_tx(instance->nfc, instance->tx_buffer); + return iso15693_3_listener_process_nfc_error(error); +} + +Iso15693_3Error + iso15693_3_listener_process_request(Iso15693_3Listener* instance, const BitBuffer* rx_buffer) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + typedef struct { + uint8_t flags; + uint8_t command; + uint8_t data[]; + } Iso15693_3RequestLayout; + + const size_t buf_size = bit_buffer_get_size_bytes(rx_buffer); + const size_t buf_size_min = sizeof(Iso15693_3RequestLayout); + + if(buf_size < buf_size_min) { + error = Iso15693_3ErrorFormat; + break; + } + + const Iso15693_3RequestLayout* request = + (const Iso15693_3RequestLayout*)bit_buffer_get_data(rx_buffer); + + Iso15693_3ListenerSessionState* session_state = &instance->session_state; + + if((request->flags & ISO15693_3_REQ_FLAG_INVENTORY_T5) == 0) { + session_state->selected = request->flags & ISO15693_3_REQ_FLAG_T4_SELECTED; + session_state->addressed = request->flags & ISO15693_3_REQ_FLAG_T4_ADDRESSED; + + if(session_state->selected && session_state->addressed) { + // A request mode can be either addressed or selected, but not both + error = Iso15693_3ErrorUnknown; + break; + } else if(instance->state == Iso15693_3ListenerStateQuiet) { + // If the card is quiet, ignore non-addressed commands + if(session_state->addressed) { + error = Iso15693_3ErrorIgnore; + break; + } + } else if(instance->state != Iso15693_3ListenerStateSelected) { + // If the card is not selected, ignore selected commands + if(session_state->selected) { + error = Iso15693_3ErrorIgnore; + break; + } + } + } else { + // If the card is quiet, ignore inventory commands + if(instance->state == Iso15693_3ListenerStateQuiet) { + error = Iso15693_3ErrorIgnore; + break; + } + + session_state->selected = false; + session_state->addressed = false; + } + + if(request->command >= ISO15693_3_CMD_CUSTOM_START) { + // Custom commands are properly handled in the protocol-specific top-level poller + error = iso15693_3_listener_handle_custom_request( + instance, request->data, buf_size - buf_size_min); + break; + } + + const uint8_t* data; + size_t data_size; + + if(session_state->addressed) { + // In addressed mode, UID must be included in each command + const size_t buf_size_min_addr = buf_size_min + ISO15693_3_UID_SIZE; + + if(buf_size < buf_size_min_addr) { + error = Iso15693_3ErrorFormat; + break; + } else if(!iso15693_3_is_equal_uid(instance->data, request->data)) { + error = Iso15693_3ErrorUidMismatch; + break; + } + + data = &request->data[ISO15693_3_UID_SIZE]; + data_size = buf_size - buf_size_min_addr; + + } else { + data = request->data; + data_size = buf_size - buf_size_min; + } + + error = iso15693_3_listener_handle_standard_request( + instance, data, data_size, request->command, request->flags); + + } while(false); + + return error; +} + +Iso15693_3Error iso15693_3_listener_process_single_eof(Iso15693_3Listener* instance) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + if(!instance->session_state.wait_for_eof) { + error = Iso15693_3ErrorUnexpectedResponse; + break; + } + + instance->session_state.wait_for_eof = false; + + error = iso15693_3_listener_send_frame(instance, instance->tx_buffer); + } while(false); + + return error; +} + +Iso15693_3Error iso15693_3_listener_process_uid_mismatch( + Iso15693_3Listener* instance, + const BitBuffer* rx_buffer) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + // No checks, assuming they have been made beforehand + typedef struct { + uint8_t flags; + uint8_t command; + } Iso15693_3RequestLayout; + + const Iso15693_3RequestLayout* request = + (const Iso15693_3RequestLayout*)bit_buffer_get_data(rx_buffer); + + if(request->command == ISO15693_3_CMD_SELECT) { + if(instance->state == Iso15693_3ListenerStateSelected) { + error = iso15693_3_listener_ready(instance); + } + } + + return error; +} diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_listener_i.h b/lib/nfc/protocols/iso15693_3/iso15693_3_listener_i.h new file mode 100644 index 000000000..a9e0822bf --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_listener_i.h @@ -0,0 +1,70 @@ +#pragma once + +#include + +#include "iso15693_3_listener.h" + +#include "iso15693_3_i.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + Iso15693_3ListenerStateReady, + Iso15693_3ListenerStateSelected, + Iso15693_3ListenerStateQuiet, +} Iso15693_3ListenerState; + +typedef struct { + bool selected; + bool addressed; + bool wait_for_eof; +} Iso15693_3ListenerSessionState; + +typedef Iso15693_3Error (*Iso15693_3ExtensionHandler)(void* context, va_list args); + +typedef struct { + Iso15693_3ExtensionHandler mandatory[ISO15693_3_MANDATORY_COUNT]; + Iso15693_3ExtensionHandler optional[ISO15693_3_OPTIONAL_COUNT]; +} Iso15693_3ExtensionHandlerTable; + +struct Iso15693_3Listener { + Nfc* nfc; + Iso15693_3Data* data; + Iso15693_3ListenerState state; + Iso15693_3ListenerSessionState session_state; + BitBuffer* tx_buffer; + + NfcGenericEvent generic_event; + Iso15693_3ListenerEvent iso15693_3_event; + Iso15693_3ListenerEventData iso15693_3_event_data; + NfcGenericCallback callback; + void* context; + + const Iso15693_3ExtensionHandlerTable* extension_table; + void* extension_context; +}; + +Iso15693_3Error iso15693_3_listener_set_extension_handler_table( + Iso15693_3Listener* instance, + const Iso15693_3ExtensionHandlerTable* table, + void* context); + +Iso15693_3Error iso15693_3_listener_ready(Iso15693_3Listener* instance); + +Iso15693_3Error + iso15693_3_listener_send_frame(Iso15693_3Listener* instance, const BitBuffer* tx_buffer); + +Iso15693_3Error + iso15693_3_listener_process_request(Iso15693_3Listener* instance, const BitBuffer* rx_buffer); + +Iso15693_3Error iso15693_3_listener_process_single_eof(Iso15693_3Listener* instance); + +Iso15693_3Error iso15693_3_listener_process_uid_mismatch( + Iso15693_3Listener* instance, + const BitBuffer* rx_buffer); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_poller.c b/lib/nfc/protocols/iso15693_3/iso15693_3_poller.c new file mode 100644 index 000000000..9500e1653 --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_poller.c @@ -0,0 +1,122 @@ +#include "iso15693_3_poller_i.h" + +#include + +#include + +#define TAG "ISO15693_3Poller" + +const Iso15693_3Data* iso15693_3_poller_get_data(Iso15693_3Poller* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +static Iso15693_3Poller* iso15693_3_poller_alloc(Nfc* nfc) { + furi_assert(nfc); + + Iso15693_3Poller* instance = malloc(sizeof(Iso15693_3Poller)); + instance->nfc = nfc; + instance->tx_buffer = bit_buffer_alloc(ISO15693_3_POLLER_MAX_BUFFER_SIZE); + instance->rx_buffer = bit_buffer_alloc(ISO15693_3_POLLER_MAX_BUFFER_SIZE); + + nfc_config(instance->nfc, NfcModePoller, NfcTechIso15693); + nfc_set_guard_time_us(instance->nfc, ISO15693_3_GUARD_TIME_US); + nfc_set_fdt_poll_fc(instance->nfc, ISO15693_3_FDT_POLL_FC); + nfc_set_fdt_poll_poll_us(instance->nfc, ISO15693_3_POLL_POLL_MIN_US); + instance->data = iso15693_3_alloc(); + + instance->iso15693_3_event.data = &instance->iso15693_3_event_data; + instance->general_event.protocol = NfcProtocolIso15693_3; + instance->general_event.event_data = &instance->iso15693_3_event; + instance->general_event.instance = instance; + + return instance; +} + +static void iso15693_3_poller_free(Iso15693_3Poller* instance) { + furi_assert(instance); + + furi_assert(instance->tx_buffer); + furi_assert(instance->rx_buffer); + furi_assert(instance->data); + + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + iso15693_3_free(instance->data); + free(instance); +} + +static void iso15693_3_poller_set_callback( + Iso15693_3Poller* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +static NfcCommand iso15693_3_poller_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolInvalid); + furi_assert(event.event_data); + + Iso15693_3Poller* instance = context; + NfcEvent* nfc_event = event.event_data; + NfcCommand command = NfcCommandContinue; + + if(nfc_event->type == NfcEventTypePollerReady) { + if(instance->state != Iso15693_3PollerStateActivated) { + Iso15693_3Error error = iso15693_3_poller_async_activate(instance, instance->data); + if(error == Iso15693_3ErrorNone) { + instance->iso15693_3_event.type = Iso15693_3PollerEventTypeReady; + instance->iso15693_3_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + } else { + instance->iso15693_3_event.type = Iso15693_3PollerEventTypeError; + instance->iso15693_3_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + // Add delay to switch context + furi_delay_ms(100); + } + } else { + instance->iso15693_3_event.type = Iso15693_3PollerEventTypeReady; + instance->iso15693_3_event_data.error = Iso15693_3ErrorNone; + command = instance->callback(instance->general_event, instance->context); + } + } + + return command; +} + +static bool iso15693_3_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.instance); + furi_assert(event.protocol == NfcProtocolInvalid); + + bool protocol_detected = false; + Iso15693_3Poller* instance = context; + NfcEvent* nfc_event = event.event_data; + furi_assert(instance->state == Iso15693_3PollerStateIdle); + + if(nfc_event->type == NfcEventTypePollerReady) { + uint8_t uid[ISO15693_3_UID_SIZE]; + Iso15693_3Error error = iso15693_3_poller_async_inventory(instance, uid); + protocol_detected = (error == Iso15693_3ErrorNone); + } + + return protocol_detected; +} + +const NfcPollerBase nfc_poller_iso15693_3 = { + .alloc = (NfcPollerAlloc)iso15693_3_poller_alloc, + .free = (NfcPollerFree)iso15693_3_poller_free, + .set_callback = (NfcPollerSetCallback)iso15693_3_poller_set_callback, + .run = (NfcPollerRun)iso15693_3_poller_run, + .detect = (NfcPollerDetect)iso15693_3_poller_detect, + .get_data = (NfcPollerGetData)iso15693_3_poller_get_data, +}; diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_poller.h b/lib/nfc/protocols/iso15693_3/iso15693_3_poller.h new file mode 100644 index 000000000..9d73242f1 --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_poller.h @@ -0,0 +1,29 @@ +#pragma once + +#include "iso15693_3.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso15693_3Poller Iso15693_3Poller; + +typedef enum { + Iso15693_3PollerEventTypeError, + Iso15693_3PollerEventTypeReady, +} Iso15693_3PollerEventType; + +typedef struct { + Iso15693_3Error error; +} Iso15693_3PollerEventData; + +typedef struct { + Iso15693_3PollerEventType type; + Iso15693_3PollerEventData* data; +} Iso15693_3PollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_poller_defs.h b/lib/nfc/protocols/iso15693_3/iso15693_3_poller_defs.h new file mode 100644 index 000000000..f0447c28b --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_poller_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcPollerBase nfc_poller_iso15693_3; diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_poller_i.c b/lib/nfc/protocols/iso15693_3/iso15693_3_poller_i.c new file mode 100644 index 000000000..8b8d8cee0 --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_poller_i.c @@ -0,0 +1,303 @@ +#include "iso15693_3_poller_i.h" + +#include + +#define TAG "Iso15693_3Poller" + +#define BITS_IN_BYTE (8) + +#define ISO15693_3_POLLER_NUM_BLOCKS_PER_QUERY (32U) + +static Iso15693_3Error iso15693_3_poller_process_nfc_error(NfcError error) { + switch(error) { + case NfcErrorNone: + return Iso15693_3ErrorNone; + case NfcErrorTimeout: + return Iso15693_3ErrorTimeout; + default: + return Iso15693_3ErrorNotPresent; + } +} + +static Iso15693_3Error iso15693_3_poller_filter_error(Iso15693_3Error error) { + switch(error) { + /* If a particular optional command is not supported, the card might + * respond with a "Not supported" error or not respond at all. + * Therefore, treat these errors as non-critical ones. */ + case Iso15693_3ErrorNotSupported: + case Iso15693_3ErrorTimeout: + return Iso15693_3ErrorNone; + default: + return error; + } +} + +static Iso15693_3Error iso15693_3_poller_prepare_trx(Iso15693_3Poller* instance) { + furi_assert(instance); + + if(instance->state == Iso15693_3PollerStateIdle) { + return iso15693_3_poller_async_activate(instance, NULL); + } + + return Iso15693_3ErrorNone; +} + +static Iso15693_3Error iso15693_3_poller_frame_exchange( + Iso15693_3Poller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + + Iso15693_3Error ret = Iso15693_3ErrorNone; + + do { + if(bit_buffer_get_size_bytes(tx_buffer) > + bit_buffer_get_capacity_bytes(instance->tx_buffer) - ISO13239_CRC_SIZE) { + ret = Iso15693_3ErrorBufferOverflow; + break; + } + + bit_buffer_copy(instance->tx_buffer, tx_buffer); + iso13239_crc_append(Iso13239CrcTypeDefault, instance->tx_buffer); + + NfcError error = + nfc_poller_trx(instance->nfc, instance->tx_buffer, instance->rx_buffer, fwt); + if(error != NfcErrorNone) { + ret = iso15693_3_poller_process_nfc_error(error); + break; + } + + if(!iso13239_crc_check(Iso13239CrcTypeDefault, instance->rx_buffer)) { + ret = Iso15693_3ErrorWrongCrc; + break; + } + + iso13239_crc_trim(instance->rx_buffer); + bit_buffer_copy(rx_buffer, instance->rx_buffer); + } while(false); + + return ret; +} + +Iso15693_3Error + iso15693_3_poller_async_activate(Iso15693_3Poller* instance, Iso15693_3Data* data) { + furi_assert(instance); + furi_assert(instance->nfc); + + iso15693_3_reset(data); + + Iso15693_3Error ret; + + do { + instance->state = Iso15693_3PollerStateColResInProgress; + + // Inventory: Mandatory command + ret = iso15693_3_poller_async_inventory(instance, data->uid); + if(ret != Iso15693_3ErrorNone) { + instance->state = Iso15693_3PollerStateColResFailed; + break; + } + + instance->state = Iso15693_3PollerStateActivated; + + // Get system info: Optional command + Iso15693_3SystemInfo* system_info = &data->system_info; + ret = iso15693_3_poller_async_get_system_info(instance, system_info); + if(ret != Iso15693_3ErrorNone) { + ret = iso15693_3_poller_filter_error(ret); + break; + } + + // Read blocks: Optional command + simple_array_init(data->block_data, system_info->block_count * system_info->block_size); + ret = iso15693_3_poller_async_read_blocks( + instance, + simple_array_get_data(data->block_data), + system_info->block_count, + system_info->block_size); + if(ret != Iso15693_3ErrorNone) { + ret = iso15693_3_poller_filter_error(ret); + break; + } + + // Get block security status: Optional command + simple_array_init(data->block_security, system_info->block_count); + + ret = iso15693_3_poller_async_get_blocks_security( + instance, simple_array_get_data(data->block_security), system_info->block_count); + if(ret != Iso15693_3ErrorNone) { + ret = iso15693_3_poller_filter_error(ret); + break; + } + + } while(false); + + return ret; +} + +Iso15693_3Error iso15693_3_poller_async_inventory(Iso15693_3Poller* instance, uint8_t* uid) { + furi_assert(instance); + furi_assert(instance->nfc); + furi_assert(uid); + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + // Send INVENTORY + bit_buffer_append_byte( + instance->tx_buffer, + ISO15693_3_REQ_FLAG_SUBCARRIER_1 | ISO15693_3_REQ_FLAG_DATA_RATE_HI | + ISO15693_3_REQ_FLAG_INVENTORY_T5 | ISO15693_3_REQ_FLAG_T5_N_SLOTS_1); + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_CMD_INVENTORY); + bit_buffer_append_byte(instance->tx_buffer, 0x00); + + Iso15693_3Error ret; + + do { + ret = iso15693_3_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ISO15693_3_FDT_POLL_FC); + if(ret != Iso15693_3ErrorNone) break; + + ret = iso15693_3_inventory_response_parse(uid, instance->rx_buffer); + } while(false); + + return ret; +} + +Iso15693_3Error iso15693_3_poller_async_get_system_info( + Iso15693_3Poller* instance, + Iso15693_3SystemInfo* data) { + furi_assert(instance); + furi_assert(data); + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + // Send GET SYSTEM INFO + bit_buffer_append_byte( + instance->tx_buffer, ISO15693_3_REQ_FLAG_SUBCARRIER_1 | ISO15693_3_REQ_FLAG_DATA_RATE_HI); + + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_CMD_GET_SYS_INFO); + + Iso15693_3Error ret; + + do { + ret = iso15693_3_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ISO15693_3_FDT_POLL_FC); + if(ret != Iso15693_3ErrorNone) break; + + ret = iso15693_3_system_info_response_parse(data, instance->rx_buffer); + } while(false); + + return ret; +} + +Iso15693_3Error iso15693_3_poller_async_read_block( + Iso15693_3Poller* instance, + uint8_t* data, + uint8_t block_number, + uint8_t block_size) { + furi_assert(instance); + furi_assert(data); + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + bit_buffer_append_byte( + instance->tx_buffer, ISO15693_3_REQ_FLAG_SUBCARRIER_1 | ISO15693_3_REQ_FLAG_DATA_RATE_HI); + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_CMD_READ_BLOCK); + bit_buffer_append_byte(instance->tx_buffer, block_number); + + Iso15693_3Error ret; + + do { + ret = iso15693_3_poller_send_frame( + instance, instance->tx_buffer, instance->rx_buffer, ISO15693_3_FDT_POLL_FC); + if(ret != Iso15693_3ErrorNone) break; + + ret = iso15693_3_read_block_response_parse(data, block_size, instance->rx_buffer); + } while(false); + + return ret; +} + +Iso15693_3Error iso15693_3_poller_async_read_blocks( + Iso15693_3Poller* instance, + uint8_t* data, + uint16_t block_count, + uint8_t block_size) { + furi_assert(instance); + furi_assert(data); + furi_assert(block_count); + furi_assert(block_size); + + Iso15693_3Error ret = Iso15693_3ErrorNone; + + for(uint32_t i = 0; i < block_count; ++i) { + ret = iso15693_3_poller_async_read_block(instance, &data[block_size * i], i, block_size); + if(ret != Iso15693_3ErrorNone) break; + } + + return ret; +} + +Iso15693_3Error iso15693_3_poller_async_get_blocks_security( + Iso15693_3Poller* instance, + uint8_t* data, + uint16_t block_count) { + furi_assert(instance); + furi_assert(data); + + // Limit the number of blocks to 32 in a single query + const uint32_t num_queries = block_count / ISO15693_3_POLLER_NUM_BLOCKS_PER_QUERY + + (block_count % ISO15693_3_POLLER_NUM_BLOCKS_PER_QUERY ? 1 : 0); + + Iso15693_3Error ret = Iso15693_3ErrorNone; + + for(uint32_t i = 0; i < num_queries; ++i) { + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + bit_buffer_append_byte( + instance->tx_buffer, + ISO15693_3_REQ_FLAG_SUBCARRIER_1 | ISO15693_3_REQ_FLAG_DATA_RATE_HI); + + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_CMD_GET_BLOCKS_SECURITY); + + const uint8_t start_block_num = i * ISO15693_3_POLLER_NUM_BLOCKS_PER_QUERY; + bit_buffer_append_byte(instance->tx_buffer, start_block_num); + + const uint8_t block_count_per_query = + MIN(block_count - start_block_num, (uint16_t)ISO15693_3_POLLER_NUM_BLOCKS_PER_QUERY); + // Block count byte must be 1 less than the desired count + bit_buffer_append_byte(instance->tx_buffer, block_count_per_query - 1); + + ret = iso15693_3_poller_send_frame( + instance, instance->tx_buffer, instance->rx_buffer, ISO15693_3_FDT_POLL_FC); + if(ret != Iso15693_3ErrorNone) break; + + ret = iso15693_3_get_block_security_response_parse( + &data[start_block_num], block_count_per_query, instance->rx_buffer); + if(ret != Iso15693_3ErrorNone) break; + } + + return ret; +} + +Iso15693_3Error iso15693_3_poller_send_frame( + Iso15693_3Poller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + Iso15693_3Error ret; + + do { + ret = iso15693_3_poller_prepare_trx(instance); + if(ret != Iso15693_3ErrorNone) break; + + ret = iso15693_3_poller_frame_exchange(instance, tx_buffer, rx_buffer, fwt); + } while(false); + + return ret; +} diff --git a/lib/nfc/protocols/iso15693_3/iso15693_3_poller_i.h b/lib/nfc/protocols/iso15693_3/iso15693_3_poller_i.h new file mode 100644 index 000000000..154ee684c --- /dev/null +++ b/lib/nfc/protocols/iso15693_3/iso15693_3_poller_i.h @@ -0,0 +1,70 @@ +#pragma once + +#include "iso15693_3_poller.h" + +#include "iso15693_3_i.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ISO15693_3_POLLER_MAX_BUFFER_SIZE (64U) + +typedef enum { + Iso15693_3PollerStateIdle, + Iso15693_3PollerStateColResInProgress, + Iso15693_3PollerStateColResFailed, + Iso15693_3PollerStateActivated, +} Iso15693_3PollerState; + +struct Iso15693_3Poller { + Nfc* nfc; + Iso15693_3PollerState state; + Iso15693_3Data* data; + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + + NfcGenericEvent general_event; + Iso15693_3PollerEvent iso15693_3_event; + Iso15693_3PollerEventData iso15693_3_event_data; + NfcGenericCallback callback; + void* context; +}; + +const Iso15693_3Data* iso15693_3_poller_get_data(Iso15693_3Poller* instance); + +Iso15693_3Error iso15693_3_poller_async_activate(Iso15693_3Poller* instance, Iso15693_3Data* data); + +Iso15693_3Error iso15693_3_poller_async_inventory(Iso15693_3Poller* instance, uint8_t* uid); + +Iso15693_3Error + iso15693_3_poller_async_get_system_info(Iso15693_3Poller* instance, Iso15693_3SystemInfo* data); + +Iso15693_3Error iso15693_3_poller_async_read_block( + Iso15693_3Poller* instance, + uint8_t* data, + uint8_t block_number, + uint8_t block_size); + +Iso15693_3Error iso15693_3_poller_async_read_blocks( + Iso15693_3Poller* instance, + uint8_t* data, + uint16_t block_count, + uint8_t block_size); + +Iso15693_3Error iso15693_3_poller_async_get_blocks_security( + Iso15693_3Poller* instance, + uint8_t* data, + uint16_t block_count); + +Iso15693_3Error iso15693_3_poller_send_frame( + Iso15693_3Poller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_classic/crypto1.c b/lib/nfc/protocols/mf_classic/crypto1.c new file mode 100644 index 000000000..df01a348c --- /dev/null +++ b/lib/nfc/protocols/mf_classic/crypto1.c @@ -0,0 +1,172 @@ +#include "crypto1.h" + +#include +#include + +// Algorithm from https://github.com/RfidResearchGroup/proxmark3.git + +#define SWAPENDIAN(x) \ + ((x) = ((x) >> 8 & 0xff00ff) | ((x)&0xff00ff) << 8, (x) = (x) >> 16 | (x) << 16) +#define LF_POLY_ODD (0x29CE5C) +#define LF_POLY_EVEN (0x870804) + +#define BEBIT(x, n) FURI_BIT(x, (n) ^ 24) + +Crypto1* crypto1_alloc() { + Crypto1* instance = malloc(sizeof(Crypto1)); + + return instance; +} + +void crypto1_free(Crypto1* instance) { + furi_assert(instance); + + free(instance); +} + +void crypto1_reset(Crypto1* crypto1) { + furi_assert(crypto1); + crypto1->even = 0; + crypto1->odd = 0; +} + +void crypto1_init(Crypto1* crypto1, uint64_t key) { + furi_assert(crypto1); + crypto1->even = 0; + crypto1->odd = 0; + for(int8_t i = 47; i > 0; i -= 2) { + crypto1->odd = crypto1->odd << 1 | FURI_BIT(key, (i - 1) ^ 7); + crypto1->even = crypto1->even << 1 | FURI_BIT(key, i ^ 7); + } +} + +static uint32_t crypto1_filter(uint32_t in) { + uint32_t out = 0; + out = 0xf22c0 >> (in & 0xf) & 16; + out |= 0x6c9c0 >> (in >> 4 & 0xf) & 8; + out |= 0x3c8b0 >> (in >> 8 & 0xf) & 4; + out |= 0x1e458 >> (in >> 12 & 0xf) & 2; + out |= 0x0d938 >> (in >> 16 & 0xf) & 1; + return FURI_BIT(0xEC57E80A, out); +} + +uint8_t crypto1_bit(Crypto1* crypto1, uint8_t in, int is_encrypted) { + furi_assert(crypto1); + uint8_t out = crypto1_filter(crypto1->odd); + uint32_t feed = out & (!!is_encrypted); + feed ^= !!in; + feed ^= LF_POLY_ODD & crypto1->odd; + feed ^= LF_POLY_EVEN & crypto1->even; + crypto1->even = crypto1->even << 1 | (nfc_util_even_parity32(feed)); + + FURI_SWAP(crypto1->odd, crypto1->even); + return out; +} + +uint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted) { + furi_assert(crypto1); + uint8_t out = 0; + for(uint8_t i = 0; i < 8; i++) { + out |= crypto1_bit(crypto1, FURI_BIT(in, i), is_encrypted) << i; + } + return out; +} + +uint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted) { + furi_assert(crypto1); + uint32_t out = 0; + for(uint8_t i = 0; i < 32; i++) { + out |= (uint32_t)crypto1_bit(crypto1, BEBIT(in, i), is_encrypted) << (24 ^ i); + } + return out; +} + +uint32_t prng_successor(uint32_t x, uint32_t n) { + SWAPENDIAN(x); + while(n--) x = x >> 1 | (x >> 16 ^ x >> 18 ^ x >> 19 ^ x >> 21) << 31; + + return SWAPENDIAN(x); +} + +void crypto1_decrypt(Crypto1* crypto, const BitBuffer* buff, BitBuffer* out) { + furi_assert(crypto); + furi_assert(buff); + furi_assert(out); + + size_t bits = bit_buffer_get_size(buff); + bit_buffer_set_size(out, bits); + const uint8_t* encrypted_data = bit_buffer_get_data(buff); + if(bits < 8) { + uint8_t decrypted_byte = 0; + uint8_t encrypted_byte = encrypted_data[0]; + decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_byte, 0)) << 0; + decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_byte, 1)) << 1; + decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_byte, 2)) << 2; + decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_byte, 3)) << 3; + bit_buffer_set_byte(out, 0, decrypted_byte); + } else { + for(size_t i = 0; i < bits / 8; i++) { + uint8_t decrypted_byte = crypto1_byte(crypto, 0, 0) ^ encrypted_data[i]; + bit_buffer_set_byte(out, i, decrypted_byte); + } + } +} + +void crypto1_encrypt(Crypto1* crypto, uint8_t* keystream, const BitBuffer* buff, BitBuffer* out) { + furi_assert(crypto); + furi_assert(buff); + furi_assert(out); + + size_t bits = bit_buffer_get_size(buff); + bit_buffer_set_size(out, bits); + const uint8_t* plain_data = bit_buffer_get_data(buff); + if(bits < 8) { + uint8_t encrypted_byte = 0; + for(size_t i = 0; i < bits; i++) { + encrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(plain_data[0], i)) << i; + } + bit_buffer_set_byte(out, 0, encrypted_byte); + } else { + for(size_t i = 0; i < bits / 8; i++) { + uint8_t encrypted_byte = crypto1_byte(crypto, keystream ? keystream[i] : 0, 0) ^ + plain_data[i]; + bool parity_bit = + ((crypto1_filter(crypto->odd) ^ nfc_util_odd_parity8(plain_data[i])) & 0x01); + bit_buffer_set_byte_with_parity(out, i, encrypted_byte, parity_bit); + } + } +} + +void crypto1_encrypt_reader_nonce( + Crypto1* crypto, + uint64_t key, + uint32_t cuid, + uint8_t* nt, + uint8_t* nr, + BitBuffer* out) { + furi_assert(crypto); + furi_assert(nt); + furi_assert(nr); + furi_assert(out); + + bit_buffer_set_size_bytes(out, 8); + uint32_t nt_num = nfc_util_bytes2num(nt, sizeof(uint32_t)); + + crypto1_init(crypto, key); + crypto1_word(crypto, nt_num ^ cuid, 0); + + for(size_t i = 0; i < 4; i++) { + uint8_t byte = crypto1_byte(crypto, nr[i], 0) ^ nr[i]; + bool parity_bit = ((crypto1_filter(crypto->odd) ^ nfc_util_odd_parity8(nr[i])) & 0x01); + bit_buffer_set_byte_with_parity(out, i, byte, parity_bit); + nr[i] = byte; + } + + nt_num = prng_successor(nt_num, 32); + for(size_t i = 4; i < 8; i++) { + nt_num = prng_successor(nt_num, 8); + uint8_t byte = crypto1_byte(crypto, 0, 0) ^ (uint8_t)(nt_num); + bool parity_bit = ((crypto1_filter(crypto->odd) ^ nfc_util_odd_parity8(nt_num)) & 0x01); + bit_buffer_set_byte_with_parity(out, i, byte, parity_bit); + } +} diff --git a/lib/nfc/protocols/crypto1.h b/lib/nfc/protocols/mf_classic/crypto1.h similarity index 56% rename from lib/nfc/protocols/crypto1.h rename to lib/nfc/protocols/mf_classic/crypto1.h index bbf6dc239..f2bdb272b 100644 --- a/lib/nfc/protocols/crypto1.h +++ b/lib/nfc/protocols/mf_classic/crypto1.h @@ -1,7 +1,6 @@ #pragma once -#include -#include +#include #ifdef __cplusplus extern "C" { @@ -12,6 +11,10 @@ typedef struct { uint32_t even; } Crypto1; +Crypto1* crypto1_alloc(); + +void crypto1_free(Crypto1* instance); + void crypto1_reset(Crypto1* crypto1); void crypto1_init(Crypto1* crypto1, uint64_t key); @@ -22,24 +25,20 @@ uint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted); uint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted); -uint32_t crypto1_filter(uint32_t in); +void crypto1_decrypt(Crypto1* crypto, const BitBuffer* buff, BitBuffer* out); + +void crypto1_encrypt(Crypto1* crypto, uint8_t* keystream, const BitBuffer* buff, BitBuffer* out); + +void crypto1_encrypt_reader_nonce( + Crypto1* crypto, + uint64_t key, + uint32_t cuid, + uint8_t* nt, + uint8_t* nr, + BitBuffer* out); uint32_t prng_successor(uint32_t x, uint32_t n); -void crypto1_decrypt( - Crypto1* crypto, - uint8_t* encrypted_data, - uint16_t encrypted_data_bits, - uint8_t* decrypted_data); - -void crypto1_encrypt( - Crypto1* crypto, - uint8_t* keystream, - uint8_t* plain_data, - uint16_t plain_data_bits, - uint8_t* encrypted_data, - uint8_t* encrypted_parity); - #ifdef __cplusplus } -#endif \ No newline at end of file +#endif diff --git a/lib/nfc/protocols/mf_classic/mf_classic.c b/lib/nfc/protocols/mf_classic/mf_classic.c new file mode 100644 index 000000000..400cf0d7f --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic.c @@ -0,0 +1,740 @@ +#include "mf_classic.h" + +#include +#include + +#include + +#define MF_CLASSIC_PROTOCOL_NAME "Mifare Classic" + +typedef struct { + uint8_t sectors_total; + uint16_t blocks_total; + const char* full_name; + const char* type_name; +} MfClassicFeatures; + +static const uint32_t mf_classic_data_format_version = 2; + +static const MfClassicFeatures mf_classic_features[MfClassicTypeNum] = { + [MfClassicTypeMini] = + { + .sectors_total = 5, + .blocks_total = 20, + .full_name = "Mifare Classic Mini 0.3K", + .type_name = "MINI", + }, + [MfClassicType1k] = + { + .sectors_total = 16, + .blocks_total = 64, + .full_name = "Mifare Classic 1K", + .type_name = "1K", + }, + [MfClassicType4k] = + { + .sectors_total = 40, + .blocks_total = 256, + .full_name = "Mifare Classic 4K", + .type_name = "4K", + }, +}; + +const NfcDeviceBase nfc_device_mf_classic = { + .protocol_name = MF_CLASSIC_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)mf_classic_alloc, + .free = (NfcDeviceFree)mf_classic_free, + .reset = (NfcDeviceReset)mf_classic_reset, + .copy = (NfcDeviceCopy)mf_classic_copy, + .verify = (NfcDeviceVerify)mf_classic_verify, + .load = (NfcDeviceLoad)mf_classic_load, + .save = (NfcDeviceSave)mf_classic_save, + .is_equal = (NfcDeviceEqual)mf_classic_is_equal, + .get_name = (NfcDeviceGetName)mf_classic_get_device_name, + .get_uid = (NfcDeviceGetUid)mf_classic_get_uid, + .set_uid = (NfcDeviceSetUid)mf_classic_set_uid, + .get_base_data = (NfcDeviceGetBaseData)mf_classic_get_base_data, +}; + +MfClassicData* mf_classic_alloc() { + MfClassicData* data = malloc(sizeof(MfClassicData)); + data->iso14443_3a_data = iso14443_3a_alloc(); + return data; +} + +void mf_classic_free(MfClassicData* data) { + furi_assert(data); + + iso14443_3a_free(data->iso14443_3a_data); + free(data); +} + +void mf_classic_reset(MfClassicData* data) { + furi_assert(data); + + iso14443_3a_reset(data->iso14443_3a_data); +} + +void mf_classic_copy(MfClassicData* data, const MfClassicData* other) { + furi_assert(data); + furi_assert(other); + + iso14443_3a_copy(data->iso14443_3a_data, other->iso14443_3a_data); + for(size_t i = 0; i < COUNT_OF(data->block); i++) { + data->block[i] = other->block[i]; + } + for(size_t i = 0; i < COUNT_OF(data->block_read_mask); i++) { + data->block_read_mask[i] = other->block_read_mask[i]; + } + data->type = other->type; + data->key_a_mask = other->key_a_mask; + data->key_b_mask = other->key_b_mask; +} + +bool mf_classic_verify(MfClassicData* data, const FuriString* device_type) { + UNUSED(data); + return furi_string_equal_str(device_type, "Mifare Classic"); +} + +static void mf_classic_parse_block(FuriString* block_str, MfClassicData* data, uint8_t block_num) { + furi_string_trim(block_str); + MfClassicBlock block_tmp = {}; + bool is_sector_trailer = mf_classic_is_sector_trailer(block_num); + uint8_t sector_num = mf_classic_get_sector_by_block(block_num); + uint16_t block_unknown_bytes_mask = 0; + + furi_string_trim(block_str); + for(size_t i = 0; i < MF_CLASSIC_BLOCK_SIZE; i++) { + char hi = furi_string_get_char(block_str, 3 * i); + char low = furi_string_get_char(block_str, 3 * i + 1); + uint8_t byte = 0; + if(hex_char_to_uint8(hi, low, &byte)) { + block_tmp.data[i] = byte; + } else { + FURI_BIT_SET(block_unknown_bytes_mask, i); + } + } + + if(block_unknown_bytes_mask != 0xffff) { + if(is_sector_trailer) { + MfClassicSectorTrailer* sec_tr_tmp = (MfClassicSectorTrailer*)&block_tmp; + // Load Key A + // Key A mask 0b0000000000111111 = 0x003f + if((block_unknown_bytes_mask & 0x003f) == 0) { + uint64_t key = nfc_util_bytes2num(sec_tr_tmp->key_a.data, sizeof(MfClassicKey)); + mf_classic_set_key_found(data, sector_num, MfClassicKeyTypeA, key); + } + // Load Access Bits + // Access bits mask 0b0000001111000000 = 0x03c0 + if((block_unknown_bytes_mask & 0x03c0) == 0) { + mf_classic_set_block_read(data, block_num, &block_tmp); + } + // Load Key B + // Key B mask 0b1111110000000000 = 0xfc00 + if((block_unknown_bytes_mask & 0xfc00) == 0) { + uint64_t key = nfc_util_bytes2num(sec_tr_tmp->key_b.data, sizeof(MfClassicKey)); + mf_classic_set_key_found(data, sector_num, MfClassicKeyTypeB, key); + } + } else { + if(block_unknown_bytes_mask == 0) { + mf_classic_set_block_read(data, block_num, &block_tmp); + } + } + } +} + +bool mf_classic_load(MfClassicData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + + FuriString* temp_str = furi_string_alloc(); + bool parsed = false; + + do { + // Read ISO14443_3A data + if(!iso14443_3a_load(data->iso14443_3a_data, ff, version)) break; + + // Read Mifare Classic type + if(!flipper_format_read_string(ff, "Mifare Classic type", temp_str)) break; + bool type_parsed = false; + for(size_t i = 0; i < MfClassicTypeNum; i++) { + if(furi_string_equal_str(temp_str, mf_classic_features[i].type_name)) { + data->type = i; + type_parsed = true; + } + } + if(!type_parsed) break; + + // Read format version + uint32_t data_format_version = 0; + bool old_format = false; + // Read Mifare Classic format version + if(!flipper_format_read_uint32(ff, "Data format version", &data_format_version, 1)) { + // Load unread sectors with zero keys access for backward compatibility + if(!flipper_format_rewind(ff)) break; + old_format = true; + } else { + if(data_format_version < mf_classic_data_format_version) { + old_format = true; + } + } + + // Read Mifare Classic blocks + bool block_read = true; + FuriString* block_str = furi_string_alloc(); + uint16_t blocks_total = mf_classic_get_total_block_num(data->type); + for(size_t i = 0; i < blocks_total; i++) { + furi_string_printf(temp_str, "Block %d", i); + if(!flipper_format_read_string(ff, furi_string_get_cstr(temp_str), block_str)) { + block_read = false; + break; + } + mf_classic_parse_block(block_str, data, i); + } + furi_string_free(block_str); + if(!block_read) break; + + // Set keys and blocks as unknown for backward compatibility + if(old_format) { + data->key_a_mask = 0ULL; + data->key_b_mask = 0ULL; + memset(data->block_read_mask, 0, sizeof(data->block_read_mask)); + } + + parsed = true; + } while(false); + + furi_string_free(temp_str); + + return parsed; +} + +static void + mf_classic_set_block_str(FuriString* block_str, const MfClassicData* data, uint8_t block_num) { + furi_string_reset(block_str); + bool is_sec_trailer = mf_classic_is_sector_trailer(block_num); + if(is_sec_trailer) { + uint8_t sector_num = mf_classic_get_sector_by_block(block_num); + MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, sector_num); + // Write key A + for(size_t i = 0; i < sizeof(sec_tr->key_a); i++) { + if(mf_classic_is_key_found(data, sector_num, MfClassicKeyTypeA)) { + furi_string_cat_printf(block_str, "%02X ", sec_tr->key_a.data[i]); + } else { + furi_string_cat_printf(block_str, "?? "); + } + } + // Write Access bytes + for(size_t i = 0; i < MF_CLASSIC_ACCESS_BYTES_SIZE; i++) { + if(mf_classic_is_block_read(data, block_num)) { + furi_string_cat_printf(block_str, "%02X ", sec_tr->access_bits.data[i]); + } else { + furi_string_cat_printf(block_str, "?? "); + } + } + // Write key B + for(size_t i = 0; i < sizeof(sec_tr->key_b); i++) { + if(mf_classic_is_key_found(data, sector_num, MfClassicKeyTypeB)) { + furi_string_cat_printf(block_str, "%02X ", sec_tr->key_b.data[i]); + } else { + furi_string_cat_printf(block_str, "?? "); + } + } + } else { + // Write data block + for(size_t i = 0; i < MF_CLASSIC_BLOCK_SIZE; i++) { + if(mf_classic_is_block_read(data, block_num)) { + furi_string_cat_printf(block_str, "%02X ", data->block[block_num].data[i]); + } else { + furi_string_cat_printf(block_str, "?? "); + } + } + } + furi_string_trim(block_str); +} + +bool mf_classic_save(const MfClassicData* data, FlipperFormat* ff) { + furi_assert(data); + + FuriString* temp_str = furi_string_alloc(); + bool saved = false; + + do { + if(!iso14443_3a_save(data->iso14443_3a_data, ff)) break; + + if(!flipper_format_write_comment_cstr(ff, "Mifare Classic specific data")) break; + if(!flipper_format_write_string_cstr( + ff, "Mifare Classic type", mf_classic_features[data->type].type_name)) + break; + if(!flipper_format_write_uint32( + ff, "Data format version", &mf_classic_data_format_version, 1)) + break; + if(!flipper_format_write_comment_cstr( + ff, "Mifare Classic blocks, \'??\' means unknown data")) + break; + + uint16_t blocks_total = mf_classic_get_total_block_num(data->type); + FuriString* block_str = furi_string_alloc(); + bool block_saved = true; + for(size_t i = 0; i < blocks_total; i++) { + furi_string_printf(temp_str, "Block %d", i); + mf_classic_set_block_str(block_str, data, i); + if(!flipper_format_write_string(ff, furi_string_get_cstr(temp_str), block_str)) { + block_saved = false; + break; + } + } + furi_string_free(block_str); + if(!block_saved) break; + + saved = true; + } while(false); + + furi_string_free(temp_str); + + return saved; +} + +bool mf_classic_is_equal(const MfClassicData* data, const MfClassicData* other) { + bool is_equal = false; + bool data_array_is_equal = true; + + do { + if(!iso14443_3a_is_equal(data->iso14443_3a_data, other->iso14443_3a_data)) break; + if(data->type != other->type) break; + if(data->key_a_mask != other->key_a_mask) break; + if(data->key_b_mask != other->key_b_mask) break; + + for(size_t i = 0; i < COUNT_OF(data->block_read_mask); i++) { + if(data->block_read_mask[i] != other->block_read_mask[i]) { + data_array_is_equal = false; + break; + } + } + if(!data_array_is_equal) break; + + for(size_t i = 0; i < COUNT_OF(data->block); i++) { + if(memcmp(&data->block[i], &other->block[i], sizeof(data->block[i])) != 0) { + data_array_is_equal = false; + break; + } + } + if(!data_array_is_equal) break; + + is_equal = true; + } while(false); + + return is_equal; +} + +const char* mf_classic_get_device_name(const MfClassicData* data, NfcDeviceNameType name_type) { + furi_assert(data); + furi_assert(data->type < MfClassicTypeNum); + + if(name_type == NfcDeviceNameTypeFull) { + return mf_classic_features[data->type].full_name; + } else { + return mf_classic_features[data->type].type_name; + } +} + +const uint8_t* mf_classic_get_uid(const MfClassicData* data, size_t* uid_len) { + furi_assert(data); + + return iso14443_3a_get_uid(data->iso14443_3a_data, uid_len); +} + +bool mf_classic_set_uid(MfClassicData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + return iso14443_3a_set_uid(data->iso14443_3a_data, uid, uid_len); +} + +Iso14443_3aData* mf_classic_get_base_data(const MfClassicData* data) { + furi_assert(data); + + return data->iso14443_3a_data; +} + +uint8_t mf_classic_get_total_sectors_num(MfClassicType type) { + return mf_classic_features[type].sectors_total; +} + +uint16_t mf_classic_get_total_block_num(MfClassicType type) { + return mf_classic_features[type].blocks_total; +} + +uint8_t mf_classic_get_sector_trailer_num_by_sector(uint8_t sector) { + uint8_t block_num = 0; + + if(sector < 32) { + block_num = sector * 4 + 3; + } else if(sector < 40) { + block_num = 32 * 4 + (sector - 32) * 16 + 15; + } else { + furi_crash("Wrong sector num"); + } + + return block_num; +} + +uint8_t mf_classic_get_sector_trailer_num_by_block(uint8_t block) { + uint8_t sec_tr_block_num = 0; + + if(block < 128) { + sec_tr_block_num = block | 0x03; + } else { + sec_tr_block_num = block | 0x0f; + } + + return sec_tr_block_num; +} + +MfClassicSectorTrailer* + mf_classic_get_sector_trailer_by_sector(const MfClassicData* data, uint8_t sector_num) { + furi_assert(data); + + uint8_t sec_tr_block = mf_classic_get_sector_trailer_num_by_sector(sector_num); + MfClassicSectorTrailer* sec_trailer = (MfClassicSectorTrailer*)&data->block[sec_tr_block]; + + return sec_trailer; +} + +bool mf_classic_is_sector_trailer(uint8_t block) { + return block == mf_classic_get_sector_trailer_num_by_block(block); +} + +uint8_t mf_classic_get_sector_by_block(uint8_t block) { + uint8_t sector = 0; + + if(block < 128) { + sector = (block | 0x03) / 4; + } else { + sector = 32 + ((block | 0x0f) - 32 * 4) / 16; + } + + return sector; +} + +bool mf_classic_block_to_value(const MfClassicBlock* block, int32_t* value, uint8_t* addr) { + furi_assert(block); + + uint32_t v = *(uint32_t*)&block->data[0]; + uint32_t v_inv = *(uint32_t*)&block->data[sizeof(uint32_t)]; + uint32_t v1 = *(uint32_t*)&block->data[sizeof(uint32_t) * 2]; + + bool val_checks = + ((v == v1) && (v == ~v_inv) && (block->data[12] == (~block->data[13] & 0xFF)) && + (block->data[14] == (~block->data[15] & 0xFF)) && (block->data[12] == block->data[14])); + if(value) { + *value = (int32_t)v; + } + if(addr) { + *addr = block->data[12]; + } + return val_checks; +} + +void mf_classic_value_to_block(int32_t value, uint8_t addr, MfClassicBlock* block) { + furi_assert(block); + + uint32_t v_inv = ~((uint32_t)value); + + memcpy(&block->data[0], &value, 4); //-V1086 + memcpy(&block->data[4], &v_inv, 4); //-V1086 + memcpy(&block->data[8], &value, 4); //-V1086 + + block->data[12] = addr; + block->data[13] = ~addr & 0xFF; + block->data[14] = addr; + block->data[15] = ~addr & 0xFF; +} + +bool mf_classic_is_key_found( + const MfClassicData* data, + uint8_t sector_num, + MfClassicKeyType key_type) { + furi_assert(data); + + bool key_found = false; + if(key_type == MfClassicKeyTypeA) { + key_found = (FURI_BIT(data->key_a_mask, sector_num) == 1); + } else if(key_type == MfClassicKeyTypeB) { + key_found = (FURI_BIT(data->key_b_mask, sector_num) == 1); + } + + return key_found; +} + +void mf_classic_set_key_found( + MfClassicData* data, + uint8_t sector_num, + MfClassicKeyType key_type, + uint64_t key) { + furi_assert(data); + + uint8_t key_arr[6] = {}; + MfClassicSectorTrailer* sec_trailer = + mf_classic_get_sector_trailer_by_sector(data, sector_num); + nfc_util_num2bytes(key, 6, key_arr); + if(key_type == MfClassicKeyTypeA) { + memcpy(sec_trailer->key_a.data, key_arr, sizeof(MfClassicKey)); + FURI_BIT_SET(data->key_a_mask, sector_num); + } else if(key_type == MfClassicKeyTypeB) { + memcpy(sec_trailer->key_b.data, key_arr, sizeof(MfClassicKey)); + FURI_BIT_SET(data->key_b_mask, sector_num); + } +} + +void mf_classic_set_key_not_found( + MfClassicData* data, + uint8_t sector_num, + MfClassicKeyType key_type) { + furi_assert(data); + + if(key_type == MfClassicKeyTypeA) { + FURI_BIT_CLEAR(data->key_a_mask, sector_num); + } else if(key_type == MfClassicKeyTypeB) { + FURI_BIT_CLEAR(data->key_b_mask, sector_num); + } +} + +bool mf_classic_is_block_read(const MfClassicData* data, uint8_t block_num) { + furi_assert(data); + + return (FURI_BIT(data->block_read_mask[block_num / 32], block_num % 32) == 1); +} + +void mf_classic_set_block_read(MfClassicData* data, uint8_t block_num, MfClassicBlock* block_data) { + furi_assert(data); + + if(mf_classic_is_sector_trailer(block_num)) { + memcpy(&data->block[block_num].data[6], &block_data->data[6], 4); + } else { + memcpy(data->block[block_num].data, block_data->data, MF_CLASSIC_BLOCK_SIZE); + } + FURI_BIT_SET(data->block_read_mask[block_num / 32], block_num % 32); +} + +uint8_t mf_classic_get_first_block_num_of_sector(uint8_t sector) { + furi_assert(sector < 40); + + uint8_t block = 0; + if(sector < 32) { + block = sector * 4; + } else { + block = 32 * 4 + (sector - 32) * 16; + } + + return block; +} + +uint8_t mf_classic_get_blocks_num_in_sector(uint8_t sector) { + furi_assert(sector < 40); + return sector < 32 ? 4 : 16; +} + +void mf_classic_get_read_sectors_and_keys( + const MfClassicData* data, + uint8_t* sectors_read, + uint8_t* keys_found) { + furi_assert(data); + furi_assert(sectors_read); + furi_assert(keys_found); + + *sectors_read = 0; + *keys_found = 0; + uint8_t sectors_total = mf_classic_get_total_sectors_num(data->type); + for(size_t i = 0; i < sectors_total; i++) { + if(mf_classic_is_key_found(data, i, MfClassicKeyTypeA)) { + *keys_found += 1; + } + if(mf_classic_is_key_found(data, i, MfClassicKeyTypeB)) { + *keys_found += 1; + } + uint8_t first_block = mf_classic_get_first_block_num_of_sector(i); + uint8_t total_blocks_in_sec = mf_classic_get_blocks_num_in_sector(i); + bool blocks_read = true; + for(size_t j = first_block; j < first_block + total_blocks_in_sec; j++) { + blocks_read = mf_classic_is_block_read(data, j); + if(!blocks_read) break; + } + if(blocks_read) { + *sectors_read += 1; + } + } +} + +bool mf_classic_is_card_read(const MfClassicData* data) { + furi_assert(data); + + uint8_t sectors_total = mf_classic_get_total_sectors_num(data->type); + uint8_t sectors_read = 0; + uint8_t keys_found = 0; + mf_classic_get_read_sectors_and_keys(data, §ors_read, &keys_found); + bool card_read = (sectors_read == sectors_total) && (keys_found == sectors_total * 2); + + return card_read; +} + +bool mf_classic_is_sector_read(const MfClassicData* data, uint8_t sector_num) { + furi_assert(data); + + bool sector_read = false; + do { + if(!mf_classic_is_key_found(data, sector_num, MfClassicKeyTypeA)) break; + if(!mf_classic_is_key_found(data, sector_num, MfClassicKeyTypeB)) break; + uint8_t start_block = mf_classic_get_first_block_num_of_sector(sector_num); + uint8_t total_blocks = mf_classic_get_blocks_num_in_sector(sector_num); + uint8_t block_read = true; + for(size_t i = start_block; i < start_block + total_blocks; i++) { + block_read = mf_classic_is_block_read(data, i); + if(!block_read) break; + } + sector_read = block_read; + } while(false); + + return sector_read; +} + +static bool mf_classic_is_allowed_access_sector_trailer( + MfClassicData* data, + uint8_t block_num, + MfClassicKeyType key_type, + MfClassicAction action) { + uint8_t sector_num = mf_classic_get_sector_by_block(block_num); + MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, sector_num); + uint8_t* access_bits_arr = sec_tr->access_bits.data; + uint8_t AC = ((access_bits_arr[1] >> 5) & 0x04) | ((access_bits_arr[2] >> 2) & 0x02) | + ((access_bits_arr[2] >> 7) & 0x01); + + switch(action) { + case MfClassicActionKeyARead: { + return false; + } + case MfClassicActionKeyAWrite: + case MfClassicActionKeyBWrite: { + return ( + (key_type == MfClassicKeyTypeA && (AC == 0x00 || AC == 0x01)) || + (key_type == MfClassicKeyTypeB && (AC == 0x04 || AC == 0x03))); + } + case MfClassicActionKeyBRead: { + return (key_type == MfClassicKeyTypeA && (AC == 0x00 || AC == 0x02 || AC == 0x01)); + } + case MfClassicActionACRead: { + return ( + (key_type == MfClassicKeyTypeA) || + (key_type == MfClassicKeyTypeB && !(AC == 0x00 || AC == 0x02 || AC == 0x01))); + } + case MfClassicActionACWrite: { + return ( + (key_type == MfClassicKeyTypeA && (AC == 0x01)) || + (key_type == MfClassicKeyTypeB && (AC == 0x03 || AC == 0x05))); + } + default: + return false; + } + return true; +} + +bool mf_classic_is_allowed_access_data_block( + MfClassicSectorTrailer* sec_tr, + uint8_t block_num, + MfClassicKeyType key_type, + MfClassicAction action) { + furi_assert(sec_tr); + + uint8_t* access_bits_arr = sec_tr->access_bits.data; + + if(block_num == 0 && action == MfClassicActionDataWrite) { + return false; + } + + uint8_t sector_block = 0; + if(block_num <= 128) { + sector_block = block_num & 0x03; + } else { + sector_block = (block_num & 0x0f) / 5; + } + + uint8_t AC; + switch(sector_block) { + case 0x00: { + AC = ((access_bits_arr[1] >> 2) & 0x04) | ((access_bits_arr[2] << 1) & 0x02) | + ((access_bits_arr[2] >> 4) & 0x01); + break; + } + case 0x01: { + AC = ((access_bits_arr[1] >> 3) & 0x04) | ((access_bits_arr[2] >> 0) & 0x02) | + ((access_bits_arr[2] >> 5) & 0x01); + break; + } + case 0x02: { + AC = ((access_bits_arr[1] >> 4) & 0x04) | ((access_bits_arr[2] >> 1) & 0x02) | + ((access_bits_arr[2] >> 6) & 0x01); + break; + } + default: + return false; + } + + switch(action) { + case MfClassicActionDataRead: { + return ( + (key_type == MfClassicKeyTypeA && !(AC == 0x03 || AC == 0x05 || AC == 0x07)) || + (key_type == MfClassicKeyTypeB && !(AC == 0x07))); + } + case MfClassicActionDataWrite: { + return ( + (key_type == MfClassicKeyTypeA && (AC == 0x00)) || + (key_type == MfClassicKeyTypeB && + (AC == 0x00 || AC == 0x04 || AC == 0x06 || AC == 0x03))); + } + case MfClassicActionDataInc: { + return ( + (key_type == MfClassicKeyTypeA && (AC == 0x00)) || + (key_type == MfClassicKeyTypeB && (AC == 0x00 || AC == 0x06))); + } + case MfClassicActionDataDec: { + return ( + (key_type == MfClassicKeyTypeA && (AC == 0x00 || AC == 0x06 || AC == 0x01)) || + (key_type == MfClassicKeyTypeB && (AC == 0x00 || AC == 0x06 || AC == 0x01))); + } + default: + return false; + } + + return false; +} + +bool mf_classic_is_allowed_access( + MfClassicData* data, + uint8_t block_num, + MfClassicKeyType key_type, + MfClassicAction action) { + furi_assert(data); + + bool access_allowed = false; + if(mf_classic_is_sector_trailer(block_num)) { + access_allowed = + mf_classic_is_allowed_access_sector_trailer(data, block_num, key_type, action); + } else { + uint8_t sector_num = mf_classic_get_sector_by_block(block_num); + MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, sector_num); + access_allowed = + mf_classic_is_allowed_access_data_block(sec_tr, block_num, key_type, action); + } + + return access_allowed; +} + +bool mf_classic_is_value_block(MfClassicSectorTrailer* sec_tr, uint8_t block_num) { + furi_assert(sec_tr); + + // Check if key A can write, if it can, it's transport configuration, not data block + return !mf_classic_is_allowed_access_data_block( + sec_tr, block_num, MfClassicKeyTypeA, MfClassicActionDataWrite) && + (mf_classic_is_allowed_access_data_block( + sec_tr, block_num, MfClassicKeyTypeB, MfClassicActionDataInc) || + mf_classic_is_allowed_access_data_block( + sec_tr, block_num, MfClassicKeyTypeB, MfClassicActionDataDec)); +} diff --git a/lib/nfc/protocols/mf_classic/mf_classic.h b/lib/nfc/protocols/mf_classic/mf_classic.h new file mode 100644 index 000000000..f180411df --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic.h @@ -0,0 +1,235 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define MF_CLASSIC_CMD_AUTH_KEY_A (0x60U) +#define MF_CLASSIC_CMD_AUTH_KEY_B (0x61U) +#define MF_CLASSIC_CMD_READ_BLOCK (0x30U) +#define MF_CLASSIC_CMD_WRITE_BLOCK (0xA0U) +#define MF_CLASSIC_CMD_VALUE_DEC (0xC0U) +#define MF_CLASSIC_CMD_VALUE_INC (0xC1U) +#define MF_CLASSIC_CMD_VALUE_RESTORE (0xC2U) +#define MF_CLASSIC_CMD_VALUE_TRANSFER (0xB0U) + +#define MF_CLASSIC_CMD_HALT_MSB (0x50) +#define MF_CLASSIC_CMD_HALT_LSB (0x00) +#define MF_CLASSIC_CMD_ACK (0x0A) +#define MF_CLASSIC_CMD_NACK (0x00) + +#define MF_CLASSIC_TOTAL_SECTORS_MAX (40) +#define MF_CLASSIC_TOTAL_BLOCKS_MAX (256) +#define MF_CLASSIC_READ_MASK_SIZE (MF_CLASSIC_TOTAL_BLOCKS_MAX / 32) +#define MF_CLASSIC_BLOCK_SIZE (16) +#define MF_CLASSIC_KEY_SIZE (6) +#define MF_CLASSIC_ACCESS_BYTES_SIZE (4) + +#define MF_CLASSIC_NT_SIZE (4) +#define MF_CLASSIC_NR_SIZE (4) +#define MF_CLASSIC_AR_SIZE (4) +#define MF_CLASSIC_AT_SIZE (4) + +typedef enum { + MfClassicErrorNone, + MfClassicErrorNotPresent, + MfClassicErrorProtocol, + MfClassicErrorAuth, + MfClassicErrorTimeout, +} MfClassicError; + +typedef enum { + MfClassicTypeMini, + MfClassicType1k, + MfClassicType4k, + + MfClassicTypeNum, +} MfClassicType; + +typedef enum { + MfClassicActionDataRead, + MfClassicActionDataWrite, + MfClassicActionDataInc, + MfClassicActionDataDec, + + MfClassicActionKeyARead, + MfClassicActionKeyAWrite, + MfClassicActionKeyBRead, + MfClassicActionKeyBWrite, + MfClassicActionACRead, + MfClassicActionACWrite, +} MfClassicAction; + +typedef enum { + MfClassicValueCommandIncrement, + MfClassicValueCommandDecrement, + MfClassicValueCommandRestore, + + MfClassicValueCommandInvalid, +} MfClassicValueCommand; + +typedef struct { + uint8_t data[MF_CLASSIC_BLOCK_SIZE]; +} MfClassicBlock; + +typedef enum { + MfClassicKeyTypeA, + MfClassicKeyTypeB, +} MfClassicKeyType; + +typedef struct { + uint8_t data[MF_CLASSIC_KEY_SIZE]; +} MfClassicKey; + +typedef struct { + uint8_t data[MF_CLASSIC_ACCESS_BYTES_SIZE]; +} MfClassicAccessBits; + +typedef struct { + uint8_t data[MF_CLASSIC_NT_SIZE]; +} MfClassicNt; + +typedef struct { + uint8_t data[MF_CLASSIC_AT_SIZE]; +} MfClassicAt; + +typedef struct { + uint8_t data[MF_CLASSIC_NR_SIZE]; +} MfClassicNr; + +typedef struct { + uint8_t data[MF_CLASSIC_AR_SIZE]; +} MfClassicAr; + +typedef struct { + uint8_t block_num; + MfClassicKey key; + MfClassicKeyType key_type; + MfClassicNt nt; + MfClassicNr nr; + MfClassicAr ar; + MfClassicAt at; +} MfClassicAuthContext; + +typedef union { + MfClassicBlock block; + struct { + MfClassicKey key_a; + MfClassicAccessBits access_bits; + MfClassicKey key_b; + }; +} MfClassicSectorTrailer; + +typedef struct { + uint64_t key_a_mask; + MfClassicKey key_a[MF_CLASSIC_TOTAL_SECTORS_MAX]; + uint64_t key_b_mask; + MfClassicKey key_b[MF_CLASSIC_TOTAL_SECTORS_MAX]; +} MfClassicDeviceKeys; + +typedef struct { + Iso14443_3aData* iso14443_3a_data; + MfClassicType type; + uint32_t block_read_mask[MF_CLASSIC_READ_MASK_SIZE]; + uint64_t key_a_mask; + uint64_t key_b_mask; + MfClassicBlock block[MF_CLASSIC_TOTAL_BLOCKS_MAX]; +} MfClassicData; + +extern const NfcDeviceBase nfc_device_mf_classic; + +MfClassicData* mf_classic_alloc(); + +void mf_classic_free(MfClassicData* data); + +void mf_classic_reset(MfClassicData* data); + +void mf_classic_copy(MfClassicData* data, const MfClassicData* other); + +bool mf_classic_verify(MfClassicData* data, const FuriString* device_type); + +bool mf_classic_load(MfClassicData* data, FlipperFormat* ff, uint32_t version); + +bool mf_classic_save(const MfClassicData* data, FlipperFormat* ff); + +bool mf_classic_is_equal(const MfClassicData* data, const MfClassicData* other); + +const char* mf_classic_get_device_name(const MfClassicData* data, NfcDeviceNameType name_type); + +const uint8_t* mf_classic_get_uid(const MfClassicData* data, size_t* uid_len); + +bool mf_classic_set_uid(MfClassicData* data, const uint8_t* uid, size_t uid_len); + +Iso14443_3aData* mf_classic_get_base_data(const MfClassicData* data); + +uint8_t mf_classic_get_total_sectors_num(MfClassicType type); + +uint16_t mf_classic_get_total_block_num(MfClassicType type); + +uint8_t mf_classic_get_first_block_num_of_sector(uint8_t sector); + +uint8_t mf_classic_get_blocks_num_in_sector(uint8_t sector); + +uint8_t mf_classic_get_sector_trailer_num_by_sector(uint8_t sector); + +uint8_t mf_classic_get_sector_trailer_num_by_block(uint8_t block); + +MfClassicSectorTrailer* + mf_classic_get_sector_trailer_by_sector(const MfClassicData* data, uint8_t sector_num); + +bool mf_classic_is_sector_trailer(uint8_t block); + +uint8_t mf_classic_get_sector_by_block(uint8_t block); + +bool mf_classic_block_to_value(const MfClassicBlock* block, int32_t* value, uint8_t* addr); + +void mf_classic_value_to_block(int32_t value, uint8_t addr, MfClassicBlock* block); + +bool mf_classic_is_key_found( + const MfClassicData* data, + uint8_t sector_num, + MfClassicKeyType key_type); + +void mf_classic_set_key_found( + MfClassicData* data, + uint8_t sector_num, + MfClassicKeyType key_type, + uint64_t key); + +void mf_classic_set_key_not_found( + MfClassicData* data, + uint8_t sector_num, + MfClassicKeyType key_type); + +bool mf_classic_is_block_read(const MfClassicData* data, uint8_t block_num); + +void mf_classic_set_block_read(MfClassicData* data, uint8_t block_num, MfClassicBlock* block_data); + +bool mf_classic_is_sector_read(const MfClassicData* data, uint8_t sector_num); + +void mf_classic_get_read_sectors_and_keys( + const MfClassicData* data, + uint8_t* sectors_read, + uint8_t* keys_found); + +bool mf_classic_is_card_read(const MfClassicData* data); + +bool mf_classic_is_value_block(MfClassicSectorTrailer* sec_tr, uint8_t block_num); + +bool mf_classic_is_allowed_access_data_block( + MfClassicSectorTrailer* sec_tr, + uint8_t block_num, + MfClassicKeyType key_type, + MfClassicAction action); + +bool mf_classic_is_allowed_access( + MfClassicData* data, + uint8_t block_num, + MfClassicKeyType key_type, + MfClassicAction action); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_classic/mf_classic_listener.c b/lib/nfc/protocols/mf_classic/mf_classic_listener.c new file mode 100644 index 000000000..f7bd5b3f4 --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_listener.c @@ -0,0 +1,656 @@ +#include "mf_classic_listener_i.h" + +#include + +#include +#include + +#include +#include + +#define TAG "MfClassicListener" + +#define MF_CLASSIC_MAX_BUFF_SIZE (64) + +typedef MfClassicListenerCommand ( + *MfClassicListenerCommandHandler)(MfClassicListener* instance, BitBuffer* buf); + +typedef struct { + uint8_t cmd_start_byte; + size_t cmd_len_bits; + size_t command_num; + MfClassicListenerCommandHandler* handler; +} MfClassicListenerCmd; + +static void mf_classic_listener_prepare_emulation(MfClassicListener* instance) { + instance->total_block_num = mf_classic_get_total_block_num(instance->data->type); +} + +static void mf_classic_listener_reset_state(MfClassicListener* instance) { + crypto1_reset(instance->crypto); + memset(&instance->auth_context, 0, sizeof(MfClassicAuthContext)); + instance->comm_state = MfClassicListenerCommStatePlain; + instance->state = MfClassicListenerStateIdle; + instance->cmd_in_progress = false; + instance->current_cmd_handler_idx = 0; + instance->transfer_value = 0; + instance->value_cmd = MfClassicValueCommandInvalid; +} + +static MfClassicListenerCommand + mf_classic_listener_halt_handler(MfClassicListener* instance, BitBuffer* buff) { + MfClassicListenerCommand command = MfClassicListenerCommandNack; + + if(bit_buffer_get_byte(buff, 1) == MF_CLASSIC_CMD_HALT_LSB) { + mf_classic_listener_reset_state(instance); + command = MfClassicListenerCommandSleep; + } + + return command; +} + +static MfClassicListenerCommand mf_classic_listener_auth_first_part_handler( + MfClassicListener* instance, + MfClassicKeyType key_type, + uint8_t block_num) { + MfClassicListenerCommand command = MfClassicListenerCommandNack; + + do { + instance->state = MfClassicListenerStateIdle; + + if(block_num >= instance->total_block_num) { + mf_classic_listener_reset_state(instance); + break; + } + + uint8_t sector_num = mf_classic_get_sector_by_block(block_num); + + MfClassicSectorTrailer* sec_tr = + mf_classic_get_sector_trailer_by_sector(instance->data, sector_num); + MfClassicKey* key = (key_type == MfClassicKeyTypeA) ? &sec_tr->key_a : &sec_tr->key_b; + uint64_t key_num = nfc_util_bytes2num(key->data, sizeof(MfClassicKey)); + uint32_t cuid = iso14443_3a_get_cuid(instance->data->iso14443_3a_data); + + instance->auth_context.key_type = key_type; + instance->auth_context.block_num = block_num; + + furi_hal_random_fill_buf(instance->auth_context.nt.data, sizeof(MfClassicNt)); + uint32_t nt_num = nfc_util_bytes2num(instance->auth_context.nt.data, sizeof(MfClassicNt)); + + crypto1_init(instance->crypto, key_num); + if(instance->comm_state == MfClassicListenerCommStatePlain) { + crypto1_word(instance->crypto, nt_num ^ cuid, 0); + bit_buffer_copy_bytes( + instance->tx_encrypted_buffer, + instance->auth_context.nt.data, + sizeof(MfClassicNt)); + iso14443_3a_listener_tx(instance->iso14443_3a_listener, instance->tx_encrypted_buffer); + command = MfClassicListenerCommandProcessed; + } else { + uint8_t key_stream[4] = {}; + nfc_util_num2bytes(nt_num ^ cuid, sizeof(uint32_t), key_stream); + bit_buffer_copy_bytes( + instance->tx_plain_buffer, instance->auth_context.nt.data, sizeof(MfClassicNt)); + crypto1_encrypt( + instance->crypto, + key_stream, + instance->tx_plain_buffer, + instance->tx_encrypted_buffer); + + iso14443_3a_listener_tx_with_custom_parity( + instance->iso14443_3a_listener, instance->tx_encrypted_buffer); + + command = MfClassicListenerCommandProcessed; + } + + instance->cmd_in_progress = true; + instance->current_cmd_handler_idx++; + } while(false); + + return command; +} + +static MfClassicListenerCommand + mf_classic_listener_auth_key_a_handler(MfClassicListener* instance, BitBuffer* buff) { + MfClassicListenerCommand command = mf_classic_listener_auth_first_part_handler( + instance, MfClassicKeyTypeA, bit_buffer_get_byte(buff, 1)); + + return command; +} + +static MfClassicListenerCommand + mf_classic_listener_auth_key_b_handler(MfClassicListener* instance, BitBuffer* buff) { + MfClassicListenerCommand command = mf_classic_listener_auth_first_part_handler( + instance, MfClassicKeyTypeB, bit_buffer_get_byte(buff, 1)); + + return command; +} + +static MfClassicListenerCommand + mf_classic_listener_auth_second_part_handler(MfClassicListener* instance, BitBuffer* buff) { + MfClassicListenerCommand command = MfClassicListenerCommandSilent; + + do { + instance->cmd_in_progress = false; + + if(bit_buffer_get_size_bytes(buff) != (sizeof(MfClassicNr) + sizeof(MfClassicAr))) { + mf_classic_listener_reset_state(instance); + break; + } + bit_buffer_write_bytes_mid(buff, instance->auth_context.nr.data, 0, sizeof(MfClassicNr)); + bit_buffer_write_bytes_mid( + buff, instance->auth_context.ar.data, sizeof(MfClassicNr), sizeof(MfClassicAr)); + + if(instance->callback) { + instance->mfc_event.type = MfClassicListenerEventTypeAuthContextPartCollected, + instance->mfc_event_data.auth_context = instance->auth_context; + instance->callback(instance->generic_event, instance->context); + } + + uint32_t nr_num = nfc_util_bytes2num(instance->auth_context.nr.data, sizeof(MfClassicNr)); + uint32_t ar_num = nfc_util_bytes2num(instance->auth_context.ar.data, sizeof(MfClassicAr)); + + crypto1_word(instance->crypto, nr_num, 1); + uint32_t nt_num = nfc_util_bytes2num(instance->auth_context.nt.data, sizeof(MfClassicNt)); + uint32_t secret_poller = ar_num ^ crypto1_word(instance->crypto, 0, 0); + if(secret_poller != prng_successor(nt_num, 64)) { + FURI_LOG_D( + TAG, "Wrong reader key: %08lX != %08lX", secret_poller, prng_successor(nt_num, 64)); + mf_classic_listener_reset_state(instance); + break; + } + + uint32_t at_num = prng_successor(nt_num, 96); + nfc_util_num2bytes(at_num, sizeof(uint32_t), instance->auth_context.at.data); + bit_buffer_copy_bytes( + instance->tx_plain_buffer, instance->auth_context.at.data, sizeof(MfClassicAr)); + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + iso14443_3a_listener_tx_with_custom_parity( + instance->iso14443_3a_listener, instance->tx_encrypted_buffer); + + instance->state = MfClassicListenerStateAuthComplete; + instance->comm_state = MfClassicListenerCommStateEncrypted; + command = MfClassicListenerCommandProcessed; + + if(instance->callback) { + instance->mfc_event.type = MfClassicListenerEventTypeAuthContextFullCollected, + instance->mfc_event_data.auth_context = instance->auth_context; + instance->callback(instance->generic_event, instance->context); + } + } while(false); + + return command; +} + +static MfClassicListenerCommand + mf_classic_listener_read_block_handler(MfClassicListener* instance, BitBuffer* buff) { + MfClassicListenerCommand command = MfClassicListenerCommandNack; + MfClassicAuthContext* auth_ctx = &instance->auth_context; + + do { + if(instance->state != MfClassicListenerStateAuthComplete) break; + + uint8_t block_num = bit_buffer_get_byte(buff, 1); + uint8_t sector_num = mf_classic_get_sector_by_block(block_num); + uint8_t auth_sector_num = mf_classic_get_sector_by_block(auth_ctx->block_num); + if(sector_num != auth_sector_num) break; + + MfClassicBlock access_block = instance->data->block[block_num]; + + if(mf_classic_is_sector_trailer(block_num)) { + MfClassicSectorTrailer* access_sec_tr = (MfClassicSectorTrailer*)&access_block; + if(!mf_classic_is_allowed_access( + instance->data, block_num, auth_ctx->key_type, MfClassicActionKeyARead)) { + memset(access_sec_tr->key_a.data, 0, sizeof(MfClassicKey)); + } + if(!mf_classic_is_allowed_access( + instance->data, block_num, auth_ctx->key_type, MfClassicActionKeyBRead)) { + memset(access_sec_tr->key_b.data, 0, sizeof(MfClassicKey)); + } + if(!mf_classic_is_allowed_access( + instance->data, block_num, auth_ctx->key_type, MfClassicActionACRead)) { + memset(access_sec_tr->access_bits.data, 0, sizeof(MfClassicAccessBits)); + } + } else if(!mf_classic_is_allowed_access( + instance->data, block_num, auth_ctx->key_type, MfClassicActionDataRead)) { + break; + } + + bit_buffer_copy_bytes( + instance->tx_plain_buffer, access_block.data, sizeof(MfClassicBlock)); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_plain_buffer); + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + iso14443_3a_listener_tx_with_custom_parity( + instance->iso14443_3a_listener, instance->tx_encrypted_buffer); + command = MfClassicListenerCommandProcessed; + } while(false); + + return command; +} + +static MfClassicListenerCommand mf_classic_listener_write_block_first_part_handler( + MfClassicListener* instance, + BitBuffer* buff) { + MfClassicListenerCommand command = MfClassicListenerCommandNack; + MfClassicAuthContext* auth_ctx = &instance->auth_context; + + do { + if(instance->state != MfClassicListenerStateAuthComplete) break; + + uint8_t block_num = bit_buffer_get_byte(buff, 1); + if(block_num >= instance->total_block_num) break; + + uint8_t sector_num = mf_classic_get_sector_by_block(block_num); + uint8_t auth_sector_num = mf_classic_get_sector_by_block(auth_ctx->block_num); + if(sector_num != auth_sector_num) break; + + instance->cmd_in_progress = true; + instance->current_cmd_handler_idx++; + command = MfClassicListenerCommandAck; + } while(false); + + return command; +} + +static MfClassicListenerCommand mf_classic_listener_write_block_second_part_handler( + MfClassicListener* instance, + BitBuffer* buff) { + MfClassicListenerCommand command = MfClassicListenerCommandNack; + MfClassicAuthContext* auth_ctx = &instance->auth_context; + + do { + instance->cmd_in_progress = false; + + size_t buff_size = bit_buffer_get_size_bytes(buff); + if(buff_size != sizeof(MfClassicBlock)) break; + + uint8_t block_num = auth_ctx->block_num; + MfClassicKeyType key_type = auth_ctx->key_type; + MfClassicBlock block = instance->data->block[block_num]; + + if(mf_classic_is_sector_trailer(block_num)) { + MfClassicSectorTrailer* sec_tr = (MfClassicSectorTrailer*)█ + if(mf_classic_is_allowed_access( + instance->data, block_num, key_type, MfClassicActionKeyAWrite)) { + bit_buffer_write_bytes_mid(buff, sec_tr->key_a.data, 0, sizeof(MfClassicKey)); + } + if(mf_classic_is_allowed_access( + instance->data, block_num, key_type, MfClassicActionKeyBWrite)) { + bit_buffer_write_bytes_mid(buff, sec_tr->key_b.data, 10, sizeof(MfClassicKey)); + } + if(mf_classic_is_allowed_access( + instance->data, block_num, key_type, MfClassicActionACWrite)) { + bit_buffer_write_bytes_mid( + buff, sec_tr->access_bits.data, 6, sizeof(MfClassicAccessBits)); + } + } else { + if(mf_classic_is_allowed_access( + instance->data, block_num, key_type, MfClassicActionDataWrite)) { + bit_buffer_write_bytes_mid(buff, block.data, 0, sizeof(MfClassicBlock)); + } else { + break; + } + } + + instance->data->block[block_num] = block; + command = MfClassicListenerCommandAck; + } while(false); + + return command; +} + +static MfClassicListenerCommand + mf_classic_listener_value_cmd_handler(MfClassicListener* instance, BitBuffer* buff) { + MfClassicListenerCommand command = MfClassicListenerCommandNack; + MfClassicAuthContext* auth_ctx = &instance->auth_context; + + do { + if(instance->state != MfClassicListenerStateAuthComplete) break; + + uint8_t block_num = bit_buffer_get_byte(buff, 1); + if(block_num >= instance->total_block_num) break; + + uint8_t sector_num = mf_classic_get_sector_by_block(block_num); + uint8_t auth_sector_num = mf_classic_get_sector_by_block(auth_ctx->block_num); + if(sector_num != auth_sector_num) break; + + uint8_t cmd = bit_buffer_get_byte(buff, 0); + MfClassicAction action = MfClassicActionDataDec; + if(cmd == MF_CLASSIC_CMD_VALUE_DEC) { + instance->value_cmd = MfClassicValueCommandDecrement; + } else if(cmd == MF_CLASSIC_CMD_VALUE_INC) { + instance->value_cmd = MfClassicValueCommandIncrement; + action = MfClassicActionDataInc; + } else if(cmd == MF_CLASSIC_CMD_VALUE_RESTORE) { + instance->value_cmd = MfClassicValueCommandRestore; + } else { + break; + } + + if(!mf_classic_is_allowed_access(instance->data, block_num, auth_ctx->key_type, action)) { + break; + } + + if(!mf_classic_block_to_value( + &instance->data->block[block_num], &instance->transfer_value, NULL)) { + break; + } + + instance->cmd_in_progress = true; + instance->current_cmd_handler_idx++; + command = MfClassicListenerCommandAck; + } while(false); + + return command; +} + +static MfClassicListenerCommand + mf_classic_listener_value_dec_handler(MfClassicListener* instance, BitBuffer* buff) { + return mf_classic_listener_value_cmd_handler(instance, buff); +} + +static MfClassicListenerCommand + mf_classic_listener_value_inc_handler(MfClassicListener* instance, BitBuffer* buff) { + return mf_classic_listener_value_cmd_handler(instance, buff); +} + +static MfClassicListenerCommand + mf_classic_listener_value_restore_handler(MfClassicListener* instance, BitBuffer* buff) { + return mf_classic_listener_value_cmd_handler(instance, buff); +} + +static MfClassicListenerCommand + mf_classic_listener_value_data_receive_handler(MfClassicListener* instance, BitBuffer* buff) { + MfClassicListenerCommand command = MfClassicListenerCommandNack; + + do { + if(bit_buffer_get_size_bytes(buff) != 4) break; + + int32_t data; + bit_buffer_write_bytes_mid(buff, &data, 0, sizeof(data)); + + if(data < 0) { + data = -data; + } + + if(instance->value_cmd == MfClassicValueCommandDecrement) { + data = -data; + } else if(instance->value_cmd == MfClassicValueCommandRestore) { + data = 0; + } + + instance->transfer_value += data; + + instance->cmd_in_progress = true; + instance->current_cmd_handler_idx++; + command = MfClassicListenerCommandSilent; + } while(false); + + return command; +} + +static MfClassicListenerCommand + mf_classic_listener_value_transfer_handler(MfClassicListener* instance, BitBuffer* buff) { + MfClassicListenerCommand command = MfClassicListenerCommandNack; + MfClassicAuthContext* auth_ctx = &instance->auth_context; + + do { + instance->cmd_in_progress = false; + + if(bit_buffer_get_size_bytes(buff) != 2) break; + if(bit_buffer_get_byte(buff, 0) != MF_CLASSIC_CMD_VALUE_TRANSFER) break; + + uint8_t block_num = bit_buffer_get_byte(buff, 1); + if(!mf_classic_is_allowed_access( + instance->data, block_num, auth_ctx->key_type, MfClassicActionDataDec)) { + break; + } + + mf_classic_value_to_block( + instance->transfer_value, block_num, &instance->data->block[block_num]); + instance->transfer_value = 0; + + command = MfClassicListenerCommandAck; + } while(false); + + return command; +} + +static MfClassicListenerCommandHandler mf_classic_listener_halt_handlers[] = { + mf_classic_listener_halt_handler, +}; + +static MfClassicListenerCommandHandler mf_classic_listener_auth_key_a_handlers[] = { + mf_classic_listener_auth_key_a_handler, + mf_classic_listener_auth_second_part_handler, +}; + +static MfClassicListenerCommandHandler mf_classic_listener_auth_key_b_handlers[] = { + mf_classic_listener_auth_key_b_handler, + mf_classic_listener_auth_second_part_handler, +}; + +static MfClassicListenerCommandHandler mf_classic_listener_read_block_handlers[] = { + mf_classic_listener_read_block_handler, +}; + +static MfClassicListenerCommandHandler mf_classic_listener_write_block_handlers[] = { + mf_classic_listener_write_block_first_part_handler, + mf_classic_listener_write_block_second_part_handler, +}; + +static MfClassicListenerCommandHandler mf_classic_listener_value_dec_handlers[] = { + mf_classic_listener_value_dec_handler, + mf_classic_listener_value_data_receive_handler, + mf_classic_listener_value_transfer_handler, +}; + +static MfClassicListenerCommandHandler mf_classic_listener_value_inc_handlers[] = { + mf_classic_listener_value_inc_handler, + mf_classic_listener_value_data_receive_handler, + mf_classic_listener_value_transfer_handler, +}; + +static MfClassicListenerCommandHandler mf_classic_listener_value_restore_handlers[] = { + mf_classic_listener_value_restore_handler, + mf_classic_listener_value_data_receive_handler, + mf_classic_listener_value_transfer_handler, +}; + +static const MfClassicListenerCmd mf_classic_listener_cmd_handlers[] = { + { + .cmd_start_byte = MF_CLASSIC_CMD_HALT_MSB, + .cmd_len_bits = 2 * 8, + .command_num = COUNT_OF(mf_classic_listener_halt_handlers), + .handler = mf_classic_listener_halt_handlers, + }, + { + .cmd_start_byte = MF_CLASSIC_CMD_AUTH_KEY_A, + .cmd_len_bits = 2 * 8, + .command_num = COUNT_OF(mf_classic_listener_auth_key_a_handlers), + .handler = mf_classic_listener_auth_key_a_handlers, + }, + { + .cmd_start_byte = MF_CLASSIC_CMD_AUTH_KEY_B, + .cmd_len_bits = 2 * 8, + .command_num = COUNT_OF(mf_classic_listener_auth_key_b_handlers), + .handler = mf_classic_listener_auth_key_b_handlers, + }, + { + .cmd_start_byte = MF_CLASSIC_CMD_READ_BLOCK, + .cmd_len_bits = 2 * 8, + .command_num = COUNT_OF(mf_classic_listener_read_block_handlers), + .handler = mf_classic_listener_read_block_handlers, + }, + { + .cmd_start_byte = MF_CLASSIC_CMD_WRITE_BLOCK, + .cmd_len_bits = 2 * 8, + .command_num = COUNT_OF(mf_classic_listener_write_block_handlers), + .handler = mf_classic_listener_write_block_handlers, + }, + { + .cmd_start_byte = MF_CLASSIC_CMD_VALUE_DEC, + .cmd_len_bits = 2 * 8, + .command_num = COUNT_OF(mf_classic_listener_value_dec_handlers), + .handler = mf_classic_listener_value_dec_handlers, + }, + { + .cmd_start_byte = MF_CLASSIC_CMD_VALUE_INC, + .cmd_len_bits = 2 * 8, + .command_num = COUNT_OF(mf_classic_listener_value_inc_handlers), + .handler = mf_classic_listener_value_inc_handlers, + }, + { + .cmd_start_byte = MF_CLASSIC_CMD_VALUE_RESTORE, + .cmd_len_bits = 2 * 8, + .command_num = COUNT_OF(mf_classic_listener_value_restore_handlers), + .handler = mf_classic_listener_value_restore_handlers, + }, +}; + +static void mf_classic_listener_send_short_frame(MfClassicListener* instance, uint8_t data) { + BitBuffer* tx_buffer = instance->tx_plain_buffer; + + bit_buffer_set_size(instance->tx_plain_buffer, 4); + bit_buffer_set_byte(instance->tx_plain_buffer, 0, data); + if(instance->comm_state == MfClassicListenerCommStateEncrypted) { + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + tx_buffer = instance->tx_encrypted_buffer; + } + + iso14443_3a_listener_tx_with_custom_parity(instance->iso14443_3a_listener, tx_buffer); +} + +NfcCommand mf_classic_listener_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + + NfcCommand command = NfcCommandContinue; + MfClassicListener* instance = context; + Iso14443_3aListenerEvent* iso3_event = event.event_data; + BitBuffer* rx_buffer_plain; + + if(iso3_event->type == Iso14443_3aListenerEventTypeFieldOff) { + mf_classic_listener_reset_state(instance); + command = NfcCommandSleep; + } else if( + (iso3_event->type == Iso14443_3aListenerEventTypeReceivedData) || + (iso3_event->type == Iso14443_3aListenerEventTypeReceivedStandardFrame)) { + if(instance->comm_state == MfClassicListenerCommStateEncrypted) { + if(instance->state == MfClassicListenerStateAuthComplete) { + crypto1_decrypt( + instance->crypto, iso3_event->data->buffer, instance->rx_plain_buffer); + rx_buffer_plain = instance->rx_plain_buffer; + if(iso14443_crc_check(Iso14443CrcTypeA, rx_buffer_plain)) { + iso14443_crc_trim(rx_buffer_plain); + } + } else { + rx_buffer_plain = iso3_event->data->buffer; + } + } else { + rx_buffer_plain = iso3_event->data->buffer; + } + + MfClassicListenerCommand mfc_command = MfClassicListenerCommandNack; + if(instance->cmd_in_progress) { + mfc_command = + mf_classic_listener_cmd_handlers[instance->current_cmd_idx] + .handler[instance->current_cmd_handler_idx](instance, rx_buffer_plain); + } else { + for(size_t i = 0; i < COUNT_OF(mf_classic_listener_cmd_handlers); i++) { + if(bit_buffer_get_size(rx_buffer_plain) != + mf_classic_listener_cmd_handlers[i].cmd_len_bits) { + continue; + } + if(bit_buffer_get_byte(rx_buffer_plain, 0) != + mf_classic_listener_cmd_handlers[i].cmd_start_byte) { + continue; + } + instance->current_cmd_idx = i; + instance->current_cmd_handler_idx = 0; + mfc_command = + mf_classic_listener_cmd_handlers[i].handler[0](instance, rx_buffer_plain); + break; + } + } + + if(mfc_command == MfClassicListenerCommandAck) { + mf_classic_listener_send_short_frame(instance, MF_CLASSIC_CMD_ACK); + } else if(mfc_command == MfClassicListenerCommandNack) { + mf_classic_listener_send_short_frame(instance, MF_CLASSIC_CMD_NACK); + } else if(mfc_command == MfClassicListenerCommandSilent) { + command = NfcCommandReset; + } else if(mfc_command == MfClassicListenerCommandSleep) { + command = NfcCommandSleep; + } + } else if(iso3_event->type == Iso14443_3aListenerEventTypeHalted) { + mf_classic_listener_reset_state(instance); + } + + return command; +} + +MfClassicListener* + mf_classic_listener_alloc(Iso14443_3aListener* iso14443_3a_listener, MfClassicData* data) { + MfClassicListener* instance = malloc(sizeof(MfClassicListener)); + instance->iso14443_3a_listener = iso14443_3a_listener; + instance->data = data; + mf_classic_listener_prepare_emulation(instance); + + instance->crypto = crypto1_alloc(); + instance->tx_plain_buffer = bit_buffer_alloc(MF_CLASSIC_MAX_BUFF_SIZE); + instance->tx_encrypted_buffer = bit_buffer_alloc(MF_CLASSIC_MAX_BUFF_SIZE); + instance->rx_plain_buffer = bit_buffer_alloc(MF_CLASSIC_MAX_BUFF_SIZE); + + instance->mfc_event.data = &instance->mfc_event_data; + instance->generic_event.protocol = NfcProtocolMfClassic; + instance->generic_event.event_data = &instance->mfc_event; + instance->generic_event.instance = instance; + + return instance; +} + +void mf_classic_listener_free(MfClassicListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + furi_assert(instance->crypto); + furi_assert(instance->rx_plain_buffer); + furi_assert(instance->tx_encrypted_buffer); + furi_assert(instance->tx_plain_buffer); + + crypto1_free(instance->crypto); + bit_buffer_free(instance->rx_plain_buffer); + bit_buffer_free(instance->tx_encrypted_buffer); + bit_buffer_free(instance->tx_plain_buffer); + + free(instance); +} + +void mf_classic_listener_set_callback( + MfClassicListener* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + + instance->callback = callback; + instance->context = context; +} + +const MfClassicData* mf_classic_listener_get_data(const MfClassicListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +const NfcListenerBase mf_classic_listener = { + .alloc = (NfcListenerAlloc)mf_classic_listener_alloc, + .free = (NfcListenerFree)mf_classic_listener_free, + .set_callback = (NfcListenerSetCallback)mf_classic_listener_set_callback, + .get_data = (NfcListenerGetData)mf_classic_listener_get_data, + .run = (NfcListenerRun)mf_classic_listener_run, +}; diff --git a/lib/nfc/protocols/mf_classic/mf_classic_listener.h b/lib/nfc/protocols/mf_classic/mf_classic_listener.h new file mode 100644 index 000000000..5169de62d --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_listener.h @@ -0,0 +1,27 @@ +#pragma once + +#include "mf_classic.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct MfClassicListener MfClassicListener; + +typedef enum { + MfClassicListenerEventTypeAuthContextPartCollected, + MfClassicListenerEventTypeAuthContextFullCollected, +} MfClassicListenerEventType; + +typedef union { + MfClassicAuthContext auth_context; +} MfClassicListenerEventData; + +typedef struct { + MfClassicListenerEventType type; + MfClassicListenerEventData* data; +} MfClassicListenerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_classic/mf_classic_listener_defs.h b/lib/nfc/protocols/mf_classic/mf_classic_listener_defs.h new file mode 100644 index 000000000..6c7a1dd6a --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_listener_defs.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NfcListenerBase mf_classic_listener; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_classic/mf_classic_listener_i.h b/lib/nfc/protocols/mf_classic/mf_classic_listener_i.h new file mode 100644 index 000000000..4b040bec1 --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_listener_i.h @@ -0,0 +1,62 @@ +#pragma once + +#include "mf_classic_listener.h" +#include +#include +#include "crypto1.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + MfClassicListenerCommandProcessed, + MfClassicListenerCommandAck, + MfClassicListenerCommandNack, + MfClassicListenerCommandSilent, + MfClassicListenerCommandSleep, +} MfClassicListenerCommand; + +typedef enum { + MfClassicListenerStateIdle, + MfClassicListenerStateAuthComplete, +} MfClassicListenerState; + +typedef enum { + MfClassicListenerCommStatePlain, + MfClassicListenerCommStateEncrypted, +} MfClassicListenerCommState; + +struct MfClassicListener { + Iso14443_3aListener* iso14443_3a_listener; + MfClassicListenerState state; + MfClassicListenerCommState comm_state; + + MfClassicData* data; + BitBuffer* tx_plain_buffer; + BitBuffer* tx_encrypted_buffer; + BitBuffer* rx_plain_buffer; + + Crypto1* crypto; + MfClassicAuthContext auth_context; + + // Value operation data + int32_t transfer_value; + MfClassicValueCommand value_cmd; + + NfcGenericEvent generic_event; + MfClassicListenerEvent mfc_event; + MfClassicListenerEventData mfc_event_data; + NfcGenericCallback callback; + void* context; + + bool cmd_in_progress; + size_t current_cmd_idx; + size_t current_cmd_handler_idx; + + size_t total_block_num; +}; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_classic/mf_classic_poller.c b/lib/nfc/protocols/mf_classic/mf_classic_poller.c new file mode 100644 index 000000000..3eba6ee56 --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_poller.c @@ -0,0 +1,951 @@ +#include "mf_classic_poller_i.h" + +#include + +#include + +#define TAG "MfClassicPoller" + +#define MF_CLASSIC_MAX_BUFF_SIZE (64) + +typedef NfcCommand (*MfClassicPollerReadHandler)(MfClassicPoller* instance); + +MfClassicPoller* mf_classic_poller_alloc(Iso14443_3aPoller* iso14443_3a_poller) { + furi_assert(iso14443_3a_poller); + + MfClassicPoller* instance = malloc(sizeof(MfClassicPoller)); + instance->iso14443_3a_poller = iso14443_3a_poller; + instance->data = mf_classic_alloc(); + instance->crypto = crypto1_alloc(); + instance->tx_plain_buffer = bit_buffer_alloc(MF_CLASSIC_MAX_BUFF_SIZE); + instance->tx_encrypted_buffer = bit_buffer_alloc(MF_CLASSIC_MAX_BUFF_SIZE); + instance->rx_plain_buffer = bit_buffer_alloc(MF_CLASSIC_MAX_BUFF_SIZE); + instance->rx_encrypted_buffer = bit_buffer_alloc(MF_CLASSIC_MAX_BUFF_SIZE); + instance->current_type_check = MfClassicType4k; + + instance->mfc_event.data = &instance->mfc_event_data; + + instance->general_event.protocol = NfcProtocolMfClassic; + instance->general_event.event_data = &instance->mfc_event; + instance->general_event.instance = instance; + + return instance; +} + +void mf_classic_poller_free(MfClassicPoller* instance) { + furi_assert(instance); + furi_assert(instance->data); + furi_assert(instance->crypto); + furi_assert(instance->tx_plain_buffer); + furi_assert(instance->rx_plain_buffer); + furi_assert(instance->tx_encrypted_buffer); + furi_assert(instance->rx_encrypted_buffer); + + mf_classic_free(instance->data); + crypto1_free(instance->crypto); + bit_buffer_free(instance->tx_plain_buffer); + bit_buffer_free(instance->rx_plain_buffer); + bit_buffer_free(instance->tx_encrypted_buffer); + bit_buffer_free(instance->rx_encrypted_buffer); + + free(instance); +} + +static NfcCommand mf_classic_poller_handle_data_update(MfClassicPoller* instance) { + MfClassicPollerEventDataUpdate* data_update = &instance->mfc_event_data.data_update; + + mf_classic_get_read_sectors_and_keys( + instance->data, &data_update->sectors_read, &data_update->keys_found); + data_update->current_sector = instance->mode_ctx.dict_attack_ctx.current_sector; + instance->mfc_event.type = MfClassicPollerEventTypeDataUpdate; + return instance->callback(instance->general_event, instance->context); +} + +static void mf_classic_poller_check_key_b_is_readable( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicBlock* data) { + do { + if(!mf_classic_is_sector_trailer(block_num)) break; + if(!mf_classic_is_allowed_access( + instance->data, block_num, MfClassicKeyTypeA, MfClassicActionKeyBRead)) + break; + + MfClassicSectorTrailer* sec_tr = (MfClassicSectorTrailer*)data; + uint64_t key_b = nfc_util_bytes2num(sec_tr->key_b.data, sizeof(MfClassicKey)); + uint8_t sector_num = mf_classic_get_sector_by_block(block_num); + mf_classic_set_key_found(instance->data, sector_num, MfClassicKeyTypeB, key_b); + } while(false); +} + +NfcCommand mf_classic_poller_handler_detect_type(MfClassicPoller* instance) { + NfcCommand command = NfcCommandReset; + + if(instance->current_type_check == MfClassicType4k) { + iso14443_3a_copy( + instance->data->iso14443_3a_data, + iso14443_3a_poller_get_data(instance->iso14443_3a_poller)); + MfClassicError error = mf_classic_async_get_nt(instance, 254, MfClassicKeyTypeA, NULL); + if(error == MfClassicErrorNone) { + instance->data->type = MfClassicType4k; + instance->state = MfClassicPollerStateStart; + instance->current_type_check = MfClassicType4k; + FURI_LOG_D(TAG, "4K detected"); + } else { + instance->current_type_check = MfClassicType1k; + } + } else if(instance->current_type_check == MfClassicType1k) { + MfClassicError error = mf_classic_async_get_nt(instance, 62, MfClassicKeyTypeA, NULL); + if(error == MfClassicErrorNone) { + instance->data->type = MfClassicType1k; + FURI_LOG_D(TAG, "1K detected"); + } else { + instance->data->type = MfClassicTypeMini; + FURI_LOG_D(TAG, "Mini detected"); + } + instance->current_type_check = MfClassicType4k; + instance->state = MfClassicPollerStateStart; + } + + return command; +} + +NfcCommand mf_classic_poller_handler_start(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + + instance->sectors_total = mf_classic_get_total_sectors_num(instance->data->type); + memset(&instance->mode_ctx, 0, sizeof(MfClassicPollerModeContext)); + + instance->mfc_event.type = MfClassicPollerEventTypeRequestMode; + command = instance->callback(instance->general_event, instance->context); + + if(instance->mfc_event_data.poller_mode.mode == MfClassicPollerModeDictAttack) { + mf_classic_copy(instance->data, instance->mfc_event_data.poller_mode.data); + instance->state = MfClassicPollerStateRequestKey; + } else if(instance->mfc_event_data.poller_mode.mode == MfClassicPollerModeRead) { + instance->state = MfClassicPollerStateRequestReadSector; + } else if(instance->mfc_event_data.poller_mode.mode == MfClassicPollerModeWrite) { + instance->state = MfClassicPollerStateRequestSectorTrailer; + } else { + furi_crash("Invalid mode selected"); + } + + return command; +} + +NfcCommand mf_classic_poller_handler_request_sector_trailer(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerWriteContext* write_ctx = &instance->mode_ctx.write_ctx; + + if(write_ctx->current_sector == instance->sectors_total) { + instance->state = MfClassicPollerStateSuccess; + } else { + instance->mfc_event.type = MfClassicPollerEventTypeRequestSectorTrailer; + instance->mfc_event_data.sec_tr_data.sector_num = write_ctx->current_sector; + command = instance->callback(instance->general_event, instance->context); + if(instance->mfc_event_data.sec_tr_data.sector_trailer_provided) { + instance->state = MfClassicPollerStateCheckWriteConditions; + memcpy( + &write_ctx->sec_tr, + &instance->mfc_event_data.sec_tr_data.sector_trailer, + sizeof(MfClassicSectorTrailer)); + write_ctx->current_block = + MAX(1, mf_classic_get_first_block_num_of_sector(write_ctx->current_sector)); + + } else { + write_ctx->current_sector++; + } + } + + return command; +} + +NfcCommand mf_classic_handler_check_write_conditions(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + + MfClassicPollerWriteContext* write_ctx = &instance->mode_ctx.write_ctx; + MfClassicSectorTrailer* sec_tr = &write_ctx->sec_tr; + + do { + // Check last block in sector to write + uint8_t sec_tr_block_num = + mf_classic_get_sector_trailer_num_by_sector(write_ctx->current_sector); + if(write_ctx->current_block == sec_tr_block_num) { + write_ctx->current_sector++; + instance->state = MfClassicPollerStateRequestSectorTrailer; + break; + } + + // Check write and read access + if(mf_classic_is_allowed_access_data_block( + sec_tr, write_ctx->current_block, MfClassicKeyTypeA, MfClassicActionDataWrite)) { + write_ctx->key_type_write = MfClassicKeyTypeA; + } else if(mf_classic_is_allowed_access_data_block( + sec_tr, + write_ctx->current_block, + MfClassicKeyTypeB, + MfClassicActionDataWrite)) { + write_ctx->key_type_write = MfClassicKeyTypeB; + } else if(mf_classic_is_value_block(sec_tr, write_ctx->current_block)) { + write_ctx->is_value_block = true; + } else { + FURI_LOG_D(TAG, "Not allowed to write block %d", write_ctx->current_block); + write_ctx->current_block++; + break; + } + + if(mf_classic_is_allowed_access_data_block( + sec_tr, + write_ctx->current_block, + write_ctx->key_type_write, + MfClassicActionDataRead)) { + write_ctx->key_type_read = write_ctx->key_type_write; + } else { + write_ctx->key_type_read = write_ctx->key_type_write == MfClassicKeyTypeA ? + MfClassicKeyTypeB : + MfClassicKeyTypeA; + if(!mf_classic_is_allowed_access_data_block( + sec_tr, + write_ctx->current_block, + write_ctx->key_type_read, + MfClassicActionDataRead)) { + FURI_LOG_D(TAG, "Not allowed to read block %d", write_ctx->current_block); + write_ctx->current_block++; + break; + } + } + + write_ctx->need_halt_before_write = + (write_ctx->key_type_read != write_ctx->key_type_write); + instance->state = MfClassicPollerStateReadBlock; + } while(false); + + return command; +} + +NfcCommand mf_classic_poller_handler_read_block(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerWriteContext* write_ctx = &instance->mode_ctx.write_ctx; + + MfClassicKey* auth_key = write_ctx->key_type_read == MfClassicKeyTypeA ? + &write_ctx->sec_tr.key_a : + &write_ctx->sec_tr.key_b; + MfClassicError error = MfClassicErrorNone; + + do { + // Authenticate to sector + error = mf_classic_async_auth( + instance, write_ctx->current_block, auth_key, write_ctx->key_type_read, NULL); + if(error != MfClassicErrorNone) { + FURI_LOG_D(TAG, "Failed to auth to block %d", write_ctx->current_block); + instance->state = MfClassicPollerStateFail; + break; + } + + // Read block from tag + error = + mf_classic_async_read_block(instance, write_ctx->current_block, &write_ctx->tag_block); + if(error != MfClassicErrorNone) { + FURI_LOG_D(TAG, "Failed to read block %d", write_ctx->current_block); + instance->state = MfClassicPollerStateFail; + break; + } + + if(write_ctx->is_value_block) { + mf_classic_async_halt(instance); + instance->state = MfClassicPollerStateWriteValueBlock; + } else { + if(write_ctx->need_halt_before_write) { + mf_classic_async_halt(instance); + } + instance->state = MfClassicPollerStateWriteBlock; + } + } while(false); + + return command; +} + +NfcCommand mf_classic_poller_handler_write_block(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + + MfClassicPollerWriteContext* write_ctx = &instance->mode_ctx.write_ctx; + MfClassicKey* auth_key = write_ctx->key_type_write == MfClassicKeyTypeA ? + &write_ctx->sec_tr.key_a : + &write_ctx->sec_tr.key_b; + MfClassicError error = MfClassicErrorNone; + + do { + // Request block to write + instance->mfc_event.type = MfClassicPollerEventTypeRequestWriteBlock; + instance->mfc_event_data.write_block_data.block_num = write_ctx->current_block; + command = instance->callback(instance->general_event, instance->context); + if(!instance->mfc_event_data.write_block_data.write_block_provided) break; + + // Compare tag and saved block + if(memcmp( + write_ctx->tag_block.data, + instance->mfc_event_data.write_block_data.write_block.data, + sizeof(MfClassicBlock)) == 0) { + FURI_LOG_D(TAG, "Block %d is equal. Skip writing", write_ctx->current_block); + break; + } + + // Reauth if necessary + if(write_ctx->need_halt_before_write) { + error = mf_classic_async_auth( + instance, write_ctx->current_block, auth_key, write_ctx->key_type_write, NULL); + if(error != MfClassicErrorNone) { + FURI_LOG_D( + TAG, "Failed to auth to block %d for writing", write_ctx->current_block); + instance->state = MfClassicPollerStateFail; + break; + } + } + + // Write block + error = mf_classic_async_write_block( + instance, + write_ctx->current_block, + &instance->mfc_event_data.write_block_data.write_block); + if(error != MfClassicErrorNone) { + FURI_LOG_D(TAG, "Failed to write block %d", write_ctx->current_block); + instance->state = MfClassicPollerStateFail; + break; + } + + } while(false); + + mf_classic_async_halt(instance); + write_ctx->current_block++; + instance->state = MfClassicPollerStateCheckWriteConditions; + + return command; +} + +NfcCommand mf_classic_poller_handler_write_value_block(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerWriteContext* write_ctx = &instance->mode_ctx.write_ctx; + + do { + // Request block to write + instance->mfc_event.type = MfClassicPollerEventTypeRequestWriteBlock; + instance->mfc_event_data.write_block_data.block_num = write_ctx->current_block; + command = instance->callback(instance->general_event, instance->context); + if(!instance->mfc_event_data.write_block_data.write_block_provided) break; + + // Compare tag and saved block + if(memcmp( + write_ctx->tag_block.data, + instance->mfc_event_data.write_block_data.write_block.data, + sizeof(MfClassicBlock)) == 0) { + FURI_LOG_D(TAG, "Block %d is equal. Skip writing", write_ctx->current_block); + break; + } + + bool key_a_inc_allowed = mf_classic_is_allowed_access_data_block( + &write_ctx->sec_tr, + write_ctx->current_block, + MfClassicKeyTypeA, + MfClassicActionDataInc); + bool key_b_inc_allowed = mf_classic_is_allowed_access_data_block( + &write_ctx->sec_tr, + write_ctx->current_block, + MfClassicKeyTypeB, + MfClassicActionDataInc); + bool key_a_dec_allowed = mf_classic_is_allowed_access_data_block( + &write_ctx->sec_tr, + write_ctx->current_block, + MfClassicKeyTypeA, + MfClassicActionDataDec); + bool key_b_dec_allowed = mf_classic_is_allowed_access_data_block( + &write_ctx->sec_tr, + write_ctx->current_block, + MfClassicKeyTypeB, + MfClassicActionDataDec); + + int32_t source_value = 0; + int32_t target_value = 0; + if(!mf_classic_block_to_value( + &instance->mfc_event_data.write_block_data.write_block, &source_value, NULL)) + break; + if(!mf_classic_block_to_value(&write_ctx->tag_block, &target_value, NULL)) break; + + MfClassicKeyType auth_key_type = MfClassicKeyTypeA; + MfClassicValueCommand value_cmd = MfClassicValueCommandIncrement; + int32_t diff = source_value - target_value; + if(diff > 0) { + if(key_a_inc_allowed) { + auth_key_type = MfClassicKeyTypeA; + value_cmd = MfClassicValueCommandIncrement; + } else if(key_b_inc_allowed) { + auth_key_type = MfClassicKeyTypeB; + value_cmd = MfClassicValueCommandIncrement; + } else { + FURI_LOG_D(TAG, "Unable to increment value block"); + break; + } + } else { + if(key_a_dec_allowed) { + auth_key_type = MfClassicKeyTypeA; + value_cmd = MfClassicValueCommandDecrement; + diff *= -1; + } else if(key_b_dec_allowed) { + auth_key_type = MfClassicKeyTypeB; + value_cmd = MfClassicValueCommandDecrement; + diff *= -1; + } else { + FURI_LOG_D(TAG, "Unable to decrement value block"); + break; + } + } + + MfClassicKey* key = (auth_key_type == MfClassicKeyTypeA) ? &write_ctx->sec_tr.key_a : + &write_ctx->sec_tr.key_b; + + MfClassicError error = + mf_classic_async_auth(instance, write_ctx->current_block, key, auth_key_type, NULL); + if(error != MfClassicErrorNone) break; + + error = mf_classic_async_value_cmd(instance, write_ctx->current_block, value_cmd, diff); + if(error != MfClassicErrorNone) break; + + error = mf_classic_async_value_transfer(instance, write_ctx->current_block); + if(error != MfClassicErrorNone) break; + + } while(false); + + mf_classic_async_halt(instance); + write_ctx->is_value_block = false; + write_ctx->current_block++; + instance->state = MfClassicPollerStateCheckWriteConditions; + + return command; +} + +NfcCommand mf_classic_poller_handler_request_read_sector(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + + MfClassicPollerReadContext* sec_read_ctx = &instance->mode_ctx.read_ctx; + MfClassicPollerEventDataReadSectorRequest* sec_read = + &instance->mfc_event_data.read_sector_request_data; + instance->mfc_event.type = MfClassicPollerEventTypeRequestReadSector; + command = instance->callback(instance->general_event, instance->context); + + if(!sec_read->key_provided) { + instance->state = MfClassicPollerStateSuccess; + } else { + sec_read_ctx->current_sector = sec_read->sector_num; + sec_read_ctx->key = sec_read->key; + sec_read_ctx->key_type = sec_read->key_type; + sec_read_ctx->current_block = + mf_classic_get_first_block_num_of_sector(sec_read->sector_num); + sec_read_ctx->auth_passed = false; + instance->state = MfClassicPollerStateReadSectorBlocks; + } + + return command; +} + +NfcCommand mf_classic_poller_handler_request_read_sector_blocks(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + + MfClassicPollerReadContext* sec_read_ctx = &instance->mode_ctx.read_ctx; + + do { + MfClassicError error = MfClassicErrorNone; + + if(!sec_read_ctx->auth_passed) { + uint64_t key = nfc_util_bytes2num(sec_read_ctx->key.data, sizeof(MfClassicKey)); + FURI_LOG_D( + TAG, + "Auth to block %d with key %c: %06llx", + sec_read_ctx->current_block, + sec_read_ctx->key_type == MfClassicKeyTypeA ? 'A' : 'B', + key); + error = mf_classic_async_auth( + instance, + sec_read_ctx->current_block, + &sec_read_ctx->key, + sec_read_ctx->key_type, + NULL); + if(error != MfClassicErrorNone) break; + + sec_read_ctx->auth_passed = true; + if(!mf_classic_is_key_found( + instance->data, sec_read_ctx->current_sector, sec_read_ctx->key_type)) { + mf_classic_set_key_found( + instance->data, sec_read_ctx->current_sector, sec_read_ctx->key_type, key); + } + } + if(mf_classic_is_block_read(instance->data, sec_read_ctx->current_block)) break; + + FURI_LOG_D(TAG, "Reading block %d", sec_read_ctx->current_block); + MfClassicBlock read_block = {}; + error = mf_classic_async_read_block(instance, sec_read_ctx->current_block, &read_block); + if(error == MfClassicErrorNone) { + mf_classic_set_block_read(instance->data, sec_read_ctx->current_block, &read_block); + if(sec_read_ctx->key_type == MfClassicKeyTypeA) { + mf_classic_poller_check_key_b_is_readable( + instance, sec_read_ctx->current_block, &read_block); + } + } else { + mf_classic_async_halt(instance); + sec_read_ctx->auth_passed = false; + } + } while(false); + + uint8_t sec_tr_num = mf_classic_get_sector_trailer_num_by_sector(sec_read_ctx->current_sector); + sec_read_ctx->current_block++; + if(sec_read_ctx->current_block > sec_tr_num) { + mf_classic_async_halt(instance); + instance->state = MfClassicPollerStateRequestReadSector; + } + + return command; +} + +NfcCommand mf_classic_poller_handler_request_key(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerDictAttackContext* dict_attack_ctx = &instance->mode_ctx.dict_attack_ctx; + + instance->mfc_event.type = MfClassicPollerEventTypeRequestKey; + command = instance->callback(instance->general_event, instance->context); + if(instance->mfc_event_data.key_request_data.key_provided) { + dict_attack_ctx->current_key = instance->mfc_event_data.key_request_data.key; + instance->state = MfClassicPollerStateAuthKeyA; + } else { + instance->state = MfClassicPollerStateNextSector; + } + + return command; +} + +NfcCommand mf_classic_poller_handler_auth_a(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerDictAttackContext* dict_attack_ctx = &instance->mode_ctx.dict_attack_ctx; + + if(mf_classic_is_key_found( + instance->data, dict_attack_ctx->current_sector, MfClassicKeyTypeA)) { + instance->state = MfClassicPollerStateAuthKeyB; + } else { + uint8_t block = mf_classic_get_first_block_num_of_sector(dict_attack_ctx->current_sector); + uint64_t key = nfc_util_bytes2num(dict_attack_ctx->current_key.data, sizeof(MfClassicKey)); + FURI_LOG_D(TAG, "Auth to block %d with key A: %06llx", block, key); + + MfClassicError error = mf_classic_async_auth( + instance, block, &dict_attack_ctx->current_key, MfClassicKeyTypeA, NULL); + if(error == MfClassicErrorNone) { + FURI_LOG_I(TAG, "Key A found"); + mf_classic_set_key_found( + instance->data, dict_attack_ctx->current_sector, MfClassicKeyTypeA, key); + + command = mf_classic_poller_handle_data_update(instance); + dict_attack_ctx->current_key_type = MfClassicKeyTypeA; + dict_attack_ctx->current_block = block; + dict_attack_ctx->auth_passed = true; + instance->state = MfClassicPollerStateReadSector; + } else { + mf_classic_async_halt(instance); + instance->state = MfClassicPollerStateAuthKeyB; + } + } + + return command; +} + +NfcCommand mf_classic_poller_handler_auth_b(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerDictAttackContext* dict_attack_ctx = &instance->mode_ctx.dict_attack_ctx; + + if(mf_classic_is_key_found( + instance->data, dict_attack_ctx->current_sector, MfClassicKeyTypeB)) { + if(mf_classic_is_key_found( + instance->data, dict_attack_ctx->current_sector, MfClassicKeyTypeA)) { + instance->state = MfClassicPollerStateNextSector; + } else { + instance->state = MfClassicPollerStateRequestKey; + } + } else { + uint8_t block = mf_classic_get_first_block_num_of_sector(dict_attack_ctx->current_sector); + uint64_t key = nfc_util_bytes2num(dict_attack_ctx->current_key.data, sizeof(MfClassicKey)); + FURI_LOG_D(TAG, "Auth to block %d with key B: %06llx", block, key); + + MfClassicError error = mf_classic_async_auth( + instance, block, &dict_attack_ctx->current_key, MfClassicKeyTypeB, NULL); + if(error == MfClassicErrorNone) { + FURI_LOG_I(TAG, "Key B found"); + mf_classic_set_key_found( + instance->data, dict_attack_ctx->current_sector, MfClassicKeyTypeB, key); + + command = mf_classic_poller_handle_data_update(instance); + dict_attack_ctx->current_key_type = MfClassicKeyTypeB; + dict_attack_ctx->current_block = block; + + dict_attack_ctx->auth_passed = true; + instance->state = MfClassicPollerStateReadSector; + } else { + mf_classic_async_halt(instance); + instance->state = MfClassicPollerStateRequestKey; + } + } + + return command; +} + +NfcCommand mf_classic_poller_handler_next_sector(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerDictAttackContext* dict_attack_ctx = &instance->mode_ctx.dict_attack_ctx; + + dict_attack_ctx->current_sector++; + if(dict_attack_ctx->current_sector == instance->sectors_total) { + instance->state = MfClassicPollerStateSuccess; + } else { + instance->mfc_event.type = MfClassicPollerEventTypeNextSector; + instance->mfc_event_data.next_sector_data.current_sector = dict_attack_ctx->current_sector; + command = instance->callback(instance->general_event, instance->context); + instance->state = MfClassicPollerStateRequestKey; + } + + return command; +} + +NfcCommand mf_classic_poller_handler_read_sector(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerDictAttackContext* dict_attack_ctx = &instance->mode_ctx.dict_attack_ctx; + + MfClassicError error = MfClassicErrorNone; + uint8_t block_num = dict_attack_ctx->current_block; + MfClassicBlock block = {}; + + do { + if(mf_classic_is_block_read(instance->data, block_num)) break; + + if(!dict_attack_ctx->auth_passed) { + error = mf_classic_async_auth( + instance, + block_num, + &dict_attack_ctx->current_key, + dict_attack_ctx->current_key_type, + NULL); + if(error != MfClassicErrorNone) { + instance->state = MfClassicPollerStateNextSector; + FURI_LOG_W(TAG, "Failed to re-auth. Go to next sector"); + break; + } + } + + FURI_LOG_D(TAG, "Reading block %d", block_num); + error = mf_classic_async_read_block(instance, block_num, &block); + + if(error != MfClassicErrorNone) { + mf_classic_async_halt(instance); + dict_attack_ctx->auth_passed = false; + FURI_LOG_D(TAG, "Failed to read block %d", block_num); + } else { + mf_classic_set_block_read(instance->data, block_num, &block); + if(dict_attack_ctx->current_key_type == MfClassicKeyTypeA) { + mf_classic_poller_check_key_b_is_readable(instance, block_num, &block); + } + } + } while(false); + + uint8_t sec_tr_block_num = + mf_classic_get_sector_trailer_num_by_sector(dict_attack_ctx->current_sector); + dict_attack_ctx->current_block++; + if(dict_attack_ctx->current_block > sec_tr_block_num) { + mf_classic_poller_handle_data_update(instance); + + mf_classic_async_halt(instance); + dict_attack_ctx->auth_passed = false; + + if(dict_attack_ctx->current_sector == instance->sectors_total) { + instance->state = MfClassicPollerStateNextSector; + } else { + dict_attack_ctx->reuse_key_sector = dict_attack_ctx->current_sector; + instance->mfc_event.type = MfClassicPollerEventTypeKeyAttackStart; + instance->mfc_event_data.key_attack_data.current_sector = + dict_attack_ctx->reuse_key_sector; + command = instance->callback(instance->general_event, instance->context); + instance->state = MfClassicPollerStateKeyReuseStart; + } + } + + return command; +} + +NfcCommand mf_classic_poller_handler_key_reuse_start(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerDictAttackContext* dict_attack_ctx = &instance->mode_ctx.dict_attack_ctx; + + if(dict_attack_ctx->current_key_type == MfClassicKeyTypeA) { + dict_attack_ctx->current_key_type = MfClassicKeyTypeB; + instance->state = MfClassicPollerStateKeyReuseAuthKeyB; + } else { + dict_attack_ctx->reuse_key_sector++; + if(dict_attack_ctx->reuse_key_sector == instance->sectors_total) { + instance->mfc_event.type = MfClassicPollerEventTypeKeyAttackStop; + command = instance->callback(instance->general_event, instance->context); + instance->state = MfClassicPollerStateRequestKey; + } else { + instance->mfc_event.type = MfClassicPollerEventTypeKeyAttackStart; + instance->mfc_event_data.key_attack_data.current_sector = + dict_attack_ctx->reuse_key_sector; + command = instance->callback(instance->general_event, instance->context); + + dict_attack_ctx->current_key_type = MfClassicKeyTypeA; + instance->state = MfClassicPollerStateKeyReuseAuthKeyA; + } + } + + return command; +} + +NfcCommand mf_classic_poller_handler_key_reuse_auth_key_a(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerDictAttackContext* dict_attack_ctx = &instance->mode_ctx.dict_attack_ctx; + + if(mf_classic_is_key_found( + instance->data, dict_attack_ctx->reuse_key_sector, MfClassicKeyTypeA)) { + instance->state = MfClassicPollerStateKeyReuseStart; + } else { + uint8_t block = + mf_classic_get_first_block_num_of_sector(dict_attack_ctx->reuse_key_sector); + uint64_t key = nfc_util_bytes2num(dict_attack_ctx->current_key.data, sizeof(MfClassicKey)); + FURI_LOG_D(TAG, "Key attack auth to block %d with key A: %06llx", block, key); + + MfClassicError error = mf_classic_async_auth( + instance, block, &dict_attack_ctx->current_key, MfClassicKeyTypeA, NULL); + if(error == MfClassicErrorNone) { + FURI_LOG_I(TAG, "Key A found"); + mf_classic_set_key_found( + instance->data, dict_attack_ctx->reuse_key_sector, MfClassicKeyTypeA, key); + + command = mf_classic_poller_handle_data_update(instance); + dict_attack_ctx->current_key_type = MfClassicKeyTypeA; + dict_attack_ctx->current_block = block; + dict_attack_ctx->auth_passed = true; + instance->state = MfClassicPollerStateKeyReuseReadSector; + } else { + mf_classic_async_halt(instance); + dict_attack_ctx->auth_passed = false; + instance->state = MfClassicPollerStateKeyReuseStart; + } + } + + return command; +} + +NfcCommand mf_classic_poller_handler_key_reuse_auth_key_b(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerDictAttackContext* dict_attack_ctx = &instance->mode_ctx.dict_attack_ctx; + + if(mf_classic_is_key_found( + instance->data, dict_attack_ctx->reuse_key_sector, MfClassicKeyTypeB)) { + instance->state = MfClassicPollerStateKeyReuseStart; + } else { + uint8_t block = + mf_classic_get_first_block_num_of_sector(dict_attack_ctx->reuse_key_sector); + uint64_t key = nfc_util_bytes2num(dict_attack_ctx->current_key.data, sizeof(MfClassicKey)); + FURI_LOG_D(TAG, "Key attack auth to block %d with key B: %06llx", block, key); + + MfClassicError error = mf_classic_async_auth( + instance, block, &dict_attack_ctx->current_key, MfClassicKeyTypeB, NULL); + if(error == MfClassicErrorNone) { + FURI_LOG_I(TAG, "Key B found"); + mf_classic_set_key_found( + instance->data, dict_attack_ctx->reuse_key_sector, MfClassicKeyTypeB, key); + + command = mf_classic_poller_handle_data_update(instance); + dict_attack_ctx->current_key_type = MfClassicKeyTypeB; + dict_attack_ctx->current_block = block; + + dict_attack_ctx->auth_passed = true; + instance->state = MfClassicPollerStateKeyReuseReadSector; + } else { + mf_classic_async_halt(instance); + dict_attack_ctx->auth_passed = false; + instance->state = MfClassicPollerStateKeyReuseStart; + } + } + + return command; +} + +NfcCommand mf_classic_poller_handler_key_reuse_read_sector(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + MfClassicPollerDictAttackContext* dict_attack_ctx = &instance->mode_ctx.dict_attack_ctx; + + MfClassicError error = MfClassicErrorNone; + uint8_t block_num = dict_attack_ctx->current_block; + MfClassicBlock block = {}; + + do { + if(mf_classic_is_block_read(instance->data, block_num)) break; + + if(!dict_attack_ctx->auth_passed) { + error = mf_classic_async_auth( + instance, + block_num, + &dict_attack_ctx->current_key, + dict_attack_ctx->current_key_type, + NULL); + if(error != MfClassicErrorNone) { + instance->state = MfClassicPollerStateKeyReuseStart; + break; + } + } + + FURI_LOG_D(TAG, "Reading block %d", block_num); + error = mf_classic_async_read_block(instance, block_num, &block); + + if(error != MfClassicErrorNone) { + mf_classic_async_halt(instance); + dict_attack_ctx->auth_passed = false; + FURI_LOG_D(TAG, "Failed to read block %d", block_num); + } else { + mf_classic_set_block_read(instance->data, block_num, &block); + if(dict_attack_ctx->current_key_type == MfClassicKeyTypeA) { + mf_classic_poller_check_key_b_is_readable(instance, block_num, &block); + } + } + } while(false); + + uint16_t sec_tr_block_num = + mf_classic_get_sector_trailer_num_by_sector(dict_attack_ctx->reuse_key_sector); + dict_attack_ctx->current_block++; + if(dict_attack_ctx->current_block > sec_tr_block_num) { + mf_classic_async_halt(instance); + dict_attack_ctx->auth_passed = false; + + mf_classic_poller_handle_data_update(instance); + instance->state = MfClassicPollerStateKeyReuseStart; + } + + return command; +} + +NfcCommand mf_classic_poller_handler_success(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + instance->mfc_event.type = MfClassicPollerEventTypeSuccess; + command = instance->callback(instance->general_event, instance->context); + + return command; +} + +NfcCommand mf_classic_poller_handler_fail(MfClassicPoller* instance) { + NfcCommand command = NfcCommandContinue; + instance->mfc_event.type = MfClassicPollerEventTypeFail; + command = instance->callback(instance->general_event, instance->context); + instance->state = MfClassicPollerStateDetectType; + + return command; +} + +static const MfClassicPollerReadHandler + mf_classic_poller_dict_attack_handler[MfClassicPollerStateNum] = { + [MfClassicPollerStateDetectType] = mf_classic_poller_handler_detect_type, + [MfClassicPollerStateStart] = mf_classic_poller_handler_start, + [MfClassicPollerStateRequestSectorTrailer] = + mf_classic_poller_handler_request_sector_trailer, + [MfClassicPollerStateCheckWriteConditions] = mf_classic_handler_check_write_conditions, + [MfClassicPollerStateReadBlock] = mf_classic_poller_handler_read_block, + [MfClassicPollerStateWriteBlock] = mf_classic_poller_handler_write_block, + [MfClassicPollerStateWriteValueBlock] = mf_classic_poller_handler_write_value_block, + [MfClassicPollerStateNextSector] = mf_classic_poller_handler_next_sector, + [MfClassicPollerStateRequestKey] = mf_classic_poller_handler_request_key, + [MfClassicPollerStateRequestReadSector] = mf_classic_poller_handler_request_read_sector, + [MfClassicPollerStateReadSectorBlocks] = + mf_classic_poller_handler_request_read_sector_blocks, + [MfClassicPollerStateAuthKeyA] = mf_classic_poller_handler_auth_a, + [MfClassicPollerStateAuthKeyB] = mf_classic_poller_handler_auth_b, + [MfClassicPollerStateReadSector] = mf_classic_poller_handler_read_sector, + [MfClassicPollerStateKeyReuseStart] = mf_classic_poller_handler_key_reuse_start, + [MfClassicPollerStateKeyReuseAuthKeyA] = mf_classic_poller_handler_key_reuse_auth_key_a, + [MfClassicPollerStateKeyReuseAuthKeyB] = mf_classic_poller_handler_key_reuse_auth_key_b, + [MfClassicPollerStateKeyReuseReadSector] = mf_classic_poller_handler_key_reuse_read_sector, + [MfClassicPollerStateSuccess] = mf_classic_poller_handler_success, + [MfClassicPollerStateFail] = mf_classic_poller_handler_fail, +}; + +NfcCommand mf_classic_poller_run(NfcGenericEvent event, void* context) { + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + furi_assert(context); + + MfClassicPoller* instance = context; + Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + NfcCommand command = NfcCommandContinue; + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + if(instance->card_state == MfClassicCardStateLost) { + instance->card_state = MfClassicCardStateDetected; + instance->mfc_event.type = MfClassicPollerEventTypeCardDetected; + instance->callback(instance->general_event, instance->context); + } + command = mf_classic_poller_dict_attack_handler[instance->state](instance); + } else if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeError) { + if(instance->card_state == MfClassicCardStateDetected) { + instance->card_state = MfClassicCardStateLost; + instance->mfc_event.type = MfClassicPollerEventTypeCardLost; + command = instance->callback(instance->general_event, instance->context); + } + } + + return command; +} + +bool mf_classic_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + furi_assert(context); + + Iso14443_3aPoller* iso3_poller = event.instance; + Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + bool detected = false; + const uint8_t auth_cmd[] = {MF_CLASSIC_CMD_AUTH_KEY_A, 0}; + BitBuffer* tx_buffer = bit_buffer_alloc(COUNT_OF(auth_cmd)); + bit_buffer_copy_bytes(tx_buffer, auth_cmd, COUNT_OF(auth_cmd)); + BitBuffer* rx_buffer = bit_buffer_alloc(sizeof(MfClassicNt)); + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + Iso14443_3aError error = iso14443_3a_poller_send_standard_frame( + iso3_poller, tx_buffer, rx_buffer, MF_CLASSIC_FWT_FC); + if(error == Iso14443_3aErrorWrongCrc) { + if(bit_buffer_get_size_bytes(rx_buffer) == sizeof(MfClassicNt)) { + detected = true; + } + } + } + + bit_buffer_free(tx_buffer); + bit_buffer_free(rx_buffer); + + return detected; +} + +void mf_classic_poller_set_callback( + MfClassicPoller* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +const MfClassicData* mf_classic_poller_get_data(const MfClassicPoller* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +const NfcPollerBase mf_classic_poller = { + .alloc = (NfcPollerAlloc)mf_classic_poller_alloc, + .free = (NfcPollerFree)mf_classic_poller_free, + .set_callback = (NfcPollerSetCallback)mf_classic_poller_set_callback, + .run = (NfcPollerRun)mf_classic_poller_run, + .detect = (NfcPollerDetect)mf_classic_poller_detect, + .get_data = (NfcPollerGetData)mf_classic_poller_get_data, +}; diff --git a/lib/nfc/protocols/mf_classic/mf_classic_poller.h b/lib/nfc/protocols/mf_classic/mf_classic_poller.h new file mode 100644 index 000000000..da1f3c3dc --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_poller.h @@ -0,0 +1,109 @@ +#pragma once + +#include "mf_classic.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct MfClassicPoller MfClassicPoller; + +typedef enum { + // Start event + MfClassicPollerEventTypeRequestMode, + + // Read with key cache events + MfClassicPollerEventTypeRequestReadSector, + + // Write events + MfClassicPollerEventTypeRequestSectorTrailer, + MfClassicPollerEventTypeRequestWriteBlock, + + // Dictionary attack events + MfClassicPollerEventTypeRequestKey, + MfClassicPollerEventTypeNextSector, + MfClassicPollerEventTypeDataUpdate, + MfClassicPollerEventTypeFoundKeyA, + MfClassicPollerEventTypeFoundKeyB, + MfClassicPollerEventTypeCardNotDetected, + MfClassicPollerEventTypeKeyAttackStart, + MfClassicPollerEventTypeKeyAttackStop, + MfClassicPollerEventTypeKeyAttackNextSector, + + // Common events + MfClassicPollerEventTypeCardDetected, + MfClassicPollerEventTypeCardLost, + MfClassicPollerEventTypeSuccess, + MfClassicPollerEventTypeFail, +} MfClassicPollerEventType; + +typedef enum { + MfClassicPollerModeRead, + MfClassicPollerModeWrite, + MfClassicPollerModeDictAttack, +} MfClassicPollerMode; + +typedef struct { + MfClassicPollerMode mode; + const MfClassicData* data; +} MfClassicPollerEventDataRequestMode; + +typedef struct { + uint8_t current_sector; +} MfClassicPollerEventDataDictAttackNextSector; + +typedef struct { + uint8_t sectors_read; + uint8_t keys_found; + uint8_t current_sector; +} MfClassicPollerEventDataUpdate; + +typedef struct { + MfClassicKey key; + bool key_provided; +} MfClassicPollerEventDataKeyRequest; + +typedef struct { + uint8_t sector_num; + MfClassicKey key; + MfClassicKeyType key_type; + bool key_provided; +} MfClassicPollerEventDataReadSectorRequest; + +typedef struct { + uint8_t sector_num; + MfClassicBlock sector_trailer; + bool sector_trailer_provided; +} MfClassicPollerEventDataSectorTrailerRequest; + +typedef struct { + uint8_t block_num; + MfClassicBlock write_block; + bool write_block_provided; +} MfClassicPollerEventDataWriteBlockRequest; + +typedef struct { + uint8_t current_sector; +} MfClassicPollerEventKeyAttackData; + +typedef union { + MfClassicError error; + MfClassicPollerEventDataRequestMode poller_mode; + MfClassicPollerEventDataDictAttackNextSector next_sector_data; + MfClassicPollerEventDataKeyRequest key_request_data; + MfClassicPollerEventDataUpdate data_update; + MfClassicPollerEventDataReadSectorRequest read_sector_request_data; + MfClassicPollerEventKeyAttackData key_attack_data; + MfClassicPollerEventDataSectorTrailerRequest sec_tr_data; + MfClassicPollerEventDataWriteBlockRequest write_block_data; +} MfClassicPollerEventData; + +typedef struct { + MfClassicPollerEventType type; + MfClassicPollerEventData* data; +} MfClassicPollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_classic/mf_classic_poller_defs.h b/lib/nfc/protocols/mf_classic/mf_classic_poller_defs.h new file mode 100644 index 000000000..d0c0b18fc --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_poller_defs.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NfcPollerBase mf_classic_poller; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_classic/mf_classic_poller_i.c b/lib/nfc/protocols/mf_classic/mf_classic_poller_i.c new file mode 100644 index 000000000..7eab4fe3b --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_poller_i.c @@ -0,0 +1,386 @@ +#include "mf_classic_poller_i.h" + +#include +#include + +#include + +#define TAG "MfCLassicPoller" + +MfClassicError mf_classic_process_error(Iso14443_3aError error) { + MfClassicError ret = MfClassicErrorNone; + + switch(error) { + case Iso14443_3aErrorNone: + ret = MfClassicErrorNone; + break; + case Iso14443_3aErrorNotPresent: + ret = MfClassicErrorNotPresent; + break; + case Iso14443_3aErrorColResFailed: + case Iso14443_3aErrorCommunication: + case Iso14443_3aErrorWrongCrc: + ret = MfClassicErrorProtocol; + break; + case Iso14443_3aErrorTimeout: + ret = MfClassicErrorTimeout; + break; + default: + ret = MfClassicErrorProtocol; + break; + } + + return ret; +} + +MfClassicError mf_classic_async_get_nt( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicKeyType key_type, + MfClassicNt* nt) { + MfClassicError ret = MfClassicErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t auth_type = (key_type == MfClassicKeyTypeB) ? MF_CLASSIC_CMD_AUTH_KEY_B : + MF_CLASSIC_CMD_AUTH_KEY_A; + uint8_t auth_cmd[2] = {auth_type, block_num}; + bit_buffer_copy_bytes(instance->tx_plain_buffer, auth_cmd, sizeof(auth_cmd)); + + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_plain_buffer, + instance->rx_plain_buffer, + MF_CLASSIC_FWT_FC); + if(error != Iso14443_3aErrorWrongCrc) { + ret = mf_classic_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_plain_buffer) != sizeof(MfClassicNt)) { + ret = MfClassicErrorProtocol; + break; + } + + if(nt) { + bit_buffer_write_bytes(instance->rx_plain_buffer, nt->data, sizeof(MfClassicNt)); + } + } while(false); + + return ret; +} + +MfClassicError mf_classic_async_auth( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + MfClassicAuthContext* data) { + MfClassicError ret = MfClassicErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + iso14443_3a_copy( + instance->data->iso14443_3a_data, + iso14443_3a_poller_get_data(instance->iso14443_3a_poller)); + + MfClassicNt nt = {}; + ret = mf_classic_async_get_nt(instance, block_num, key_type, &nt); + if(ret != MfClassicErrorNone) break; + if(data) { + data->nt = nt; + } + + uint32_t cuid = iso14443_3a_get_cuid(instance->data->iso14443_3a_data); + uint64_t key_num = nfc_util_bytes2num(key->data, sizeof(MfClassicKey)); + MfClassicNr nr = {}; + furi_hal_random_fill_buf(nr.data, sizeof(MfClassicNr)); + + crypto1_encrypt_reader_nonce( + instance->crypto, key_num, cuid, nt.data, nr.data, instance->tx_encrypted_buffer); + error = iso14443_3a_poller_txrx_custom_parity( + instance->iso14443_3a_poller, + instance->tx_encrypted_buffer, + instance->rx_encrypted_buffer, + MF_CLASSIC_FWT_FC); + + if(error != Iso14443_3aErrorNone) { + ret = mf_classic_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_encrypted_buffer) != 4) { + ret = MfClassicErrorAuth; + } + + crypto1_word(instance->crypto, 0, 0); + instance->auth_state = MfClassicAuthStatePassed; + + if(data) { + data->nr = nr; + const uint8_t* nr_ar = bit_buffer_get_data(instance->tx_encrypted_buffer); + memcpy(data->ar.data, &nr_ar[4], sizeof(MfClassicAr)); + bit_buffer_write_bytes( + instance->rx_encrypted_buffer, data->at.data, sizeof(MfClassicAt)); + } + } while(false); + + if(ret != MfClassicErrorNone) { + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + } + + return ret; +} + +MfClassicError mf_classic_async_halt(MfClassicPoller* instance) { + MfClassicError ret = MfClassicErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t halt_cmd[2] = {MF_CLASSIC_CMD_HALT_MSB, MF_CLASSIC_CMD_HALT_LSB}; + bit_buffer_copy_bytes(instance->tx_plain_buffer, halt_cmd, sizeof(halt_cmd)); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_plain_buffer); + + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + + error = iso14443_3a_poller_txrx_custom_parity( + instance->iso14443_3a_poller, + instance->tx_encrypted_buffer, + instance->rx_encrypted_buffer, + MF_CLASSIC_FWT_FC); + if(error != Iso14443_3aErrorTimeout) { + ret = mf_classic_process_error(error); + break; + } + instance->auth_state = MfClassicAuthStateIdle; + instance->iso14443_3a_poller->state = Iso14443_3aPollerStateIdle; + } while(false); + + return ret; +} + +MfClassicError mf_classic_async_read_block( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicBlock* data) { + MfClassicError ret = MfClassicErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t read_block_cmd[2] = {MF_CLASSIC_CMD_READ_BLOCK, block_num}; + bit_buffer_copy_bytes(instance->tx_plain_buffer, read_block_cmd, sizeof(read_block_cmd)); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_plain_buffer); + + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + + error = iso14443_3a_poller_txrx_custom_parity( + instance->iso14443_3a_poller, + instance->tx_encrypted_buffer, + instance->rx_encrypted_buffer, + MF_CLASSIC_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_classic_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_encrypted_buffer) != + (sizeof(MfClassicBlock) + 2)) { + ret = MfClassicErrorProtocol; + break; + } + + crypto1_decrypt( + instance->crypto, instance->rx_encrypted_buffer, instance->rx_plain_buffer); + + if(!iso14443_crc_check(Iso14443CrcTypeA, instance->rx_plain_buffer)) { + FURI_LOG_D(TAG, "CRC error"); + ret = MfClassicErrorProtocol; + break; + } + + iso14443_crc_trim(instance->rx_plain_buffer); + bit_buffer_write_bytes(instance->rx_plain_buffer, data->data, sizeof(MfClassicBlock)); + } while(false); + + return ret; +} + +MfClassicError mf_classic_async_write_block( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicBlock* data) { + MfClassicError ret = MfClassicErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t write_block_cmd[2] = {MF_CLASSIC_CMD_WRITE_BLOCK, block_num}; + bit_buffer_copy_bytes(instance->tx_plain_buffer, write_block_cmd, sizeof(write_block_cmd)); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_plain_buffer); + + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + + error = iso14443_3a_poller_txrx_custom_parity( + instance->iso14443_3a_poller, + instance->tx_encrypted_buffer, + instance->rx_encrypted_buffer, + MF_CLASSIC_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_classic_process_error(error); + break; + } + if(bit_buffer_get_size(instance->rx_encrypted_buffer) != 4) { + ret = MfClassicErrorProtocol; + break; + } + + crypto1_decrypt( + instance->crypto, instance->rx_encrypted_buffer, instance->rx_plain_buffer); + + if(bit_buffer_get_byte(instance->rx_plain_buffer, 0) != MF_CLASSIC_CMD_ACK) { + FURI_LOG_D(TAG, "Not ACK received"); + ret = MfClassicErrorProtocol; + break; + } + + bit_buffer_copy_bytes(instance->tx_plain_buffer, data->data, sizeof(MfClassicBlock)); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_plain_buffer); + + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + + error = iso14443_3a_poller_txrx_custom_parity( + instance->iso14443_3a_poller, + instance->tx_encrypted_buffer, + instance->rx_encrypted_buffer, + MF_CLASSIC_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_classic_process_error(error); + break; + } + if(bit_buffer_get_size(instance->rx_encrypted_buffer) != 4) { + ret = MfClassicErrorProtocol; + break; + } + + crypto1_decrypt( + instance->crypto, instance->rx_encrypted_buffer, instance->rx_plain_buffer); + + if(bit_buffer_get_byte(instance->rx_plain_buffer, 0) != MF_CLASSIC_CMD_ACK) { + FURI_LOG_D(TAG, "Not ACK received"); + ret = MfClassicErrorProtocol; + break; + } + } while(false); + + return ret; +} + +MfClassicError mf_classic_async_value_cmd( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicValueCommand cmd, + int32_t data) { + MfClassicError ret = MfClassicErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t cmd_value = 0; + if(cmd == MfClassicValueCommandDecrement) { + cmd_value = MF_CLASSIC_CMD_VALUE_DEC; + } else if(cmd == MfClassicValueCommandIncrement) { + cmd_value = MF_CLASSIC_CMD_VALUE_INC; + } else { + cmd_value = MF_CLASSIC_CMD_VALUE_RESTORE; + } + uint8_t value_cmd[2] = {cmd_value, block_num}; + bit_buffer_copy_bytes(instance->tx_plain_buffer, value_cmd, sizeof(value_cmd)); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_plain_buffer); + + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + + error = iso14443_3a_poller_txrx_custom_parity( + instance->iso14443_3a_poller, + instance->tx_encrypted_buffer, + instance->rx_encrypted_buffer, + MF_CLASSIC_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_classic_process_error(error); + break; + } + if(bit_buffer_get_size(instance->rx_encrypted_buffer) != 4) { + ret = MfClassicErrorProtocol; + break; + } + + crypto1_decrypt( + instance->crypto, instance->rx_encrypted_buffer, instance->rx_plain_buffer); + + if(bit_buffer_get_byte(instance->rx_plain_buffer, 0) != MF_CLASSIC_CMD_ACK) { + FURI_LOG_D(TAG, "Not ACK received"); + ret = MfClassicErrorProtocol; + break; + } + + bit_buffer_copy_bytes(instance->tx_plain_buffer, (uint8_t*)&data, sizeof(data)); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_plain_buffer); + + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + + error = iso14443_3a_poller_txrx_custom_parity( + instance->iso14443_3a_poller, + instance->tx_encrypted_buffer, + instance->rx_encrypted_buffer, + MF_CLASSIC_FWT_FC); + + // Command processed if tag doesn't respond + if(error != Iso14443_3aErrorTimeout) { + ret = MfClassicErrorProtocol; + break; + } + ret = MfClassicErrorNone; + } while(false); + + return ret; +} + +MfClassicError mf_classic_async_value_transfer(MfClassicPoller* instance, uint8_t block_num) { + MfClassicError ret = MfClassicErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t transfer_cmd[2] = {MF_CLASSIC_CMD_VALUE_TRANSFER, block_num}; + bit_buffer_copy_bytes(instance->tx_plain_buffer, transfer_cmd, sizeof(transfer_cmd)); + iso14443_crc_append(Iso14443CrcTypeA, instance->tx_plain_buffer); + + crypto1_encrypt( + instance->crypto, NULL, instance->tx_plain_buffer, instance->tx_encrypted_buffer); + + error = iso14443_3a_poller_txrx_custom_parity( + instance->iso14443_3a_poller, + instance->tx_encrypted_buffer, + instance->rx_encrypted_buffer, + MF_CLASSIC_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_classic_process_error(error); + break; + } + if(bit_buffer_get_size(instance->rx_encrypted_buffer) != 4) { + ret = MfClassicErrorProtocol; + break; + } + + crypto1_decrypt( + instance->crypto, instance->rx_encrypted_buffer, instance->rx_plain_buffer); + + if(bit_buffer_get_byte(instance->rx_plain_buffer, 0) != MF_CLASSIC_CMD_ACK) { + FURI_LOG_D(TAG, "Not ACK received"); + ret = MfClassicErrorProtocol; + break; + } + + } while(false); + + return ret; +} diff --git a/lib/nfc/protocols/mf_classic/mf_classic_poller_i.h b/lib/nfc/protocols/mf_classic/mf_classic_poller_i.h new file mode 100644 index 000000000..c6f4ccf7f --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_poller_i.h @@ -0,0 +1,205 @@ +#pragma once + +#include "mf_classic_poller.h" +#include +#include +#include "crypto1.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define MF_CLASSIC_FWT_FC (60000) + +typedef enum { + MfClassicAuthStateIdle, + MfClassicAuthStatePassed, +} MfClassicAuthState; + +typedef enum { + MfClassicCardStateDetected, + MfClassicCardStateLost, +} MfClassicCardState; + +typedef enum { + MfClassicPollerStateDetectType, + MfClassicPollerStateStart, + + // Write states + MfClassicPollerStateRequestSectorTrailer, + MfClassicPollerStateCheckWriteConditions, + MfClassicPollerStateReadBlock, + MfClassicPollerStateWriteBlock, + MfClassicPollerStateWriteValueBlock, + + // Read states + MfClassicPollerStateRequestReadSector, + MfClassicPollerStateReadSectorBlocks, + + // Dict attack states + MfClassicPollerStateNextSector, + MfClassicPollerStateRequestKey, + MfClassicPollerStateReadSector, + MfClassicPollerStateAuthKeyA, + MfClassicPollerStateAuthKeyB, + MfClassicPollerStateKeyReuseStart, + MfClassicPollerStateKeyReuseAuthKeyA, + MfClassicPollerStateKeyReuseAuthKeyB, + MfClassicPollerStateKeyReuseReadSector, + MfClassicPollerStateSuccess, + MfClassicPollerStateFail, + + MfClassicPollerStateNum, +} MfClassicPollerState; + +typedef struct { + uint8_t current_sector; + MfClassicSectorTrailer sec_tr; + uint16_t current_block; + bool is_value_block; + MfClassicKeyType key_type_read; + MfClassicKeyType key_type_write; + bool need_halt_before_write; + MfClassicBlock tag_block; +} MfClassicPollerWriteContext; + +typedef struct { + uint8_t current_sector; + MfClassicKey current_key; + MfClassicKeyType current_key_type; + bool auth_passed; + uint16_t current_block; + uint8_t reuse_key_sector; +} MfClassicPollerDictAttackContext; + +typedef struct { + uint8_t current_sector; + uint16_t current_block; + MfClassicKeyType key_type; + MfClassicKey key; + bool auth_passed; +} MfClassicPollerReadContext; + +typedef union { + MfClassicPollerWriteContext write_ctx; + MfClassicPollerDictAttackContext dict_attack_ctx; + MfClassicPollerReadContext read_ctx; + +} MfClassicPollerModeContext; + +struct MfClassicPoller { + Iso14443_3aPoller* iso14443_3a_poller; + + MfClassicPollerState state; + MfClassicAuthState auth_state; + MfClassicCardState card_state; + + MfClassicType current_type_check; + uint8_t sectors_total; + MfClassicPollerModeContext mode_ctx; + + Crypto1* crypto; + BitBuffer* tx_plain_buffer; + BitBuffer* tx_encrypted_buffer; + BitBuffer* rx_plain_buffer; + BitBuffer* rx_encrypted_buffer; + MfClassicData* data; + + NfcGenericEvent general_event; + MfClassicPollerEvent mfc_event; + MfClassicPollerEventData mfc_event_data; + NfcGenericCallback callback; + void* context; +}; + +typedef struct { + uint8_t block; + MfClassicKeyType key_type; + MfClassicNt nt; +} MfClassicCollectNtContext; + +typedef struct { + uint8_t block_num; + MfClassicKey key; + MfClassicKeyType key_type; + MfClassicBlock block; +} MfClassicReadBlockContext; + +typedef struct { + uint8_t block_num; + MfClassicKey key; + MfClassicKeyType key_type; + MfClassicBlock block; +} MfClassicWriteBlockContext; + +typedef struct { + uint8_t block_num; + MfClassicKey key; + MfClassicKeyType key_type; + int32_t value; +} MfClassicReadValueContext; + +typedef struct { + uint8_t block_num; + MfClassicKey key; + MfClassicKeyType key_type; + MfClassicValueCommand value_cmd; + int32_t data; + int32_t new_value; +} MfClassicChangeValueContext; + +typedef struct { + MfClassicDeviceKeys keys; + uint8_t current_sector; +} MfClassicReadContext; + +typedef union { + MfClassicCollectNtContext collect_nt_context; + MfClassicAuthContext auth_context; + MfClassicReadBlockContext read_block_context; + MfClassicWriteBlockContext write_block_context; + MfClassicReadValueContext read_value_context; + MfClassicChangeValueContext change_value_context; + MfClassicReadContext read_context; +} MfClassicPollerContextData; + +MfClassicError mf_classic_process_error(Iso14443_3aError error); + +MfClassicPoller* mf_classic_poller_alloc(Iso14443_3aPoller* iso14443_3a_poller); + +void mf_classic_poller_free(MfClassicPoller* instance); + +MfClassicError mf_classic_async_get_nt( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicKeyType key_type, + MfClassicNt* nt); + +MfClassicError mf_classic_async_auth( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + MfClassicAuthContext* data); + +MfClassicError mf_classic_async_halt(MfClassicPoller* instance); + +MfClassicError + mf_classic_async_read_block(MfClassicPoller* instance, uint8_t block_num, MfClassicBlock* data); + +MfClassicError mf_classic_async_write_block( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicBlock* data); + +MfClassicError mf_classic_async_value_cmd( + MfClassicPoller* instance, + uint8_t block_num, + MfClassicValueCommand cmd, + int32_t data); + +MfClassicError mf_classic_async_value_transfer(MfClassicPoller* instance, uint8_t block_num); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_classic/mf_classic_poller_sync_api.c b/lib/nfc/protocols/mf_classic/mf_classic_poller_sync_api.c new file mode 100644 index 000000000..8b9fb69f1 --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_poller_sync_api.c @@ -0,0 +1,524 @@ +#include "mf_classic_poller_i.h" + +#include + +#include + +#define TAG "MfClassicPoller" + +#define MF_CLASSIC_POLLER_COMPLETE_EVENT (1UL << 0) + +typedef enum { + MfClassicPollerCmdTypeCollectNt, + MfClassicPollerCmdTypeAuth, + MfClassicPollerCmdTypeReadBlock, + MfClassicPollerCmdTypeWriteBlock, + MfClassicPollerCmdTypeReadValue, + MfClassicPollerCmdTypeChangeValue, + + MfClassicPollerCmdTypeNum, +} MfClassicPollerCmdType; + +typedef struct { + MfClassicPollerCmdType cmd_type; + FuriThreadId thread_id; + MfClassicError error; + MfClassicPollerContextData data; +} MfClassicPollerContext; + +typedef MfClassicError ( + *MfClassicPollerCmdHandler)(MfClassicPoller* poller, MfClassicPollerContextData* data); + +static MfClassicError mf_classic_poller_collect_nt_handler( + MfClassicPoller* poller, + MfClassicPollerContextData* data) { + return mf_classic_async_get_nt( + poller, + data->collect_nt_context.block, + data->collect_nt_context.key_type, + &data->collect_nt_context.nt); +} + +static MfClassicError + mf_classic_poller_auth_handler(MfClassicPoller* poller, MfClassicPollerContextData* data) { + return mf_classic_async_auth( + poller, + data->auth_context.block_num, + &data->auth_context.key, + data->auth_context.key_type, + &data->auth_context); +} + +static MfClassicError mf_classic_poller_read_block_handler( + MfClassicPoller* poller, + MfClassicPollerContextData* data) { + MfClassicError error = MfClassicErrorNone; + + do { + error = mf_classic_async_auth( + poller, + data->read_block_context.block_num, + &data->read_block_context.key, + data->read_block_context.key_type, + NULL); + if(error != MfClassicErrorNone) break; + + error = mf_classic_async_read_block( + poller, data->read_block_context.block_num, &data->read_block_context.block); + if(error != MfClassicErrorNone) break; + + error = mf_classic_async_halt(poller); + if(error != MfClassicErrorNone) break; + + } while(false); + + return error; +} + +static MfClassicError mf_classic_poller_write_block_handler( + MfClassicPoller* poller, + MfClassicPollerContextData* data) { + MfClassicError error = MfClassicErrorNone; + + do { + error = mf_classic_async_auth( + poller, + data->read_block_context.block_num, + &data->read_block_context.key, + data->read_block_context.key_type, + NULL); + if(error != MfClassicErrorNone) break; + + error = mf_classic_async_write_block( + poller, data->write_block_context.block_num, &data->write_block_context.block); + if(error != MfClassicErrorNone) break; + + error = mf_classic_async_halt(poller); + if(error != MfClassicErrorNone) break; + + } while(false); + + return error; +} + +static MfClassicError mf_classic_poller_read_value_handler( + MfClassicPoller* poller, + MfClassicPollerContextData* data) { + MfClassicError error = MfClassicErrorNone; + + do { + error = mf_classic_async_auth( + poller, + data->read_value_context.block_num, + &data->read_value_context.key, + data->read_value_context.key_type, + NULL); + if(error != MfClassicErrorNone) break; + + MfClassicBlock block = {}; + error = mf_classic_async_read_block(poller, data->read_value_context.block_num, &block); + if(error != MfClassicErrorNone) break; + + if(!mf_classic_block_to_value(&block, &data->read_value_context.value, NULL)) { + error = MfClassicErrorProtocol; + break; + } + + error = mf_classic_async_halt(poller); + if(error != MfClassicErrorNone) break; + + } while(false); + + return error; +} + +static MfClassicError mf_classic_poller_change_value_handler( + MfClassicPoller* poller, + MfClassicPollerContextData* data) { + MfClassicError error = MfClassicErrorNone; + + do { + error = mf_classic_async_auth( + poller, + data->change_value_context.block_num, + &data->change_value_context.key, + data->change_value_context.key_type, + NULL); + if(error != MfClassicErrorNone) break; + + error = mf_classic_async_value_cmd( + poller, + data->change_value_context.block_num, + data->change_value_context.value_cmd, + data->change_value_context.data); + if(error != MfClassicErrorNone) break; + + error = mf_classic_async_value_transfer(poller, data->change_value_context.block_num); + if(error != MfClassicErrorNone) break; + + MfClassicBlock block = {}; + error = mf_classic_async_read_block(poller, data->change_value_context.block_num, &block); + if(error != MfClassicErrorNone) break; + + error = mf_classic_async_halt(poller); + if(error != MfClassicErrorNone) break; + + if(!mf_classic_block_to_value(&block, &data->change_value_context.new_value, NULL)) { + error = MfClassicErrorProtocol; + break; + } + + } while(false); + + return error; +} + +static const MfClassicPollerCmdHandler mf_classic_poller_cmd_handlers[MfClassicPollerCmdTypeNum] = { + [MfClassicPollerCmdTypeCollectNt] = mf_classic_poller_collect_nt_handler, + [MfClassicPollerCmdTypeAuth] = mf_classic_poller_auth_handler, + [MfClassicPollerCmdTypeReadBlock] = mf_classic_poller_read_block_handler, + [MfClassicPollerCmdTypeWriteBlock] = mf_classic_poller_write_block_handler, + [MfClassicPollerCmdTypeReadValue] = mf_classic_poller_read_value_handler, + [MfClassicPollerCmdTypeChangeValue] = mf_classic_poller_change_value_handler, +}; + +static NfcCommand mf_classic_poller_cmd_callback(NfcGenericEvent event, void* context) { + furi_assert(event.instance); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + furi_assert(event.event_data); + furi_assert(context); + + MfClassicPollerContext* poller_context = context; + Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + Iso14443_3aPoller* iso14443_3a_poller = event.instance; + MfClassicPoller* mfc_poller = mf_classic_poller_alloc(iso14443_3a_poller); + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + poller_context->error = mf_classic_poller_cmd_handlers[poller_context->cmd_type]( + mfc_poller, &poller_context->data); + } else if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeError) { + poller_context->error = mf_classic_process_error(iso14443_3a_event->data->error); + } + + furi_thread_flags_set(poller_context->thread_id, MF_CLASSIC_POLLER_COMPLETE_EVENT); + + mf_classic_poller_free(mfc_poller); + + return NfcCommandStop; +} + +static MfClassicError mf_classic_poller_cmd_execute(Nfc* nfc, MfClassicPollerContext* poller_ctx) { + furi_assert(poller_ctx->cmd_type < MfClassicPollerCmdTypeNum); + + poller_ctx->thread_id = furi_thread_get_current_id(); + + NfcPoller* poller = nfc_poller_alloc(nfc, NfcProtocolIso14443_3a); + nfc_poller_start(poller, mf_classic_poller_cmd_callback, poller_ctx); + furi_thread_flags_wait(MF_CLASSIC_POLLER_COMPLETE_EVENT, FuriFlagWaitAny, FuriWaitForever); + furi_thread_flags_clear(MF_CLASSIC_POLLER_COMPLETE_EVENT); + + nfc_poller_stop(poller); + nfc_poller_free(poller); + + return poller_ctx->error; +} + +MfClassicError mf_classic_poller_collect_nt( + Nfc* nfc, + uint8_t block_num, + MfClassicKeyType key_type, + MfClassicNt* nt) { + furi_assert(nfc); + + MfClassicPollerContext poller_context = { + .cmd_type = MfClassicPollerCmdTypeCollectNt, + .data.collect_nt_context.block = block_num, + .data.collect_nt_context.key_type = key_type, + }; + + MfClassicError error = mf_classic_poller_cmd_execute(nfc, &poller_context); + + if(error == MfClassicErrorNone) { + if(nt) { + *nt = poller_context.data.collect_nt_context.nt; + } + } + + return error; +} + +MfClassicError mf_classic_poller_auth( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + MfClassicAuthContext* data) { + furi_assert(nfc); + furi_assert(key); + + MfClassicPollerContext poller_context = { + .cmd_type = MfClassicPollerCmdTypeAuth, + .data.auth_context.block_num = block_num, + .data.auth_context.key = *key, + .data.auth_context.key_type = key_type, + }; + + MfClassicError error = mf_classic_poller_cmd_execute(nfc, &poller_context); + + if(error == MfClassicErrorNone) { + if(data) { + *data = poller_context.data.auth_context; + } + } + + return error; +} + +MfClassicError mf_classic_poller_read_block( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + MfClassicBlock* data) { + furi_assert(nfc); + furi_assert(key); + furi_assert(data); + + MfClassicPollerContext poller_context = { + .cmd_type = MfClassicPollerCmdTypeReadBlock, + .data.read_block_context.block_num = block_num, + .data.read_block_context.key = *key, + .data.read_block_context.key_type = key_type, + }; + + MfClassicError error = mf_classic_poller_cmd_execute(nfc, &poller_context); + + if(error == MfClassicErrorNone) { + *data = poller_context.data.read_block_context.block; + } + + return error; +} + +MfClassicError mf_classic_poller_write_block( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + MfClassicBlock* data) { + furi_assert(nfc); + furi_assert(key); + furi_assert(data); + + MfClassicPollerContext poller_context = { + .cmd_type = MfClassicPollerCmdTypeWriteBlock, + .data.write_block_context.block_num = block_num, + .data.write_block_context.key = *key, + .data.write_block_context.key_type = key_type, + .data.write_block_context.block = *data, + }; + + MfClassicError error = mf_classic_poller_cmd_execute(nfc, &poller_context); + + return error; +} + +MfClassicError mf_classic_poller_read_value( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + int32_t* value) { + furi_assert(nfc); + furi_assert(key); + furi_assert(value); + + MfClassicPollerContext poller_context = { + .cmd_type = MfClassicPollerCmdTypeReadValue, + .data.write_block_context.block_num = block_num, + .data.write_block_context.key = *key, + .data.write_block_context.key_type = key_type, + }; + + MfClassicError error = mf_classic_poller_cmd_execute(nfc, &poller_context); + + if(error == MfClassicErrorNone) { + *value = poller_context.data.read_value_context.value; + } + + return error; +} + +MfClassicError mf_classic_poller_change_value( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + int32_t data, + int32_t* new_value) { + furi_assert(nfc); + furi_assert(key); + furi_assert(new_value); + + MfClassicValueCommand command = MfClassicValueCommandRestore; + int32_t command_data = 0; + if(data > 0) { + command = MfClassicValueCommandIncrement; + command_data = data; + } else if(data < 0) { + command = MfClassicValueCommandDecrement; + command_data = -data; + } + + MfClassicPollerContext poller_context = { + .cmd_type = MfClassicPollerCmdTypeChangeValue, + .data.change_value_context.block_num = block_num, + .data.change_value_context.key = *key, + .data.change_value_context.key_type = key_type, + .data.change_value_context.value_cmd = command, + .data.change_value_context.data = command_data, + }; + + MfClassicError error = mf_classic_poller_cmd_execute(nfc, &poller_context); + + if(error == MfClassicErrorNone) { + *new_value = poller_context.data.change_value_context.new_value; + } + + return error; +} + +static bool mf_classic_poller_read_get_next_key( + MfClassicReadContext* read_ctx, + uint8_t* sector_num, + MfClassicKey* key, + MfClassicKeyType* key_type) { + bool next_key_found = false; + + for(uint8_t i = read_ctx->current_sector; i < MF_CLASSIC_TOTAL_SECTORS_MAX; i++) { + if(FURI_BIT(read_ctx->keys.key_a_mask, i)) { + FURI_BIT_CLEAR(read_ctx->keys.key_a_mask, i); + *key = read_ctx->keys.key_a[i]; + *key_type = MfClassicKeyTypeA; + *sector_num = i; + + next_key_found = true; + break; + } + if(FURI_BIT(read_ctx->keys.key_b_mask, i)) { + FURI_BIT_CLEAR(read_ctx->keys.key_b_mask, i); + *key = read_ctx->keys.key_b[i]; + *key_type = MfClassicKeyTypeB; + *sector_num = i; + + next_key_found = true; + read_ctx->current_sector = i; + break; + } + } + + return next_key_found; +} + +NfcCommand mf_classic_poller_read_callback(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolMfClassic); + + NfcCommand command = NfcCommandContinue; + MfClassicPollerContext* poller_context = context; + MfClassicPollerEvent* mfc_event = event.event_data; + + if(mfc_event->type == MfClassicPollerEventTypeCardLost) { + poller_context->error = MfClassicErrorNotPresent; + command = NfcCommandStop; + } else if(mfc_event->type == MfClassicPollerEventTypeRequestMode) { + mfc_event->data->poller_mode.mode = MfClassicPollerModeRead; + } else if(mfc_event->type == MfClassicPollerEventTypeRequestReadSector) { + MfClassicPollerEventDataReadSectorRequest* req_data = + &mfc_event->data->read_sector_request_data; + MfClassicKey key = {}; + MfClassicKeyType key_type = MfClassicKeyTypeA; + uint8_t sector_num = 0; + if(mf_classic_poller_read_get_next_key( + &poller_context->data.read_context, §or_num, &key, &key_type)) { + req_data->sector_num = sector_num; + req_data->key = key; + req_data->key_type = key_type; + req_data->key_provided = true; + } else { + req_data->key_provided = false; + } + } else if(mfc_event->type == MfClassicPollerEventTypeSuccess) { + command = NfcCommandStop; + } + + if(command == NfcCommandStop) { + furi_thread_flags_set(poller_context->thread_id, MF_CLASSIC_POLLER_COMPLETE_EVENT); + } + + return command; +} + +MfClassicError + mf_classic_poller_read(Nfc* nfc, const MfClassicDeviceKeys* keys, MfClassicData* data) { + furi_assert(nfc); + furi_assert(keys); + furi_assert(data); + + MfClassicError error = MfClassicErrorNone; + MfClassicPollerContext poller_context = {}; + poller_context.thread_id = furi_thread_get_current_id(); + poller_context.data.read_context.keys = *keys; + + NfcPoller* poller = nfc_poller_alloc(nfc, NfcProtocolMfClassic); + nfc_poller_start(poller, mf_classic_poller_read_callback, &poller_context); + furi_thread_flags_wait(MF_CLASSIC_POLLER_COMPLETE_EVENT, FuriFlagWaitAny, FuriWaitForever); + furi_thread_flags_clear(MF_CLASSIC_POLLER_COMPLETE_EVENT); + + nfc_poller_stop(poller); + + if(poller_context.error != MfClassicErrorNone) { + error = poller_context.error; + } else { + const MfClassicData* mfc_data = nfc_poller_get_data(poller); + uint8_t sectors_read = 0; + uint8_t keys_found = 0; + + mf_classic_get_read_sectors_and_keys(mfc_data, §ors_read, &keys_found); + if((sectors_read > 0) || (keys_found > 0)) { + mf_classic_copy(data, mfc_data); + } else { + error = MfClassicErrorNotPresent; + } + } + + nfc_poller_free(poller); + + return error; +} + +MfClassicError mf_classic_poller_detect_type(Nfc* nfc, MfClassicType* type) { + furi_assert(nfc); + furi_assert(type); + + MfClassicError error = MfClassicErrorNone; + + const uint8_t mf_classic_verify_block[MfClassicTypeNum] = { + [MfClassicTypeMini] = 0, + [MfClassicType1k] = 62, + [MfClassicType4k] = 254, + }; + + size_t i = 0; + for(i = 0; i < COUNT_OF(mf_classic_verify_block); i++) { + error = mf_classic_poller_collect_nt( + nfc, mf_classic_verify_block[MfClassicTypeNum - i - 1], MfClassicKeyTypeA, NULL); + if(error == MfClassicErrorNone) { + *type = MfClassicTypeNum - i - 1; + break; + } + } + + return error; +} diff --git a/lib/nfc/protocols/mf_classic/mf_classic_poller_sync_api.h b/lib/nfc/protocols/mf_classic/mf_classic_poller_sync_api.h new file mode 100644 index 000000000..11db291b8 --- /dev/null +++ b/lib/nfc/protocols/mf_classic/mf_classic_poller_sync_api.h @@ -0,0 +1,59 @@ +#pragma once + +#include "mf_classic.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +MfClassicError mf_classic_poller_collect_nt( + Nfc* nfc, + uint8_t block_num, + MfClassicKeyType key_type, + MfClassicNt* nt); + +MfClassicError mf_classic_poller_auth( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + MfClassicAuthContext* data); + +MfClassicError mf_classic_poller_read_block( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + MfClassicBlock* data); + +MfClassicError mf_classic_poller_write_block( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + MfClassicBlock* data); + +MfClassicError mf_classic_poller_read_value( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + int32_t* value); + +MfClassicError mf_classic_poller_change_value( + Nfc* nfc, + uint8_t block_num, + MfClassicKey* key, + MfClassicKeyType key_type, + int32_t data, + int32_t* new_value); + +MfClassicError mf_classic_poller_detect_type(Nfc* nfc, MfClassicType* type); + +MfClassicError + mf_classic_poller_read(Nfc* nfc, const MfClassicDeviceKeys* keys, MfClassicData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_desfire/mf_desfire.c b/lib/nfc/protocols/mf_desfire/mf_desfire.c new file mode 100644 index 000000000..b83198a25 --- /dev/null +++ b/lib/nfc/protocols/mf_desfire/mf_desfire.c @@ -0,0 +1,290 @@ +#include "mf_desfire_i.h" + +#include + +#define MF_DESFIRE_PROTOCOL_NAME "Mifare DESFire" + +const NfcDeviceBase nfc_device_mf_desfire = { + .protocol_name = MF_DESFIRE_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)mf_desfire_alloc, + .free = (NfcDeviceFree)mf_desfire_free, + .reset = (NfcDeviceReset)mf_desfire_reset, + .copy = (NfcDeviceCopy)mf_desfire_copy, + .verify = (NfcDeviceVerify)mf_desfire_verify, + .load = (NfcDeviceLoad)mf_desfire_load, + .save = (NfcDeviceSave)mf_desfire_save, + .is_equal = (NfcDeviceEqual)mf_desfire_is_equal, + .get_name = (NfcDeviceGetName)mf_desfire_get_device_name, + .get_uid = (NfcDeviceGetUid)mf_desfire_get_uid, + .set_uid = (NfcDeviceSetUid)mf_desfire_set_uid, + .get_base_data = (NfcDeviceGetBaseData)mf_desfire_get_base_data, +}; + +MfDesfireData* mf_desfire_alloc() { + MfDesfireData* data = malloc(sizeof(MfDesfireData)); + data->iso14443_4a_data = iso14443_4a_alloc(); + data->master_key_versions = simple_array_alloc(&mf_desfire_key_version_array_config); + data->application_ids = simple_array_alloc(&mf_desfire_app_id_array_config); + data->applications = simple_array_alloc(&mf_desfire_application_array_config); + + return data; +} + +void mf_desfire_free(MfDesfireData* data) { + furi_assert(data); + + mf_desfire_reset(data); + simple_array_free(data->applications); + simple_array_free(data->application_ids); + simple_array_free(data->master_key_versions); + iso14443_4a_free(data->iso14443_4a_data); + free(data); +} + +void mf_desfire_reset(MfDesfireData* data) { + furi_assert(data); + + iso14443_4a_reset(data->iso14443_4a_data); + + memset(&data->version, 0, sizeof(MfDesfireVersion)); + memset(&data->free_memory, 0, sizeof(MfDesfireFreeMemory)); + + simple_array_reset(data->master_key_versions); + simple_array_reset(data->application_ids); + simple_array_reset(data->applications); +} + +void mf_desfire_copy(MfDesfireData* data, const MfDesfireData* other) { + furi_assert(data); + furi_assert(other); + + mf_desfire_reset(data); + + iso14443_4a_copy(data->iso14443_4a_data, other->iso14443_4a_data); + + data->version = other->version; + data->free_memory = other->free_memory; + data->master_key_settings = other->master_key_settings; + + simple_array_copy(data->master_key_versions, other->master_key_versions); + simple_array_copy(data->application_ids, other->application_ids); + simple_array_copy(data->applications, other->applications); +} + +bool mf_desfire_verify(MfDesfireData* data, const FuriString* device_type) { + UNUSED(data); + return furi_string_equal_str(device_type, MF_DESFIRE_PROTOCOL_NAME); +} + +bool mf_desfire_load(MfDesfireData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + + FuriString* prefix = furi_string_alloc(); + + bool success = false; + + do { + if(!iso14443_4a_load(data->iso14443_4a_data, ff, version)) break; + + if(!mf_desfire_version_load(&data->version, ff)) break; + if(!mf_desfire_free_memory_load(&data->free_memory, ff)) break; + if(!mf_desfire_key_settings_load( + &data->master_key_settings, MF_DESFIRE_FFF_PICC_PREFIX, ff)) + break; + + const uint32_t master_key_version_count = data->master_key_settings.max_keys; + simple_array_init(data->master_key_versions, master_key_version_count); + + uint32_t i; + for(i = 0; i < master_key_version_count; ++i) { + if(!mf_desfire_key_version_load( + simple_array_get(data->master_key_versions, i), + MF_DESFIRE_FFF_PICC_PREFIX, + i, + ff)) + break; + } + + if(i != master_key_version_count) break; + + uint32_t application_count; + if(!mf_desfire_application_count_load(&application_count, ff)) break; + + if(application_count > 0) { + simple_array_init(data->application_ids, application_count); + if(!mf_desfire_application_ids_load( + simple_array_get_data(data->application_ids), application_count, ff)) + break; + + simple_array_init(data->applications, application_count); + for(i = 0; i < application_count; ++i) { + const MfDesfireApplicationId* app_id = simple_array_cget(data->application_ids, i); + furi_string_printf( + prefix, + "%s %02x%02x%02x", + MF_DESFIRE_FFF_APP_PREFIX, + app_id->data[0], + app_id->data[1], + app_id->data[2]); + + if(!mf_desfire_application_load( + simple_array_get(data->applications, i), furi_string_get_cstr(prefix), ff)) + break; + } + + if(i != application_count) break; + } + + success = true; + } while(false); + + furi_string_free(prefix); + return success; +} + +bool mf_desfire_save(const MfDesfireData* data, FlipperFormat* ff) { + furi_assert(data); + + FuriString* prefix = furi_string_alloc(); + + bool success = false; + + do { + if(!iso14443_4a_save(data->iso14443_4a_data, ff)) break; + + if(!flipper_format_write_comment_cstr(ff, MF_DESFIRE_PROTOCOL_NAME " specific data")) + break; + if(!mf_desfire_version_save(&data->version, ff)) break; + if(!mf_desfire_free_memory_save(&data->free_memory, ff)) break; + if(!mf_desfire_key_settings_save( + &data->master_key_settings, MF_DESFIRE_FFF_PICC_PREFIX, ff)) + break; + + const uint32_t master_key_version_count = + simple_array_get_count(data->master_key_versions); + + uint32_t i; + for(i = 0; i < master_key_version_count; ++i) { + if(!mf_desfire_key_version_save( + simple_array_cget(data->master_key_versions, i), + MF_DESFIRE_FFF_PICC_PREFIX, + i, + ff)) + break; + } + + if(i != master_key_version_count) break; + + const uint32_t application_count = simple_array_get_count(data->application_ids); + if(!mf_desfire_application_count_save(&application_count, ff)) break; + + if(application_count > 0) { + if(!mf_desfire_application_ids_save( + simple_array_cget_data(data->application_ids), application_count, ff)) + break; + + for(i = 0; i < application_count; ++i) { + const MfDesfireApplicationId* app_id = simple_array_cget(data->application_ids, i); + furi_string_printf( + prefix, + "%s %02x%02x%02x", + MF_DESFIRE_FFF_APP_PREFIX, + app_id->data[0], + app_id->data[1], + app_id->data[2]); + + const MfDesfireApplication* app = simple_array_cget(data->applications, i); + if(!mf_desfire_application_save(app, furi_string_get_cstr(prefix), ff)) break; + } + + if(i != application_count) break; + } + + success = true; + } while(false); + + furi_string_free(prefix); + return success; +} + +bool mf_desfire_is_equal(const MfDesfireData* data, const MfDesfireData* other) { + furi_assert(data); + furi_assert(other); + + return iso14443_4a_is_equal(data->iso14443_4a_data, other->iso14443_4a_data) && + memcmp(&data->version, &other->version, sizeof(MfDesfireVersion)) == 0 && + memcmp(&data->free_memory, &other->free_memory, sizeof(MfDesfireFreeMemory)) == 0 && + memcmp( + &data->master_key_settings, + &other->master_key_settings, + sizeof(MfDesfireKeySettings)) == 0 && + simple_array_is_equal(data->master_key_versions, other->master_key_versions) && + simple_array_is_equal(data->application_ids, other->application_ids) && + simple_array_is_equal(data->applications, other->applications); +} + +const char* mf_desfire_get_device_name(const MfDesfireData* data, NfcDeviceNameType name_type) { + UNUSED(data); + UNUSED(name_type); + return MF_DESFIRE_PROTOCOL_NAME; +} + +const uint8_t* mf_desfire_get_uid(const MfDesfireData* data, size_t* uid_len) { + furi_assert(data); + + return iso14443_4a_get_uid(data->iso14443_4a_data, uid_len); +} + +bool mf_desfire_set_uid(MfDesfireData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + return iso14443_4a_set_uid(data->iso14443_4a_data, uid, uid_len); +} + +Iso14443_4aData* mf_desfire_get_base_data(const MfDesfireData* data) { + furi_assert(data); + + return data->iso14443_4a_data; +} + +const MfDesfireApplication* + mf_desfire_get_application(const MfDesfireData* data, const MfDesfireApplicationId* app_id) { + MfDesfireApplication* app = NULL; + + for(uint32_t i = 0; i < simple_array_get_count(data->application_ids); ++i) { + const MfDesfireApplicationId* current_app_id = simple_array_cget(data->application_ids, i); + if(memcmp(app_id, current_app_id, sizeof(MfDesfireApplicationId)) == 0) { + app = simple_array_get(data->applications, i); + } + } + + return app; +} + +const MfDesfireFileSettings* + mf_desfire_get_file_settings(const MfDesfireApplication* data, const MfDesfireFileId* file_id) { + MfDesfireFileSettings* file_settings = NULL; + + for(uint32_t i = 0; i < simple_array_get_count(data->file_ids); ++i) { + const MfDesfireFileId* current_file_id = simple_array_cget(data->file_ids, i); + if(*file_id == *current_file_id) { + file_settings = simple_array_get(data->file_settings, i); + } + } + + return file_settings; +} + +const MfDesfireFileData* + mf_desfire_get_file_data(const MfDesfireApplication* data, const MfDesfireFileId* file_id) { + MfDesfireFileData* file_data = NULL; + + for(uint32_t i = 0; i < simple_array_get_count(data->file_ids); ++i) { + const MfDesfireFileId* current_file_id = simple_array_cget(data->file_ids, i); + if(*file_id == *current_file_id) { + file_data = simple_array_get(data->file_data, i); + } + } + + return file_data; +} diff --git a/lib/nfc/protocols/mf_desfire/mf_desfire.h b/lib/nfc/protocols/mf_desfire/mf_desfire.h new file mode 100644 index 000000000..8505b792a --- /dev/null +++ b/lib/nfc/protocols/mf_desfire/mf_desfire.h @@ -0,0 +1,192 @@ +#pragma once + +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define MF_DESFIRE_CMD_GET_VERSION (0x60) +#define MF_DESFIRE_CMD_GET_FREE_MEMORY (0x6E) +#define MF_DESFIRE_CMD_GET_KEY_SETTINGS (0x45) +#define MF_DESFIRE_CMD_GET_KEY_VERSION (0x64) +#define MF_DESFIRE_CMD_GET_APPLICATION_IDS (0x6A) +#define MF_DESFIRE_CMD_SELECT_APPLICATION (0x5A) +#define MF_DESFIRE_CMD_GET_FILE_IDS (0x6F) +#define MF_DESFIRE_CMD_GET_FILE_SETTINGS (0xF5) + +#define MF_DESFIRE_CMD_READ_DATA (0xBD) +#define MF_DESFIRE_CMD_GET_VALUE (0x6C) +#define MF_DESFIRE_CMD_READ_RECORDS (0xBB) + +#define MF_DESFIRE_FLAG_HAS_NEXT (0xAF) + +#define MF_DESFIRE_MAX_KEYS (14) +#define MF_DESFIRE_MAX_FILES (32) + +#define MF_DESFIRE_UID_SIZE (7) +#define MF_DESFIRE_BATCH_SIZE (5) +#define MF_DESFIRE_APP_ID_SIZE (3) +#define MF_DESFIRE_VALUE_SIZE (4) + +typedef struct { + uint8_t hw_vendor; + uint8_t hw_type; + uint8_t hw_subtype; + uint8_t hw_major; + uint8_t hw_minor; + uint8_t hw_storage; + uint8_t hw_proto; + + uint8_t sw_vendor; + uint8_t sw_type; + uint8_t sw_subtype; + uint8_t sw_major; + uint8_t sw_minor; + uint8_t sw_storage; + uint8_t sw_proto; + + uint8_t uid[MF_DESFIRE_UID_SIZE]; + uint8_t batch[MF_DESFIRE_BATCH_SIZE]; + uint8_t prod_week; + uint8_t prod_year; +} MfDesfireVersion; + +typedef struct { + uint32_t bytes_free; + bool is_present; +} MfDesfireFreeMemory; // EV1+ only + +typedef struct { + bool is_master_key_changeable; + bool is_free_directory_list; + bool is_free_create_delete; + bool is_config_changeable; + uint8_t change_key_id; + uint8_t max_keys; + uint8_t flags; +} MfDesfireKeySettings; + +typedef uint8_t MfDesfireKeyVersion; + +typedef struct { + MfDesfireKeySettings key_settings; + SimpleArray* key_versions; +} MfDesfireKeyConfiguration; + +typedef enum { + MfDesfireFileTypeStandard = 0, + MfDesfireFileTypeBackup = 1, + MfDesfireFileTypeValue = 2, + MfDesfireFileTypeLinearRecord = 3, + MfDesfireFileTypeCyclicRecord = 4, +} MfDesfireFileType; + +typedef enum { + MfDesfireFileCommunicationSettingsPlaintext = 0, + MfDesfireFileCommunicationSettingsAuthenticated = 1, + MfDesfireFileCommunicationSettingsEnciphered = 3, +} MfDesfireFileCommunicationSettings; + +typedef uint8_t MfDesfireFileId; +typedef uint16_t MfDesfireFileAccessRights; + +typedef struct { + MfDesfireFileType type; + MfDesfireFileCommunicationSettings comm; + MfDesfireFileAccessRights access_rights; + union { + struct { + uint32_t size; + } data; + struct { + uint32_t lo_limit; + uint32_t hi_limit; + uint32_t limited_credit_value; + bool limited_credit_enabled; + } value; + struct { + uint32_t size; + uint32_t max; + uint32_t cur; + } record; + }; +} MfDesfireFileSettings; + +typedef struct { + SimpleArray* data; +} MfDesfireFileData; + +typedef struct { + uint8_t data[MF_DESFIRE_APP_ID_SIZE]; +} MfDesfireApplicationId; + +typedef struct MfDesfireApplication { + MfDesfireKeySettings key_settings; + SimpleArray* key_versions; + SimpleArray* file_ids; + SimpleArray* file_settings; + SimpleArray* file_data; +} MfDesfireApplication; + +typedef enum { + MfDesfireErrorNone, + MfDesfireErrorNotPresent, + MfDesfireErrorProtocol, + MfDesfireErrorTimeout, +} MfDesfireError; + +typedef struct { + Iso14443_4aData* iso14443_4a_data; + MfDesfireVersion version; + MfDesfireFreeMemory free_memory; + MfDesfireKeySettings master_key_settings; + SimpleArray* master_key_versions; + SimpleArray* application_ids; + SimpleArray* applications; +} MfDesfireData; + +extern const NfcDeviceBase nfc_device_mf_desfire; + +// Virtual methods + +MfDesfireData* mf_desfire_alloc(); + +void mf_desfire_free(MfDesfireData* data); + +void mf_desfire_reset(MfDesfireData* data); + +void mf_desfire_copy(MfDesfireData* data, const MfDesfireData* other); + +bool mf_desfire_verify(MfDesfireData* data, const FuriString* device_type); + +bool mf_desfire_load(MfDesfireData* data, FlipperFormat* ff, uint32_t version); + +bool mf_desfire_save(const MfDesfireData* data, FlipperFormat* ff); + +bool mf_desfire_is_equal(const MfDesfireData* data, const MfDesfireData* other); + +const char* mf_desfire_get_device_name(const MfDesfireData* data, NfcDeviceNameType name_type); + +const uint8_t* mf_desfire_get_uid(const MfDesfireData* data, size_t* uid_len); + +bool mf_desfire_set_uid(MfDesfireData* data, const uint8_t* uid, size_t uid_len); + +Iso14443_4aData* mf_desfire_get_base_data(const MfDesfireData* data); + +// Getters and tests + +const MfDesfireApplication* + mf_desfire_get_application(const MfDesfireData* data, const MfDesfireApplicationId* app_id); + +const MfDesfireFileSettings* + mf_desfire_get_file_settings(const MfDesfireApplication* data, const MfDesfireFileId* file_id); + +const MfDesfireFileData* + mf_desfire_get_file_data(const MfDesfireApplication* data, const MfDesfireFileId* file_id); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_desfire/mf_desfire_i.c b/lib/nfc/protocols/mf_desfire/mf_desfire_i.c new file mode 100644 index 000000000..30313ae2b --- /dev/null +++ b/lib/nfc/protocols/mf_desfire/mf_desfire_i.c @@ -0,0 +1,790 @@ +#include "mf_desfire_i.h" + +#define BITS_IN_BYTE (8U) + +#define MF_DESFIRE_FFF_VERSION_KEY \ + MF_DESFIRE_FFF_PICC_PREFIX " " \ + "Version" +#define MF_DESFIRE_FFF_FREE_MEM_KEY \ + MF_DESFIRE_FFF_PICC_PREFIX " " \ + "Free Memory" + +#define MF_DESFIRE_FFF_CHANGE_KEY_ID_KEY "Change Key ID" +#define MF_DESFIRE_FFF_CONFIG_CHANGEABLE_KEY "Config Changeable" +#define MF_DESFIRE_FFF_FREE_CREATE_DELETE_KEY "Free Create Delete" +#define MF_DESFIRE_FFF_FREE_DIR_LIST_KEY "Free Directory List" +#define MF_DESFIRE_FFF_KEY_CHANGEABLE_KEY "Key Changeable" +#define MF_DESFIRE_FFF_FLAGS_KEY "Flags" +#define MF_DESFIRE_FFF_MAX_KEYS_KEY "Max Keys" + +#define MF_DESFIRE_FFF_KEY_SUB_PREFIX "Key" +#define MF_DESFIRE_FFF_KEY_VERSION_KEY "Version" + +#define MF_DESFIRE_FFF_APPLICATION_COUNT_KEY \ + MF_DESFIRE_FFF_APP_PREFIX " " \ + "Count" +#define MF_DESFIRE_FFF_APPLICATION_IDS_KEY \ + MF_DESFIRE_FFF_APP_PREFIX " " \ + "IDs" + +#define MF_DESFIRE_FFF_FILE_SUB_PREFIX "File" +#define MF_DESFIRE_FFF_FILE_IDS_KEY \ + MF_DESFIRE_FFF_FILE_SUB_PREFIX " " \ + "IDs" +#define MF_DESFIRE_FFF_FILE_TYPE_KEY "Type" +#define MF_DESFIRE_FFF_FILE_COMM_SETTINGS_KEY "Communication Settings" +#define MF_DESFIRE_FFF_FILE_ACCESS_RIGHTS_KEY "Access Rights" + +#define MF_DESFIRE_FFF_FILE_SIZE_KEY "Size" + +#define MF_DESFIRE_FFF_FILE_HI_LIMIT_KEY "Hi Limit" +#define MF_DESFIRE_FFF_FILE_LO_LIMIT_KEY "Lo Limit" +#define MF_DESFIRE_FFF_FILE_LIMIT_CREDIT_VALUE_KEY "Limited Credit Value" +#define MF_DESFIRE_FFF_FILE_LIMIT_CREDIT_ENABLED_KEY "Limited Credit Enabled" + +#define MF_DESFIRE_FFF_FILE_MAX_KEY "Max" +#define MF_DESFIRE_FFF_FILE_CUR_KEY "Cur" + +bool mf_desfire_version_parse(MfDesfireVersion* data, const BitBuffer* buf) { + const bool can_parse = bit_buffer_get_size_bytes(buf) == sizeof(MfDesfireVersion); + + if(can_parse) { + bit_buffer_write_bytes(buf, data, sizeof(MfDesfireVersion)); + } + + return can_parse; +} + +bool mf_desfire_free_memory_parse(MfDesfireFreeMemory* data, const BitBuffer* buf) { + typedef struct __attribute__((packed)) { + uint32_t bytes_free : 3 * BITS_IN_BYTE; + } MfDesfireFreeMemoryLayout; + + const bool can_parse = bit_buffer_get_size_bytes(buf) == sizeof(MfDesfireFreeMemoryLayout); + + if(can_parse) { + MfDesfireFreeMemoryLayout layout; + bit_buffer_write_bytes(buf, &layout, sizeof(MfDesfireFreeMemoryLayout)); + data->bytes_free = layout.bytes_free; + } + + data->is_present = can_parse; + + return can_parse; +} + +bool mf_desfire_key_settings_parse(MfDesfireKeySettings* data, const BitBuffer* buf) { + typedef struct __attribute__((packed)) { + bool is_master_key_changeable : 1; + bool is_free_directory_list : 1; + bool is_free_create_delete : 1; + bool is_config_changeable : 1; + uint8_t change_key_id : 4; + uint8_t max_keys : 4; + uint8_t flags : 4; + } MfDesfireKeySettingsLayout; + + const bool can_parse = bit_buffer_get_size_bytes(buf) == sizeof(MfDesfireKeySettingsLayout); + + if(can_parse) { + MfDesfireKeySettingsLayout layout; + bit_buffer_write_bytes(buf, &layout, sizeof(MfDesfireKeySettingsLayout)); + + data->is_master_key_changeable = layout.is_master_key_changeable; + data->is_free_directory_list = layout.is_free_directory_list; + data->is_free_create_delete = layout.is_free_create_delete; + data->is_config_changeable = layout.is_config_changeable; + + data->change_key_id = layout.change_key_id; + data->max_keys = layout.max_keys; + data->flags = layout.flags; + } + + return can_parse; +} + +bool mf_desfire_key_version_parse(MfDesfireKeyVersion* data, const BitBuffer* buf) { + const bool can_parse = bit_buffer_get_size_bytes(buf) == sizeof(MfDesfireKeyVersion); + + if(can_parse) { + bit_buffer_write_bytes(buf, data, sizeof(MfDesfireKeyVersion)); + } + + return can_parse; +} + +bool mf_desfire_application_id_parse( + MfDesfireApplicationId* data, + uint32_t index, + const BitBuffer* buf) { + const bool can_parse = + bit_buffer_get_size_bytes(buf) >= + (index * sizeof(MfDesfireApplicationId) + sizeof(MfDesfireApplicationId)); + + if(can_parse) { + bit_buffer_write_bytes_mid( + buf, data, index * sizeof(MfDesfireApplicationId), sizeof(MfDesfireApplicationId)); + } + + return can_parse; +} + +bool mf_desfire_file_id_parse(MfDesfireFileId* data, uint32_t index, const BitBuffer* buf) { + const bool can_parse = bit_buffer_get_size_bytes(buf) >= + (index * sizeof(MfDesfireFileId) + sizeof(MfDesfireFileId)); + if(can_parse) { + bit_buffer_write_bytes_mid( + buf, data, index * sizeof(MfDesfireFileId), sizeof(MfDesfireFileId)); + } + + return can_parse; +} + +bool mf_desfire_file_settings_parse(MfDesfireFileSettings* data, const BitBuffer* buf) { + bool parsed = false; + + typedef struct __attribute__((packed)) { + uint8_t type; + uint8_t comm; + uint16_t access_rights; + } MfDesfireFileSettingsHeader; + + typedef struct __attribute__((packed)) { + uint32_t size : 3 * BITS_IN_BYTE; + } MfDesfireFileSettingsData; + + typedef struct __attribute__((packed)) { + uint32_t lo_limit; + uint32_t hi_limit; + uint32_t limited_credit_value; + uint8_t limited_credit_enabled; + } MfDesfireFileSettingsValue; + + typedef struct __attribute__((packed)) { + uint32_t size : 3 * BITS_IN_BYTE; + uint32_t max : 3 * BITS_IN_BYTE; + uint32_t cur : 3 * BITS_IN_BYTE; + } MfDesfireFileSettingsRecord; + + typedef struct __attribute__((packed)) { + MfDesfireFileSettingsHeader header; + union { + MfDesfireFileSettingsData data; + MfDesfireFileSettingsValue value; + MfDesfireFileSettingsRecord record; + }; + } MfDesfireFileSettingsLayout; + + do { + const size_t data_size = bit_buffer_get_size_bytes(buf); + const size_t min_data_size = + sizeof(MfDesfireFileSettingsHeader) + sizeof(MfDesfireFileSettingsData); + + if(data_size < min_data_size) break; + + MfDesfireFileSettingsLayout layout; + bit_buffer_write_bytes(buf, &layout, sizeof(MfDesfireFileSettingsLayout)); + + data->type = layout.header.type; + data->comm = layout.header.comm; + data->access_rights = layout.header.access_rights; + + if(data->type == MfDesfireFileTypeStandard || data->type == MfDesfireFileTypeBackup) { + if(data_size != min_data_size) break; + + data->data.size = layout.data.size; + + } else if(data->type == MfDesfireFileTypeValue) { + if(data_size != + sizeof(MfDesfireFileSettingsHeader) + sizeof(MfDesfireFileSettingsValue)) + break; + + data->value.lo_limit = layout.value.lo_limit; + data->value.hi_limit = layout.value.hi_limit; + data->value.limited_credit_value = layout.value.hi_limit; + data->value.limited_credit_enabled = layout.value.limited_credit_enabled; + + } else if( + data->type == MfDesfireFileTypeLinearRecord || + data->type == MfDesfireFileTypeCyclicRecord) { + if(data_size != + sizeof(MfDesfireFileSettingsHeader) + sizeof(MfDesfireFileSettingsRecord)) + break; + + data->record.size = layout.record.size; + data->record.max = layout.record.max; + data->record.cur = layout.record.cur; + + } else { + break; + } + + parsed = true; + } while(false); + + return parsed; +} + +bool mf_desfire_file_data_parse(MfDesfireFileData* data, const BitBuffer* buf) { + const size_t data_size = bit_buffer_get_size_bytes(buf); + + if(data_size > 0) { + simple_array_init(data->data, data_size); + bit_buffer_write_bytes(buf, simple_array_get_data(data->data), data_size); + } + + // Success no matter whether there is data or not + return true; +} + +void mf_desfire_file_data_init(MfDesfireFileData* data) { + data->data = simple_array_alloc(&simple_array_config_uint8_t); +} + +void mf_desfire_application_init(MfDesfireApplication* data) { + data->key_versions = simple_array_alloc(&mf_desfire_key_version_array_config); + data->file_ids = simple_array_alloc(&mf_desfire_file_id_array_config); + data->file_settings = simple_array_alloc(&mf_desfire_file_settings_array_config); + data->file_data = simple_array_alloc(&mf_desfire_file_data_array_config); +} + +void mf_desfire_file_data_reset(MfDesfireFileData* data) { + simple_array_free(data->data); + memset(data, 0, sizeof(MfDesfireFileData)); +} + +void mf_desfire_application_reset(MfDesfireApplication* data) { + simple_array_free(data->key_versions); + simple_array_free(data->file_ids); + simple_array_free(data->file_settings); + simple_array_free(data->file_data); + memset(data, 0, sizeof(MfDesfireApplication)); +} + +void mf_desfire_file_data_copy(MfDesfireFileData* data, const MfDesfireFileData* other) { + simple_array_copy(data->data, other->data); +} + +void mf_desfire_application_copy(MfDesfireApplication* data, const MfDesfireApplication* other) { + data->key_settings = other->key_settings; + simple_array_copy(data->key_versions, other->key_versions); + simple_array_copy(data->file_ids, other->file_ids); + simple_array_copy(data->file_settings, other->file_settings); + simple_array_copy(data->file_data, other->file_data); +} + +bool mf_desfire_version_load(MfDesfireVersion* data, FlipperFormat* ff) { + return flipper_format_read_hex( + ff, MF_DESFIRE_FFF_VERSION_KEY, (uint8_t*)data, sizeof(MfDesfireVersion)); +} + +bool mf_desfire_free_memory_load(MfDesfireFreeMemory* data, FlipperFormat* ff) { + data->is_present = flipper_format_key_exist(ff, MF_DESFIRE_FFF_FREE_MEM_KEY); + return data->is_present ? + flipper_format_read_uint32(ff, MF_DESFIRE_FFF_FREE_MEM_KEY, &data->bytes_free, 1) : + true; +} + +bool mf_desfire_key_settings_load( + MfDesfireKeySettings* data, + const char* prefix, + FlipperFormat* ff) { + bool success = false; + + FuriString* key = furi_string_alloc(); + + do { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_CHANGE_KEY_ID_KEY); + if(!flipper_format_read_hex(ff, furi_string_get_cstr(key), &data->change_key_id, 1)) break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_CONFIG_CHANGEABLE_KEY); + if(!flipper_format_read_bool(ff, furi_string_get_cstr(key), &data->is_config_changeable, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FREE_CREATE_DELETE_KEY); + if(!flipper_format_read_bool( + ff, furi_string_get_cstr(key), &data->is_free_create_delete, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FREE_DIR_LIST_KEY); + if(!flipper_format_read_bool( + ff, furi_string_get_cstr(key), &data->is_free_directory_list, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_KEY_CHANGEABLE_KEY); + if(!flipper_format_read_bool( + ff, furi_string_get_cstr(key), &data->is_master_key_changeable, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FLAGS_KEY); + if(flipper_format_key_exist(ff, furi_string_get_cstr(key))) { + if(!flipper_format_read_hex(ff, furi_string_get_cstr(key), &data->flags, 1)) break; + } + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_MAX_KEYS_KEY); + if(!flipper_format_read_hex(ff, furi_string_get_cstr(key), &data->max_keys, 1)) break; + + success = true; + } while(false); + + furi_string_free(key); + return success; +} + +bool mf_desfire_key_version_load( + MfDesfireKeyVersion* data, + const char* prefix, + uint32_t index, + FlipperFormat* ff) { + FuriString* key = furi_string_alloc_printf( + "%s %s %lu %s", + prefix, + MF_DESFIRE_FFF_KEY_SUB_PREFIX, + index, + MF_DESFIRE_FFF_KEY_VERSION_KEY); + const bool success = flipper_format_read_hex(ff, furi_string_get_cstr(key), data, 1); + furi_string_free(key); + return success; +} + +bool mf_desfire_file_count_load(uint32_t* data, const char* prefix, FlipperFormat* ff) { + FuriString* key = furi_string_alloc_printf("%s %s", prefix, MF_DESFIRE_FFF_FILE_IDS_KEY); + const bool success = flipper_format_get_value_count(ff, furi_string_get_cstr(key), data); + furi_string_free(key); + return success; +} + +bool mf_desfire_file_ids_load( + MfDesfireFileId* data, + uint32_t count, + const char* prefix, + FlipperFormat* ff) { + FuriString* key = furi_string_alloc_printf("%s %s", prefix, MF_DESFIRE_FFF_FILE_IDS_KEY); + const bool success = flipper_format_read_hex(ff, furi_string_get_cstr(key), data, count); + furi_string_free(key); + return success; +} + +bool mf_desfire_file_settings_load( + MfDesfireFileSettings* data, + const char* prefix, + FlipperFormat* ff) { + bool success = false; + + FuriString* key = furi_string_alloc(); + + do { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_TYPE_KEY); + if(!flipper_format_read_hex(ff, furi_string_get_cstr(key), (uint8_t*)&data->type, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_COMM_SETTINGS_KEY); + if(!flipper_format_read_hex(ff, furi_string_get_cstr(key), (uint8_t*)&data->comm, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_ACCESS_RIGHTS_KEY); + if(!flipper_format_read_hex( + ff, + furi_string_get_cstr(key), + (uint8_t*)&data->access_rights, + sizeof(MfDesfireFileAccessRights))) + break; + + if(data->type == MfDesfireFileTypeStandard || data->type == MfDesfireFileTypeBackup) { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_SIZE_KEY); + if(!flipper_format_read_uint32(ff, furi_string_get_cstr(key), &data->data.size, 1)) + break; + + } else if(data->type == MfDesfireFileTypeValue) { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_HI_LIMIT_KEY); + if(!flipper_format_read_uint32(ff, furi_string_get_cstr(key), &data->value.hi_limit, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_LO_LIMIT_KEY); + if(!flipper_format_read_uint32(ff, furi_string_get_cstr(key), &data->value.lo_limit, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_LIMIT_CREDIT_VALUE_KEY); + if(!flipper_format_read_uint32( + ff, furi_string_get_cstr(key), &data->value.limited_credit_value, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_LIMIT_CREDIT_ENABLED_KEY); + if(!flipper_format_read_bool( + ff, furi_string_get_cstr(key), &data->value.limited_credit_enabled, 1)) + break; + } else if( + data->type == MfDesfireFileTypeLinearRecord || + data->type == MfDesfireFileTypeCyclicRecord) { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_SIZE_KEY); + if(!flipper_format_read_uint32(ff, furi_string_get_cstr(key), &data->record.size, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_MAX_KEY); + if(!flipper_format_read_uint32(ff, furi_string_get_cstr(key), &data->record.max, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_CUR_KEY); + if(!flipper_format_read_uint32(ff, furi_string_get_cstr(key), &data->record.cur, 1)) + break; + } + + success = true; + } while(false); + + furi_string_free(key); + + return success; +} + +bool mf_desfire_file_data_load(MfDesfireFileData* data, const char* prefix, FlipperFormat* ff) { + bool success = false; + do { + if(!flipper_format_key_exist(ff, prefix)) { + success = true; + break; + } + + uint32_t data_size; + if(!flipper_format_get_value_count(ff, prefix, &data_size)) break; + + simple_array_init(data->data, data_size); + + if(!flipper_format_read_hex(ff, prefix, simple_array_get_data(data->data), data_size)) + break; + + success = true; + } while(false); + + return success; +} + +bool mf_desfire_application_count_load(uint32_t* data, FlipperFormat* ff) { + return flipper_format_read_uint32(ff, MF_DESFIRE_FFF_APPLICATION_COUNT_KEY, data, 1); +} + +bool mf_desfire_application_ids_load( + MfDesfireApplicationId* data, + uint32_t count, + FlipperFormat* ff) { + return flipper_format_read_hex( + ff, MF_DESFIRE_FFF_APPLICATION_IDS_KEY, data->data, count * sizeof(MfDesfireApplicationId)); +} + +bool mf_desfire_application_load(MfDesfireApplication* data, const char* prefix, FlipperFormat* ff) { + FuriString* sub_prefix = furi_string_alloc(); + bool success = false; + + do { + if(!mf_desfire_key_settings_load(&data->key_settings, prefix, ff)) break; + + const uint32_t key_version_count = data->key_settings.max_keys; + simple_array_init(data->key_versions, key_version_count); + + uint32_t i; + for(i = 0; i < key_version_count; ++i) { + if(!mf_desfire_key_version_load(simple_array_get(data->key_versions, i), prefix, i, ff)) + break; + } + + if(i != key_version_count) break; + + uint32_t file_count; + if(!mf_desfire_file_count_load(&file_count, prefix, ff)) break; + + simple_array_init(data->file_ids, file_count); + if(!mf_desfire_file_ids_load(simple_array_get_data(data->file_ids), file_count, prefix, ff)) + break; + + simple_array_init(data->file_settings, file_count); + simple_array_init(data->file_data, file_count); + + for(i = 0; i < file_count; ++i) { + const MfDesfireFileId* file_id = simple_array_cget(data->file_ids, i); + furi_string_printf( + sub_prefix, "%s %s %u", prefix, MF_DESFIRE_FFF_FILE_SUB_PREFIX, *file_id); + + MfDesfireFileSettings* file_settings = simple_array_get(data->file_settings, i); + if(!mf_desfire_file_settings_load(file_settings, furi_string_get_cstr(sub_prefix), ff)) + break; + + MfDesfireFileData* file_data = simple_array_get(data->file_data, i); + if(!mf_desfire_file_data_load(file_data, furi_string_get_cstr(sub_prefix), ff)) break; + } + + if(i != file_count) break; + + success = true; + } while(false); + + furi_string_free(sub_prefix); + return success; +} + +bool mf_desfire_version_save(const MfDesfireVersion* data, FlipperFormat* ff) { + return flipper_format_write_hex( + ff, MF_DESFIRE_FFF_VERSION_KEY, (const uint8_t*)data, sizeof(MfDesfireVersion)); +} + +bool mf_desfire_free_memory_save(const MfDesfireFreeMemory* data, FlipperFormat* ff) { + return data->is_present ? + flipper_format_write_uint32(ff, MF_DESFIRE_FFF_FREE_MEM_KEY, &data->bytes_free, 1) : + true; +} + +bool mf_desfire_key_settings_save( + const MfDesfireKeySettings* data, + const char* prefix, + FlipperFormat* ff) { + bool success = false; + + FuriString* key = furi_string_alloc(); + + do { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_CHANGE_KEY_ID_KEY); + if(!flipper_format_write_hex(ff, furi_string_get_cstr(key), &data->change_key_id, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_CONFIG_CHANGEABLE_KEY); + if(!flipper_format_write_bool( + ff, furi_string_get_cstr(key), &data->is_config_changeable, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FREE_CREATE_DELETE_KEY); + if(!flipper_format_write_bool( + ff, furi_string_get_cstr(key), &data->is_free_create_delete, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FREE_DIR_LIST_KEY); + if(!flipper_format_write_bool( + ff, furi_string_get_cstr(key), &data->is_free_directory_list, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_KEY_CHANGEABLE_KEY); + if(!flipper_format_write_bool( + ff, furi_string_get_cstr(key), &data->is_master_key_changeable, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FLAGS_KEY); + if(!flipper_format_write_hex(ff, furi_string_get_cstr(key), &data->flags, 1)) break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_MAX_KEYS_KEY); + if(!flipper_format_write_hex(ff, furi_string_get_cstr(key), &data->max_keys, 1)) break; + + success = true; + } while(false); + + furi_string_free(key); + return success; +} + +bool mf_desfire_key_version_save( + const MfDesfireKeyVersion* data, + const char* prefix, + uint32_t index, + FlipperFormat* ff) { + FuriString* key = furi_string_alloc_printf( + "%s %s %lu %s", + prefix, + MF_DESFIRE_FFF_KEY_SUB_PREFIX, + index, + MF_DESFIRE_FFF_KEY_VERSION_KEY); + const bool success = flipper_format_write_hex(ff, furi_string_get_cstr(key), data, 1); + furi_string_free(key); + return success; +} + +bool mf_desfire_file_ids_save( + const MfDesfireFileId* data, + uint32_t count, + const char* prefix, + FlipperFormat* ff) { + FuriString* key = furi_string_alloc_printf("%s %s", prefix, MF_DESFIRE_FFF_FILE_IDS_KEY); + const bool success = flipper_format_write_hex(ff, furi_string_get_cstr(key), data, count); + furi_string_free(key); + return success; +} + +bool mf_desfire_file_settings_save( + const MfDesfireFileSettings* data, + const char* prefix, + FlipperFormat* ff) { + bool success = false; + + FuriString* key = furi_string_alloc(); + + do { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_TYPE_KEY); + if(!flipper_format_write_hex(ff, furi_string_get_cstr(key), (const uint8_t*)&data->type, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_COMM_SETTINGS_KEY); + if(!flipper_format_write_hex(ff, furi_string_get_cstr(key), (const uint8_t*)&data->comm, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_ACCESS_RIGHTS_KEY); + if(!flipper_format_write_hex( + ff, + furi_string_get_cstr(key), + (const uint8_t*)&data->access_rights, + sizeof(MfDesfireFileAccessRights))) + break; + + if(data->type == MfDesfireFileTypeStandard || data->type == MfDesfireFileTypeBackup) { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_SIZE_KEY); + if(!flipper_format_write_uint32(ff, furi_string_get_cstr(key), &data->data.size, 1)) + break; + + } else if(data->type == MfDesfireFileTypeValue) { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_HI_LIMIT_KEY); + if(!flipper_format_write_uint32( + ff, furi_string_get_cstr(key), &data->value.hi_limit, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_LO_LIMIT_KEY); + if(!flipper_format_write_uint32( + ff, furi_string_get_cstr(key), &data->value.lo_limit, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_LIMIT_CREDIT_VALUE_KEY); + if(!flipper_format_write_uint32( + ff, furi_string_get_cstr(key), &data->value.limited_credit_value, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_LIMIT_CREDIT_ENABLED_KEY); + if(!flipper_format_write_bool( + ff, furi_string_get_cstr(key), &data->value.limited_credit_enabled, 1)) + break; + } else if( + data->type == MfDesfireFileTypeLinearRecord || + data->type == MfDesfireFileTypeCyclicRecord) { + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_SIZE_KEY); + if(!flipper_format_write_uint32(ff, furi_string_get_cstr(key), &data->record.size, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_MAX_KEY); + if(!flipper_format_write_uint32(ff, furi_string_get_cstr(key), &data->record.max, 1)) + break; + + furi_string_printf(key, "%s %s", prefix, MF_DESFIRE_FFF_FILE_CUR_KEY); + if(!flipper_format_write_uint32(ff, furi_string_get_cstr(key), &data->record.cur, 1)) + break; + } + + success = true; + } while(false); + + furi_string_free(key); + return success; +} + +bool mf_desfire_file_data_save( + const MfDesfireFileData* data, + const char* prefix, + FlipperFormat* ff) { + const uint32_t data_size = simple_array_get_count(data->data); + return data_size > 0 ? flipper_format_write_hex( + ff, prefix, simple_array_cget_data(data->data), data_size) : + true; +} + +bool mf_desfire_application_count_save(const uint32_t* data, FlipperFormat* ff) { + return flipper_format_write_uint32(ff, MF_DESFIRE_FFF_APPLICATION_COUNT_KEY, data, 1); +} + +bool mf_desfire_application_ids_save( + const MfDesfireApplicationId* data, + uint32_t count, + FlipperFormat* ff) { + return flipper_format_write_hex( + ff, MF_DESFIRE_FFF_APPLICATION_IDS_KEY, data->data, count * sizeof(MfDesfireApplicationId)); +} + +bool mf_desfire_application_save( + const MfDesfireApplication* data, + const char* prefix, + FlipperFormat* ff) { + FuriString* sub_prefix = furi_string_alloc(); + bool success = false; + + do { + if(!mf_desfire_key_settings_save(&data->key_settings, prefix, ff)) break; + + const uint32_t key_version_count = data->key_settings.max_keys; + + uint32_t i; + for(i = 0; i < key_version_count; ++i) { + if(!mf_desfire_key_version_save( + simple_array_cget(data->key_versions, i), prefix, i, ff)) + break; + } + + if(i != key_version_count) break; + + const uint32_t file_count = simple_array_get_count(data->file_ids); + if(!mf_desfire_file_ids_save(simple_array_get_data(data->file_ids), file_count, prefix, ff)) + break; + + for(i = 0; i < file_count; ++i) { + const MfDesfireFileId* file_id = simple_array_cget(data->file_ids, i); + furi_string_printf( + sub_prefix, "%s %s %u", prefix, MF_DESFIRE_FFF_FILE_SUB_PREFIX, *file_id); + + const MfDesfireFileSettings* file_settings = simple_array_cget(data->file_settings, i); + if(!mf_desfire_file_settings_save(file_settings, furi_string_get_cstr(sub_prefix), ff)) + break; + + const MfDesfireFileData* file_data = simple_array_cget(data->file_data, i); + if(!mf_desfire_file_data_save(file_data, furi_string_get_cstr(sub_prefix), ff)) break; + } + + if(i != file_count) break; + + success = true; + } while(false); + + furi_string_free(sub_prefix); + return success; +} + +const SimpleArrayConfig mf_desfire_key_version_array_config = { + .init = NULL, + .copy = NULL, + .reset = NULL, + .type_size = sizeof(MfDesfireKeyVersion), +}; + +const SimpleArrayConfig mf_desfire_app_id_array_config = { + .init = NULL, + .copy = NULL, + .reset = NULL, + .type_size = sizeof(MfDesfireApplicationId), +}; + +const SimpleArrayConfig mf_desfire_file_id_array_config = { + .init = NULL, + .copy = NULL, + .reset = NULL, + .type_size = sizeof(MfDesfireFileId), +}; + +const SimpleArrayConfig mf_desfire_file_settings_array_config = { + .init = NULL, + .copy = NULL, + .reset = NULL, + .type_size = sizeof(MfDesfireFileSettings), +}; + +const SimpleArrayConfig mf_desfire_file_data_array_config = { + .init = (SimpleArrayInit)mf_desfire_file_data_init, + .copy = (SimpleArrayCopy)mf_desfire_file_data_copy, + .reset = (SimpleArrayReset)mf_desfire_file_data_reset, + .type_size = sizeof(MfDesfireData), +}; + +const SimpleArrayConfig mf_desfire_application_array_config = { + .init = (SimpleArrayInit)mf_desfire_application_init, + .copy = (SimpleArrayCopy)mf_desfire_application_copy, + .reset = (SimpleArrayReset)mf_desfire_application_reset, + .type_size = sizeof(MfDesfireApplication), +}; diff --git a/lib/nfc/protocols/mf_desfire/mf_desfire_i.h b/lib/nfc/protocols/mf_desfire/mf_desfire_i.h new file mode 100644 index 000000000..05381096d --- /dev/null +++ b/lib/nfc/protocols/mf_desfire/mf_desfire_i.h @@ -0,0 +1,140 @@ +#pragma once + +#include "mf_desfire.h" + +#define MF_DESFIRE_FFF_PICC_PREFIX "PICC" +#define MF_DESFIRE_FFF_APP_PREFIX "Application" + +// SimpleArray configurations + +extern const SimpleArrayConfig mf_desfire_key_version_array_config; +extern const SimpleArrayConfig mf_desfire_app_id_array_config; +extern const SimpleArrayConfig mf_desfire_file_id_array_config; +extern const SimpleArrayConfig mf_desfire_file_settings_array_config; +extern const SimpleArrayConfig mf_desfire_file_data_array_config; +extern const SimpleArrayConfig mf_desfire_application_array_config; + +// Parse internal MfDesfire structures + +bool mf_desfire_version_parse(MfDesfireVersion* data, const BitBuffer* buf); + +bool mf_desfire_free_memory_parse(MfDesfireFreeMemory* data, const BitBuffer* buf); + +bool mf_desfire_key_settings_parse(MfDesfireKeySettings* data, const BitBuffer* buf); + +bool mf_desfire_key_version_parse(MfDesfireKeyVersion* data, const BitBuffer* buf); + +bool mf_desfire_application_id_parse( + MfDesfireApplicationId* data, + uint32_t index, + const BitBuffer* buf); + +bool mf_desfire_file_id_parse(MfDesfireFileId* data, uint32_t index, const BitBuffer* buf); + +bool mf_desfire_file_settings_parse(MfDesfireFileSettings* data, const BitBuffer* buf); + +bool mf_desfire_file_data_parse(MfDesfireFileData* data, const BitBuffer* buf); + +// Init internal MfDesfire structures + +void mf_desfire_file_data_init(MfDesfireFileData* data); + +void mf_desfire_application_init(MfDesfireApplication* data); + +// Reset internal MfDesfire structures + +void mf_desfire_file_data_reset(MfDesfireFileData* data); + +void mf_desfire_application_reset(MfDesfireApplication* data); + +// Copy internal MfDesfire structures + +void mf_desfire_file_data_copy(MfDesfireFileData* data, const MfDesfireFileData* other); + +void mf_desfire_application_copy(MfDesfireApplication* data, const MfDesfireApplication* other); + +// Load internal MfDesfire structures + +bool mf_desfire_version_load(MfDesfireVersion* data, FlipperFormat* ff); + +bool mf_desfire_free_memory_load(MfDesfireFreeMemory* data, FlipperFormat* ff); + +bool mf_desfire_key_settings_load( + MfDesfireKeySettings* data, + const char* prefix, + FlipperFormat* ff); + +bool mf_desfire_key_version_load( + MfDesfireKeyVersion* data, + const char* prefix, + uint32_t index, + FlipperFormat* ff); + +bool mf_desfire_file_count_load(uint32_t* data, const char* prefix, FlipperFormat* ff); + +bool mf_desfire_file_ids_load( + MfDesfireFileId* data, + uint32_t count, + const char* prefix, + FlipperFormat* ff); + +bool mf_desfire_file_settings_load( + MfDesfireFileSettings* data, + const char* prefix, + FlipperFormat* ff); + +bool mf_desfire_file_data_load(MfDesfireFileData* data, const char* prefix, FlipperFormat* ff); + +bool mf_desfire_application_count_load(uint32_t* data, FlipperFormat* ff); + +bool mf_desfire_application_ids_load( + MfDesfireApplicationId* data, + uint32_t count, + FlipperFormat* ff); + +bool mf_desfire_application_load(MfDesfireApplication* data, const char* prefix, FlipperFormat* ff); + +// Save internal MFDesfire structures + +bool mf_desfire_version_save(const MfDesfireVersion* data, FlipperFormat* ff); + +bool mf_desfire_free_memory_save(const MfDesfireFreeMemory* data, FlipperFormat* ff); + +bool mf_desfire_key_settings_save( + const MfDesfireKeySettings* data, + const char* prefix, + FlipperFormat* ff); + +bool mf_desfire_key_version_save( + const MfDesfireKeyVersion* data, + const char* prefix, + uint32_t index, + FlipperFormat* ff); + +bool mf_desfire_file_ids_save( + const MfDesfireFileId* data, + uint32_t count, + const char* prefix, + FlipperFormat* ff); + +bool mf_desfire_file_settings_save( + const MfDesfireFileSettings* data, + const char* prefix, + FlipperFormat* ff); + +bool mf_desfire_file_data_save( + const MfDesfireFileData* data, + const char* prefix, + FlipperFormat* ff); + +bool mf_desfire_application_count_save(const uint32_t* data, FlipperFormat* ff); + +bool mf_desfire_application_ids_save( + const MfDesfireApplicationId* data, + uint32_t count, + FlipperFormat* ff); + +bool mf_desfire_application_save( + const MfDesfireApplication* data, + const char* prefix, + FlipperFormat* ff); diff --git a/lib/nfc/protocols/mf_desfire/mf_desfire_poller.c b/lib/nfc/protocols/mf_desfire/mf_desfire_poller.c new file mode 100644 index 000000000..11db021d5 --- /dev/null +++ b/lib/nfc/protocols/mf_desfire/mf_desfire_poller.c @@ -0,0 +1,244 @@ +#include "mf_desfire_poller_i.h" + +#include + +#include + +#define TAG "MfDesfirePoller" + +#define MF_DESFIRE_BUF_SIZE (64U) +#define MF_DESFIRE_RESULT_BUF_SIZE (512U) + +typedef NfcCommand (*MfDesfirePollerReadHandler)(MfDesfirePoller* instance); + +const MfDesfireData* mf_desfire_poller_get_data(MfDesfirePoller* instance) { + furi_assert(instance); + + return instance->data; +} + +static MfDesfirePoller* mf_desfire_poller_alloc(Iso14443_4aPoller* iso14443_4a_poller) { + MfDesfirePoller* instance = malloc(sizeof(MfDesfirePoller)); + instance->iso14443_4a_poller = iso14443_4a_poller; + instance->data = mf_desfire_alloc(); + instance->tx_buffer = bit_buffer_alloc(MF_DESFIRE_BUF_SIZE); + instance->rx_buffer = bit_buffer_alloc(MF_DESFIRE_BUF_SIZE); + instance->input_buffer = bit_buffer_alloc(MF_DESFIRE_BUF_SIZE); + instance->result_buffer = bit_buffer_alloc(MF_DESFIRE_RESULT_BUF_SIZE); + + instance->mf_desfire_event.data = &instance->mf_desfire_event_data; + + instance->general_event.protocol = NfcProtocolMfDesfire; + instance->general_event.event_data = &instance->mf_desfire_event; + instance->general_event.instance = instance; + + return instance; +} + +static void mf_desfire_poller_free(MfDesfirePoller* instance) { + furi_assert(instance); + + mf_desfire_free(instance->data); + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + bit_buffer_free(instance->input_buffer); + bit_buffer_free(instance->result_buffer); + free(instance); +} + +static NfcCommand mf_desfire_poller_handler_idle(MfDesfirePoller* instance) { + bit_buffer_reset(instance->input_buffer); + bit_buffer_reset(instance->result_buffer); + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + iso14443_4a_copy( + instance->data->iso14443_4a_data, + iso14443_4a_poller_get_data(instance->iso14443_4a_poller)); + + instance->state = MfDesfirePollerStateReadVersion; + return NfcCommandContinue; +} + +static NfcCommand mf_desfire_poller_handler_read_version(MfDesfirePoller* instance) { + instance->error = mf_desfire_poller_async_read_version(instance, &instance->data->version); + if(instance->error == MfDesfireErrorNone) { + FURI_LOG_D(TAG, "Read version success"); + instance->state = MfDesfirePollerStateReadFreeMemory; + } else { + FURI_LOG_E(TAG, "Failed to read version"); + iso14443_4a_poller_halt(instance->iso14443_4a_poller); + instance->state = MfDesfirePollerStateReadFailed; + } + + return NfcCommandContinue; +} + +static NfcCommand mf_desfire_poller_handler_read_free_memory(MfDesfirePoller* instance) { + instance->error = + mf_desfire_poller_async_read_free_memory(instance, &instance->data->free_memory); + if(instance->error == MfDesfireErrorNone) { + FURI_LOG_D(TAG, "Read free memory success"); + instance->state = MfDesfirePollerStateReadMasterKeySettings; + } else { + FURI_LOG_E(TAG, "Failed to read free memory"); + iso14443_4a_poller_halt(instance->iso14443_4a_poller); + instance->state = MfDesfirePollerStateReadFailed; + } + + return NfcCommandContinue; +} + +static NfcCommand mf_desfire_poller_handler_read_master_key_settings(MfDesfirePoller* instance) { + instance->error = + mf_desfire_poller_async_read_key_settings(instance, &instance->data->master_key_settings); + if(instance->error == MfDesfireErrorNone) { + FURI_LOG_D(TAG, "Read master key settings success"); + instance->state = MfDesfirePollerStateReadMasterKeyVersion; + } else { + FURI_LOG_E(TAG, "Failed to read master key settings"); + iso14443_4a_poller_halt(instance->iso14443_4a_poller); + instance->state = MfDesfirePollerStateReadFailed; + } + + return NfcCommandContinue; +} + +static NfcCommand mf_desfire_poller_handler_read_master_key_version(MfDesfirePoller* instance) { + instance->error = mf_desfire_poller_async_read_key_versions( + instance, + instance->data->master_key_versions, + instance->data->master_key_settings.max_keys); + if(instance->error == MfDesfireErrorNone) { + FURI_LOG_D(TAG, "Read master key version success"); + instance->state = MfDesfirePollerStateReadApplicationIds; + } else { + FURI_LOG_E(TAG, "Failed to read master key version"); + iso14443_4a_poller_halt(instance->iso14443_4a_poller); + instance->state = MfDesfirePollerStateReadFailed; + } + + return NfcCommandContinue; +} + +static NfcCommand mf_desfire_poller_handler_read_application_ids(MfDesfirePoller* instance) { + instance->error = + mf_desfire_poller_async_read_application_ids(instance, instance->data->application_ids); + if(instance->error == MfDesfireErrorNone) { + FURI_LOG_D(TAG, "Read application ids success"); + instance->state = MfDesfirePollerStateReadApplications; + } else { + FURI_LOG_E(TAG, "Failed to read application ids"); + iso14443_4a_poller_halt(instance->iso14443_4a_poller); + instance->state = MfDesfirePollerStateReadFailed; + } + + return NfcCommandContinue; +} + +static NfcCommand mf_desfire_poller_handler_read_applications(MfDesfirePoller* instance) { + instance->error = mf_desfire_poller_async_read_applications( + instance, instance->data->application_ids, instance->data->applications); + if(instance->error == MfDesfireErrorNone) { + FURI_LOG_D(TAG, "Read applications success"); + instance->state = MfDesfirePollerStateReadSuccess; + } else { + FURI_LOG_E(TAG, "Failed to read applications"); + iso14443_4a_poller_halt(instance->iso14443_4a_poller); + instance->state = MfDesfirePollerStateReadFailed; + } + + return NfcCommandContinue; +} + +static NfcCommand mf_desfire_poller_handler_read_fail(MfDesfirePoller* instance) { + FURI_LOG_D(TAG, "Read Failed"); + iso14443_4a_poller_halt(instance->iso14443_4a_poller); + instance->mf_desfire_event.data->error = instance->error; + NfcCommand command = instance->callback(instance->general_event, instance->context); + instance->state = MfDesfirePollerStateIdle; + return command; +} + +static NfcCommand mf_desfire_poller_handler_read_success(MfDesfirePoller* instance) { + FURI_LOG_D(TAG, "Read success."); + iso14443_4a_poller_halt(instance->iso14443_4a_poller); + instance->mf_desfire_event.type = MfDesfirePollerEventTypeReadSuccess; + NfcCommand command = instance->callback(instance->general_event, instance->context); + return command; +} + +static const MfDesfirePollerReadHandler mf_desfire_poller_read_handler[MfDesfirePollerStateNum] = { + [MfDesfirePollerStateIdle] = mf_desfire_poller_handler_idle, + [MfDesfirePollerStateReadVersion] = mf_desfire_poller_handler_read_version, + [MfDesfirePollerStateReadFreeMemory] = mf_desfire_poller_handler_read_free_memory, + [MfDesfirePollerStateReadMasterKeySettings] = + mf_desfire_poller_handler_read_master_key_settings, + [MfDesfirePollerStateReadMasterKeyVersion] = mf_desfire_poller_handler_read_master_key_version, + [MfDesfirePollerStateReadApplicationIds] = mf_desfire_poller_handler_read_application_ids, + [MfDesfirePollerStateReadApplications] = mf_desfire_poller_handler_read_applications, + [MfDesfirePollerStateReadFailed] = mf_desfire_poller_handler_read_fail, + [MfDesfirePollerStateReadSuccess] = mf_desfire_poller_handler_read_success, +}; + +static void mf_desfire_poller_set_callback( + MfDesfirePoller* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +static NfcCommand mf_desfire_poller_run(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_4a); + + MfDesfirePoller* instance = context; + furi_assert(instance); + furi_assert(instance->callback); + + const Iso14443_4aPollerEvent* iso14443_4a_event = event.event_data; + furi_assert(iso14443_4a_event); + + NfcCommand command = NfcCommandContinue; + + if(iso14443_4a_event->type == Iso14443_4aPollerEventTypeReady) { + command = mf_desfire_poller_read_handler[instance->state](instance); + } else if(iso14443_4a_event->type == Iso14443_4aPollerEventTypeError) { + instance->mf_desfire_event.type = MfDesfirePollerEventTypeReadFailed; + command = instance->callback(instance->general_event, instance->context); + } + + return command; +} + +static bool mf_desfire_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso14443_4a); + + MfDesfirePoller* instance = context; + furi_assert(instance); + + const Iso14443_4aPollerEvent* iso14443_4a_event = event.event_data; + furi_assert(iso14443_4a_event); + + bool protocol_detected = false; + + if(iso14443_4a_event->type == Iso14443_4aPollerEventTypeReady) { + MfDesfireVersion version = {}; + const MfDesfireError error = mf_desfire_poller_async_read_version(instance, &version); + protocol_detected = (error == MfDesfireErrorNone); + } + + return protocol_detected; +} + +const NfcPollerBase mf_desfire_poller = { + .alloc = (NfcPollerAlloc)mf_desfire_poller_alloc, + .free = (NfcPollerFree)mf_desfire_poller_free, + .set_callback = (NfcPollerSetCallback)mf_desfire_poller_set_callback, + .run = (NfcPollerRun)mf_desfire_poller_run, + .detect = (NfcPollerDetect)mf_desfire_poller_detect, + .get_data = (NfcPollerGetData)mf_desfire_poller_get_data, +}; diff --git a/lib/nfc/protocols/mf_desfire/mf_desfire_poller.h b/lib/nfc/protocols/mf_desfire/mf_desfire_poller.h new file mode 100644 index 000000000..360b0508f --- /dev/null +++ b/lib/nfc/protocols/mf_desfire/mf_desfire_poller.h @@ -0,0 +1,31 @@ +#pragma once + +#include "mf_desfire.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct MfDesfirePoller MfDesfirePoller; + +typedef enum { + MfDesfirePollerEventTypeReadSuccess, + MfDesfirePollerEventTypeReadFailed, +} MfDesfirePollerEventType; + +typedef struct { + union { + MfDesfireError error; + }; +} MfDesfirePollerEventData; + +typedef struct { + MfDesfirePollerEventType type; + MfDesfirePollerEventData* data; +} MfDesfirePollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_desfire/mf_desfire_poller_defs.h b/lib/nfc/protocols/mf_desfire/mf_desfire_poller_defs.h new file mode 100644 index 000000000..0c14ceee4 --- /dev/null +++ b/lib/nfc/protocols/mf_desfire/mf_desfire_poller_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcPollerBase mf_desfire_poller; diff --git a/lib/nfc/protocols/mf_desfire/mf_desfire_poller_i.c b/lib/nfc/protocols/mf_desfire/mf_desfire_poller_i.c new file mode 100644 index 000000000..38ae2f466 --- /dev/null +++ b/lib/nfc/protocols/mf_desfire/mf_desfire_poller_i.c @@ -0,0 +1,482 @@ +#include "mf_desfire_poller_i.h" + +#include + +#include "mf_desfire_i.h" + +#define TAG "MfDesfirePoller" + +MfDesfireError mf_desfire_process_error(Iso14443_4aError error) { + switch(error) { + case Iso14443_4aErrorNone: + return MfDesfireErrorNone; + case Iso14443_4aErrorNotPresent: + return MfDesfireErrorNotPresent; + case Iso14443_4aErrorTimeout: + return MfDesfireErrorTimeout; + default: + return MfDesfireErrorProtocol; + } +} + +MfDesfireError mf_desfire_send_chunks( + MfDesfirePoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer) { + furi_assert(instance); + furi_assert(instance->iso14443_4a_poller); + furi_assert(instance->tx_buffer); + furi_assert(instance->rx_buffer); + furi_assert(tx_buffer); + furi_assert(rx_buffer); + + MfDesfireError error = MfDesfireErrorNone; + + do { + Iso14443_4aError iso14443_4a_error = iso14443_4a_poller_send_block( + instance->iso14443_4a_poller, tx_buffer, instance->rx_buffer); + + if(iso14443_4a_error != Iso14443_4aErrorNone) { + error = mf_desfire_process_error(iso14443_4a_error); + break; + } + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_append_byte(instance->tx_buffer, MF_DESFIRE_FLAG_HAS_NEXT); + + if(bit_buffer_get_size_bytes(instance->rx_buffer) > sizeof(uint8_t)) { + bit_buffer_copy_right(rx_buffer, instance->rx_buffer, sizeof(uint8_t)); + } else { + bit_buffer_reset(rx_buffer); + } + + while(bit_buffer_starts_with_byte(instance->rx_buffer, MF_DESFIRE_FLAG_HAS_NEXT)) { + Iso14443_4aError iso14443_4a_error = iso14443_4a_poller_send_block( + instance->iso14443_4a_poller, instance->tx_buffer, instance->rx_buffer); + + if(iso14443_4a_error != Iso14443_4aErrorNone) { + error = mf_desfire_process_error(iso14443_4a_error); + break; + } + + const size_t rx_size = bit_buffer_get_size_bytes(instance->rx_buffer); + const size_t rx_capacity_remaining = + bit_buffer_get_capacity_bytes(rx_buffer) - bit_buffer_get_size_bytes(rx_buffer); + + if(rx_size <= rx_capacity_remaining) { + bit_buffer_append_right(rx_buffer, instance->rx_buffer, sizeof(uint8_t)); + } else { + FURI_LOG_W(TAG, "RX buffer overflow: ignoring %zu bytes", rx_size); + } + } + } while(false); + + return error; +} + +MfDesfireError + mf_desfire_poller_async_read_version(MfDesfirePoller* instance, MfDesfireVersion* data) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_GET_VERSION); + + MfDesfireError error; + + do { + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + if(!mf_desfire_version_parse(data, instance->result_buffer)) { + error = MfDesfireErrorProtocol; + } + } while(false); + + return error; +} + +MfDesfireError + mf_desfire_poller_async_read_free_memory(MfDesfirePoller* instance, MfDesfireFreeMemory* data) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_GET_FREE_MEMORY); + + MfDesfireError error; + + do { + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + if(!mf_desfire_free_memory_parse(data, instance->result_buffer)) { + error = MfDesfireErrorProtocol; + } + } while(false); + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_key_settings( + MfDesfirePoller* instance, + MfDesfireKeySettings* data) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_GET_KEY_SETTINGS); + + MfDesfireError error; + + do { + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + if(!mf_desfire_key_settings_parse(data, instance->result_buffer)) { + error = MfDesfireErrorProtocol; + } + } while(false); + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_key_versions( + MfDesfirePoller* instance, + SimpleArray* data, + uint32_t count) { + furi_assert(instance); + furi_assert(count > 0); + + simple_array_init(data, count); + + bit_buffer_set_size_bytes(instance->input_buffer, sizeof(uint8_t) * 2); + bit_buffer_set_byte(instance->input_buffer, 0, MF_DESFIRE_CMD_GET_KEY_VERSION); + + MfDesfireError error = MfDesfireErrorNone; + + for(uint32_t i = 0; i < count; ++i) { + bit_buffer_set_byte(instance->input_buffer, 1, i); + + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + if(!mf_desfire_key_version_parse(simple_array_get(data, i), instance->result_buffer)) { + error = MfDesfireErrorProtocol; + break; + } + } + + return error; +} + +MfDesfireError + mf_desfire_poller_async_read_application_ids(MfDesfirePoller* instance, SimpleArray* data) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_GET_APPLICATION_IDS); + + MfDesfireError error; + + do { + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + const uint32_t app_id_count = + bit_buffer_get_size_bytes(instance->result_buffer) / sizeof(MfDesfireApplicationId); + if(app_id_count == 0) break; + + simple_array_init(data, app_id_count); + + for(uint32_t i = 0; i < app_id_count; ++i) { + if(!mf_desfire_application_id_parse( + simple_array_get(data, i), i, instance->result_buffer)) { + error = MfDesfireErrorProtocol; + break; + } + } + } while(false); + + return error; +} + +MfDesfireError mf_desfire_poller_async_select_application( + MfDesfirePoller* instance, + const MfDesfireApplicationId* id) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_SELECT_APPLICATION); + bit_buffer_append_bytes( + instance->input_buffer, (const uint8_t*)id, sizeof(MfDesfireApplicationId)); + + MfDesfireError error = + mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + return error; +} + +MfDesfireError + mf_desfire_poller_async_read_file_ids(MfDesfirePoller* instance, SimpleArray* data) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_GET_FILE_IDS); + + MfDesfireError error; + + do { + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + const uint32_t id_count = + bit_buffer_get_size_bytes(instance->result_buffer) / sizeof(MfDesfireFileId); + + if(id_count == 0) break; + simple_array_init(data, id_count); + + for(uint32_t i = 0; i < id_count; ++i) { + if(!mf_desfire_file_id_parse(simple_array_get(data, i), i, instance->result_buffer)) { + error = MfDesfireErrorProtocol; + break; + } + } + } while(false); + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_file_settings( + MfDesfirePoller* instance, + MfDesfireFileId id, + MfDesfireFileSettings* data) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_GET_FILE_SETTINGS); + bit_buffer_append_byte(instance->input_buffer, id); + + MfDesfireError error; + + do { + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + if(!mf_desfire_file_settings_parse(data, instance->result_buffer)) { + error = MfDesfireErrorProtocol; + } + } while(false); + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_file_settings_multi( + MfDesfirePoller* instance, + const SimpleArray* file_ids, + SimpleArray* data) { + furi_assert(instance); + + MfDesfireError error = MfDesfireErrorNone; + + const uint32_t file_id_count = simple_array_get_count(file_ids); + if(file_id_count > 0) { + simple_array_init(data, file_id_count); + } + + for(uint32_t i = 0; i < file_id_count; ++i) { + const MfDesfireFileId file_id = *(const MfDesfireFileId*)simple_array_cget(file_ids, i); + error = mf_desfire_poller_async_read_file_settings( + instance, file_id, simple_array_get(data, i)); + if(error != MfDesfireErrorNone) break; + } + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_file_data( + MfDesfirePoller* instance, + MfDesfireFileId id, + uint32_t offset, + size_t size, + MfDesfireFileData* data) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_READ_DATA); + bit_buffer_append_byte(instance->input_buffer, id); + bit_buffer_append_bytes(instance->input_buffer, (const uint8_t*)&offset, 3); + bit_buffer_append_bytes(instance->input_buffer, (const uint8_t*)&size, 3); + + MfDesfireError error; + + do { + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + if(!mf_desfire_file_data_parse(data, instance->result_buffer)) { + error = MfDesfireErrorProtocol; + } + } while(false); + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_file_value( + MfDesfirePoller* instance, + MfDesfireFileId id, + MfDesfireFileData* data) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_GET_VALUE); + bit_buffer_append_byte(instance->input_buffer, id); + + MfDesfireError error; + + do { + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + if(!mf_desfire_file_data_parse(data, instance->result_buffer)) { + error = MfDesfireErrorProtocol; + } + } while(false); + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_file_records( + MfDesfirePoller* instance, + MfDesfireFileId id, + uint32_t offset, + size_t size, + MfDesfireFileData* data) { + furi_assert(instance); + + bit_buffer_reset(instance->input_buffer); + bit_buffer_append_byte(instance->input_buffer, MF_DESFIRE_CMD_READ_RECORDS); + bit_buffer_append_byte(instance->input_buffer, id); + bit_buffer_append_bytes(instance->input_buffer, (const uint8_t*)&offset, 3); + bit_buffer_append_bytes(instance->input_buffer, (const uint8_t*)&size, 3); + + MfDesfireError error; + + do { + error = mf_desfire_send_chunks(instance, instance->input_buffer, instance->result_buffer); + + if(error != MfDesfireErrorNone) break; + + if(!mf_desfire_file_data_parse(data, instance->result_buffer)) { + error = MfDesfireErrorProtocol; + } + } while(false); + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_file_data_multi( + MfDesfirePoller* instance, + const SimpleArray* file_ids, + const SimpleArray* file_settings, + SimpleArray* data) { + furi_assert(instance); + furi_assert(simple_array_get_count(file_ids) == simple_array_get_count(file_settings)); + + MfDesfireError error = MfDesfireErrorNone; + + const uint32_t file_id_count = simple_array_get_count(file_ids); + if(file_id_count > 0) { + simple_array_init(data, file_id_count); + } + + for(uint32_t i = 0; i < file_id_count; ++i) { + const MfDesfireFileId file_id = *(const MfDesfireFileId*)simple_array_cget(file_ids, i); + const MfDesfireFileSettings* file_settings_cur = simple_array_cget(file_settings, i); + const MfDesfireFileType file_type = file_settings_cur->type; + + MfDesfireFileData* file_data = simple_array_get(data, i); + + if(file_type == MfDesfireFileTypeStandard || file_type == MfDesfireFileTypeBackup) { + error = mf_desfire_poller_async_read_file_data( + instance, file_id, 0, file_settings_cur->data.size, file_data); + } else if(file_type == MfDesfireFileTypeValue) { + error = mf_desfire_poller_async_read_file_value(instance, file_id, file_data); + } else if( + file_type == MfDesfireFileTypeLinearRecord || + file_type == MfDesfireFileTypeCyclicRecord) { + error = mf_desfire_poller_async_read_file_records( + instance, file_id, 0, file_settings_cur->data.size, file_data); + } + + if(error != MfDesfireErrorNone) break; + } + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_application( + MfDesfirePoller* instance, + MfDesfireApplication* data) { + furi_assert(instance); + furi_assert(data); + + MfDesfireError error; + + do { + error = mf_desfire_poller_async_read_key_settings(instance, &data->key_settings); + if(error != MfDesfireErrorNone) break; + + error = mf_desfire_poller_async_read_key_versions( + instance, data->key_versions, data->key_settings.max_keys); + if(error != MfDesfireErrorNone) break; + + error = mf_desfire_poller_async_read_file_ids(instance, data->file_ids); + if(error != MfDesfireErrorNone) break; + + error = mf_desfire_poller_async_read_file_settings_multi( + instance, data->file_ids, data->file_settings); + if(error != MfDesfireErrorNone) break; + + error = mf_desfire_poller_async_read_file_data_multi( + instance, data->file_ids, data->file_settings, data->file_data); + if(error != MfDesfireErrorNone) break; + + } while(false); + + return error; +} + +MfDesfireError mf_desfire_poller_async_read_applications( + MfDesfirePoller* instance, + const SimpleArray* app_ids, + SimpleArray* data) { + furi_assert(instance); + + MfDesfireError error = MfDesfireErrorNone; + + const uint32_t app_id_count = simple_array_get_count(app_ids); + if(app_id_count > 0) { + simple_array_init(data, app_id_count); + } + + for(uint32_t i = 0; i < app_id_count; ++i) { + do { + error = mf_desfire_poller_async_select_application( + instance, simple_array_cget(app_ids, i)); + if(error != MfDesfireErrorNone) break; + + MfDesfireApplication* current_app = simple_array_get(data, i); + error = mf_desfire_poller_async_read_application(instance, current_app); + + } while(false); + } + + return error; +} diff --git a/lib/nfc/protocols/mf_desfire/mf_desfire_poller_i.h b/lib/nfc/protocols/mf_desfire/mf_desfire_poller_i.h new file mode 100644 index 000000000..abc48d0eb --- /dev/null +++ b/lib/nfc/protocols/mf_desfire/mf_desfire_poller_i.h @@ -0,0 +1,126 @@ +#pragma once + +#include "mf_desfire_poller.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + MfDesfirePollerStateIdle, + MfDesfirePollerStateReadVersion, + MfDesfirePollerStateReadFreeMemory, + MfDesfirePollerStateReadMasterKeySettings, + MfDesfirePollerStateReadMasterKeyVersion, + MfDesfirePollerStateReadApplicationIds, + MfDesfirePollerStateReadApplications, + MfDesfirePollerStateReadFailed, + MfDesfirePollerStateReadSuccess, + + MfDesfirePollerStateNum, +} MfDesfirePollerState; + +typedef enum { + MfDesfirePollerSessionStateIdle, + MfDesfirePollerSessionStateActive, + MfDesfirePollerSessionStateStopRequest, +} MfDesfirePollerSessionState; + +struct MfDesfirePoller { + Iso14443_4aPoller* iso14443_4a_poller; + MfDesfirePollerSessionState session_state; + MfDesfirePollerState state; + MfDesfireError error; + MfDesfireData* data; + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + BitBuffer* input_buffer; + BitBuffer* result_buffer; + MfDesfirePollerEventData mf_desfire_event_data; + MfDesfirePollerEvent mf_desfire_event; + NfcGenericEvent general_event; + NfcGenericCallback callback; + void* context; +}; + +MfDesfireError mf_desfire_process_error(Iso14443_4aError error); + +const MfDesfireData* mf_desfire_poller_get_data(MfDesfirePoller* instance); + +MfDesfireError mf_desfire_send_chunks( + MfDesfirePoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer); + +MfDesfireError + mf_desfire_poller_async_read_version(MfDesfirePoller* instance, MfDesfireVersion* data); + +MfDesfireError + mf_desfire_poller_async_read_free_memory(MfDesfirePoller* instance, MfDesfireFreeMemory* data); + +MfDesfireError mf_desfire_poller_async_read_key_settings( + MfDesfirePoller* instance, + MfDesfireKeySettings* data); + +MfDesfireError mf_desfire_poller_async_read_key_versions( + MfDesfirePoller* instance, + SimpleArray* data, + uint32_t count); + +MfDesfireError + mf_desfire_poller_async_read_application_ids(MfDesfirePoller* instance, SimpleArray* data); + +MfDesfireError mf_desfire_poller_async_select_application( + MfDesfirePoller* instance, + const MfDesfireApplicationId* id); + +MfDesfireError mf_desfire_poller_async_read_file_ids(MfDesfirePoller* instance, SimpleArray* data); + +MfDesfireError mf_desfire_poller_async_read_file_settings( + MfDesfirePoller* instance, + MfDesfireFileId id, + MfDesfireFileSettings* data); + +MfDesfireError mf_desfire_poller_async_read_file_settings_multi( + MfDesfirePoller* instance, + const SimpleArray* file_ids, + SimpleArray* data); + +MfDesfireError mf_desfire_poller_async_read_file_data( + MfDesfirePoller* instance, + MfDesfireFileId id, + uint32_t offset, + size_t size, + MfDesfireFileData* data); + +MfDesfireError mf_desfire_poller_async_read_file_value( + MfDesfirePoller* instance, + MfDesfireFileId id, + MfDesfireFileData* data); + +MfDesfireError mf_desfire_poller_async_read_file_records( + MfDesfirePoller* instance, + MfDesfireFileId id, + uint32_t offset, + size_t size, + MfDesfireFileData* data); + +MfDesfireError mf_desfire_poller_async_read_file_data_multi( + MfDesfirePoller* instance, + const SimpleArray* file_ids, + const SimpleArray* file_settings, + SimpleArray* data); + +MfDesfireError + mf_desfire_poller_async_read_application(MfDesfirePoller* instance, MfDesfireApplication* data); + +MfDesfireError mf_desfire_poller_async_read_applications( + MfDesfirePoller* instance, + const SimpleArray* app_ids, + SimpleArray* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight.c b/lib/nfc/protocols/mf_ultralight/mf_ultralight.c new file mode 100644 index 000000000..fd845f3c0 --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight.c @@ -0,0 +1,627 @@ +#include "mf_ultralight.h" + +#include +#include + +#define MF_ULTRALIGHT_PROTOCOL_NAME "NTAG/Ultralight" + +#define MF_ULTRALIGHT_FORMAT_VERSION_KEY "Data format version" +#define MF_ULTRALIGHT_TYPE_KEY MF_ULTRALIGHT_PROTOCOL_NAME " type" +#define MF_ULTRALIGHT_SIGNATURE_KEY "Signature" +#define MF_ULTRALIGHT_MIFARE_VERSION_KEY "Mifare version" +#define MF_ULTRALIGHT_COUNTER_KEY "Counter" +#define MF_ULTRALIGHT_TEARING_KEY "Tearing" +#define MF_ULTRALIGHT_PAGES_TOTAL_KEY "Pages total" +#define MF_ULTRALIGHT_PAGES_READ_KEY "Pages read" +#define MF_ULTRALIGHT_PAGE_KEY "Page" +#define MF_ULTRALIGHT_FAILED_ATTEMPTS_KEY "Failed authentication attempts" + +typedef struct { + const char* device_name; + uint16_t total_pages; + uint16_t config_page; + uint32_t feature_set; +} MfUltralightFeatures; + +static const uint32_t mf_ultralight_data_format_version = 2; + +static const MfUltralightFeatures mf_ultralight_features[MfUltralightTypeNum] = { + [MfUltralightTypeUnknown] = + { + .device_name = "Mifare Ultralight", + .total_pages = 16, + .config_page = 0, + .feature_set = MfUltralightFeatureSupportCompatibleWrite, + }, + [MfUltralightTypeMfulC] = + { + .device_name = "Mifare Ultralight C", + .total_pages = 48, + .config_page = 0, + .feature_set = MfUltralightFeatureSupportCompatibleWrite | + MfUltralightFeatureSupportAuthenticate, + }, + [MfUltralightTypeNTAG203] = + { + .device_name = "NTAG203", + .total_pages = 42, + .config_page = 0, + .feature_set = MfUltralightFeatureSupportCompatibleWrite | + MfUltralightFeatureSupportCounterInMemory, + }, + [MfUltralightTypeUL11] = + { + .device_name = "Mifare Ultralight 11", + .total_pages = 20, + .config_page = 16, + .feature_set = + MfUltralightFeatureSupportReadVersion | MfUltralightFeatureSupportReadSignature | + MfUltralightFeatureSupportReadCounter | + MfUltralightFeatureSupportCheckTearingFlag | MfUltralightFeatureSupportFastRead | + MfUltralightFeatureSupportIncCounter | MfUltralightFeatureSupportCompatibleWrite | + MfUltralightFeatureSupportPasswordAuth | MfUltralightFeatureSupportVcsl, + }, + [MfUltralightTypeUL21] = + { + .device_name = "Mifare Ultralight 21", + .total_pages = 41, + .config_page = 37, + .feature_set = + MfUltralightFeatureSupportReadVersion | MfUltralightFeatureSupportReadSignature | + MfUltralightFeatureSupportReadCounter | + MfUltralightFeatureSupportCheckTearingFlag | MfUltralightFeatureSupportFastRead | + MfUltralightFeatureSupportIncCounter | MfUltralightFeatureSupportCompatibleWrite | + MfUltralightFeatureSupportPasswordAuth | MfUltralightFeatureSupportVcsl | + MfUltralightFeatureSupportDynamicLock, + }, + [MfUltralightTypeNTAG213] = + { + .device_name = "NTAG213", + .total_pages = 45, + .config_page = 41, + .feature_set = + MfUltralightFeatureSupportReadVersion | MfUltralightFeatureSupportReadSignature | + MfUltralightFeatureSupportReadCounter | MfUltralightFeatureSupportFastRead | + MfUltralightFeatureSupportCompatibleWrite | + MfUltralightFeatureSupportPasswordAuth | MfUltralightFeatureSupportSingleCounter | + MfUltralightFeatureSupportAsciiMirror | MfUltralightFeatureSupportDynamicLock, + }, + [MfUltralightTypeNTAG215] = + { + .device_name = "NTAG215", + .total_pages = 135, + .config_page = 131, + .feature_set = + MfUltralightFeatureSupportReadVersion | MfUltralightFeatureSupportReadSignature | + MfUltralightFeatureSupportReadCounter | MfUltralightFeatureSupportFastRead | + MfUltralightFeatureSupportCompatibleWrite | + MfUltralightFeatureSupportPasswordAuth | MfUltralightFeatureSupportSingleCounter | + MfUltralightFeatureSupportAsciiMirror | MfUltralightFeatureSupportDynamicLock, + }, + [MfUltralightTypeNTAG216] = + { + .device_name = "NTAG216", + .total_pages = 231, + .config_page = 227, + .feature_set = + MfUltralightFeatureSupportReadVersion | MfUltralightFeatureSupportReadSignature | + MfUltralightFeatureSupportReadCounter | MfUltralightFeatureSupportFastRead | + MfUltralightFeatureSupportCompatibleWrite | + MfUltralightFeatureSupportPasswordAuth | MfUltralightFeatureSupportSingleCounter | + MfUltralightFeatureSupportAsciiMirror | MfUltralightFeatureSupportDynamicLock, + }, + [MfUltralightTypeNTAGI2C1K] = + { + .device_name = "NTAG I2C 1K", + .total_pages = 231, + .config_page = 0, + .feature_set = + MfUltralightFeatureSupportReadVersion | MfUltralightFeatureSupportFastRead | + MfUltralightFeatureSupportSectorSelect | MfUltralightFeatureSupportDynamicLock, + }, + [MfUltralightTypeNTAGI2C2K] = + { + .device_name = "NTAG I2C 2K", + .total_pages = 485, + .config_page = 0, + .feature_set = + MfUltralightFeatureSupportReadVersion | MfUltralightFeatureSupportFastRead | + MfUltralightFeatureSupportSectorSelect | MfUltralightFeatureSupportDynamicLock, + }, + [MfUltralightTypeNTAGI2CPlus1K] = + { + .device_name = "NTAG I2C Plus 1K", + .total_pages = 236, + .config_page = 227, + .feature_set = + MfUltralightFeatureSupportReadVersion | MfUltralightFeatureSupportReadSignature | + MfUltralightFeatureSupportFastRead | MfUltralightFeatureSupportPasswordAuth | + MfUltralightFeatureSupportSectorSelect | MfUltralightFeatureSupportFastWrite | + MfUltralightFeatureSupportDynamicLock, + }, + [MfUltralightTypeNTAGI2CPlus2K] = + { + .device_name = "NTAG I2C Plus 2K", + .total_pages = 492, + .config_page = 227, + .feature_set = + MfUltralightFeatureSupportReadVersion | MfUltralightFeatureSupportReadSignature | + MfUltralightFeatureSupportFastRead | MfUltralightFeatureSupportPasswordAuth | + MfUltralightFeatureSupportSectorSelect | MfUltralightFeatureSupportFastWrite | + MfUltralightFeatureSupportDynamicLock, + }, +}; + +const NfcDeviceBase nfc_device_mf_ultralight = { + .protocol_name = MF_ULTRALIGHT_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)mf_ultralight_alloc, + .free = (NfcDeviceFree)mf_ultralight_free, + .reset = (NfcDeviceReset)mf_ultralight_reset, + .copy = (NfcDeviceCopy)mf_ultralight_copy, + .verify = (NfcDeviceVerify)mf_ultralight_verify, + .load = (NfcDeviceLoad)mf_ultralight_load, + .save = (NfcDeviceSave)mf_ultralight_save, + .is_equal = (NfcDeviceEqual)mf_ultralight_is_equal, + .get_name = (NfcDeviceGetName)mf_ultralight_get_device_name, + .get_uid = (NfcDeviceGetUid)mf_ultralight_get_uid, + .set_uid = (NfcDeviceSetUid)mf_ultralight_set_uid, + .get_base_data = (NfcDeviceGetBaseData)mf_ultralight_get_base_data, +}; + +MfUltralightData* mf_ultralight_alloc() { + MfUltralightData* data = malloc(sizeof(MfUltralightData)); + data->iso14443_3a_data = iso14443_3a_alloc(); + return data; +} + +void mf_ultralight_free(MfUltralightData* data) { + furi_assert(data); + + iso14443_3a_free(data->iso14443_3a_data); + free(data); +} + +void mf_ultralight_reset(MfUltralightData* data) { + furi_assert(data); + + iso14443_3a_reset(data->iso14443_3a_data); +} + +void mf_ultralight_copy(MfUltralightData* data, const MfUltralightData* other) { + furi_assert(data); + furi_assert(other); + + iso14443_3a_copy(data->iso14443_3a_data, other->iso14443_3a_data); + for(size_t i = 0; i < COUNT_OF(data->counter); i++) { + data->counter[i] = other->counter[i]; + } + for(size_t i = 0; i < COUNT_OF(data->tearing_flag); i++) { + data->tearing_flag[i] = other->tearing_flag[i]; + } + for(size_t i = 0; i < COUNT_OF(data->page); i++) { + data->page[i] = other->page[i]; + } + + data->type = other->type; + data->version = other->version; + data->signature = other->signature; + + data->pages_read = other->pages_read; + data->pages_total = other->pages_total; + data->auth_attempts = other->auth_attempts; +} + +static const char* + mf_ultralight_get_device_name_by_type(MfUltralightType type, NfcDeviceNameType name_type) { + if(name_type == NfcDeviceNameTypeShort && + (type == MfUltralightTypeUL11 || type == MfUltralightTypeUL21)) { + type = MfUltralightTypeUnknown; + } + + return mf_ultralight_features[type].device_name; +} + +bool mf_ultralight_verify(MfUltralightData* data, const FuriString* device_type) { + furi_assert(data); + + bool verified = false; + + for(MfUltralightType i = 0; i < MfUltralightTypeNum; i++) { + const char* name = mf_ultralight_get_device_name_by_type(i, NfcDeviceNameTypeFull); + verified = furi_string_equal(device_type, name); + if(verified) { + data->type = i; + break; + } + } + + return verified; +} + +bool mf_ultralight_load(MfUltralightData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + + FuriString* temp_str = furi_string_alloc(); + bool parsed = false; + + do { + // Read ISO14443_3A data + if(!iso14443_3a_load(data->iso14443_3a_data, ff, version)) break; + + // Read Ultralight specific data + // Read Mifare Ultralight format version + uint32_t data_format_version = 0; + if(!flipper_format_read_uint32( + ff, MF_ULTRALIGHT_FORMAT_VERSION_KEY, &data_format_version, 1)) { + if(!flipper_format_rewind(ff)) break; + } + + // Read Mifare Ultralight type + if(data_format_version > 1) { + if(!flipper_format_read_string(ff, MF_ULTRALIGHT_TYPE_KEY, temp_str)) break; + if(!mf_ultralight_verify(data, temp_str)) break; + } + + // Read signature + if(!flipper_format_read_hex( + ff, + MF_ULTRALIGHT_SIGNATURE_KEY, + data->signature.data, + sizeof(MfUltralightSignature))) + break; + // Read Mifare version + if(!flipper_format_read_hex( + ff, + MF_ULTRALIGHT_MIFARE_VERSION_KEY, + (uint8_t*)&data->version, + sizeof(MfUltralightVersion))) + break; + // Read counters and tearing flags + bool counters_parsed = true; + for(size_t i = 0; i < 3; i++) { + furi_string_printf(temp_str, "%s %d", MF_ULTRALIGHT_COUNTER_KEY, i); + if(!flipper_format_read_uint32( + ff, furi_string_get_cstr(temp_str), &data->counter[i].counter, 1)) { + counters_parsed = false; + break; + } + furi_string_printf(temp_str, "%s %d", MF_ULTRALIGHT_TEARING_KEY, i); + if(!flipper_format_read_hex( + ff, furi_string_get_cstr(temp_str), &data->tearing_flag[i].data, 1)) { + counters_parsed = false; + break; + } + } + if(!counters_parsed) break; + // Read pages + uint32_t pages_total = 0; + if(!flipper_format_read_uint32(ff, MF_ULTRALIGHT_PAGES_TOTAL_KEY, &pages_total, 1)) break; + uint32_t pages_read = 0; + if(data_format_version < mf_ultralight_data_format_version) { //-V547 + pages_read = pages_total; + } else { + if(!flipper_format_read_uint32(ff, MF_ULTRALIGHT_PAGES_READ_KEY, &pages_read, 1)) + break; + } + data->pages_total = pages_total; + data->pages_read = pages_read; + + if((pages_read > MF_ULTRALIGHT_MAX_PAGE_NUM) || (pages_total > MF_ULTRALIGHT_MAX_PAGE_NUM)) + break; + + bool pages_parsed = true; + for(size_t i = 0; i < pages_total; i++) { + furi_string_printf(temp_str, "%s %d", MF_ULTRALIGHT_PAGE_KEY, i); + if(!flipper_format_read_hex( + ff, + furi_string_get_cstr(temp_str), + data->page[i].data, + sizeof(MfUltralightPage))) { + pages_parsed = false; + break; + } + } + if(!pages_parsed) break; + + // Read authentication counter + if(!flipper_format_read_uint32( + ff, MF_ULTRALIGHT_FAILED_ATTEMPTS_KEY, &data->auth_attempts, 1)) { + data->auth_attempts = 0; + } + + parsed = true; + } while(false); + + furi_string_free(temp_str); + + return parsed; +} + +bool mf_ultralight_save(const MfUltralightData* data, FlipperFormat* ff) { + furi_assert(data); + + FuriString* temp_str = furi_string_alloc(); + bool saved = false; + + do { + if(!iso14443_3a_save(data->iso14443_3a_data, ff)) break; + + if(!flipper_format_write_comment_cstr(ff, MF_ULTRALIGHT_PROTOCOL_NAME " specific data")) + break; + if(!flipper_format_write_uint32( + ff, MF_ULTRALIGHT_FORMAT_VERSION_KEY, &mf_ultralight_data_format_version, 1)) + break; + + const char* device_type_name = + mf_ultralight_get_device_name_by_type(data->type, NfcDeviceNameTypeFull); + if(!flipper_format_write_string_cstr(ff, MF_ULTRALIGHT_TYPE_KEY, device_type_name)) break; + if(!flipper_format_write_hex( + ff, + MF_ULTRALIGHT_SIGNATURE_KEY, + data->signature.data, + sizeof(MfUltralightSignature))) + break; + if(!flipper_format_write_hex( + ff, + MF_ULTRALIGHT_MIFARE_VERSION_KEY, + (uint8_t*)&data->version, + sizeof(MfUltralightVersion))) + break; + + // Write conters and tearing flags data + bool counters_saved = true; + for(size_t i = 0; i < 3; i++) { + furi_string_printf(temp_str, "%s %d", MF_ULTRALIGHT_COUNTER_KEY, i); + if(!flipper_format_write_uint32( + ff, furi_string_get_cstr(temp_str), &data->counter[i].counter, 1)) { + counters_saved = false; + break; + } + furi_string_printf(temp_str, "%s %d", MF_ULTRALIGHT_TEARING_KEY, i); + if(!flipper_format_write_hex( + ff, furi_string_get_cstr(temp_str), &data->tearing_flag[i].data, 1)) { + counters_saved = false; + break; + } + } + if(!counters_saved) break; + + // Write pages data + uint32_t pages_total = data->pages_total; + uint32_t pages_read = data->pages_read; + if(!flipper_format_write_uint32(ff, MF_ULTRALIGHT_PAGES_TOTAL_KEY, &pages_total, 1)) break; + if(!flipper_format_write_uint32(ff, MF_ULTRALIGHT_PAGES_READ_KEY, &pages_read, 1)) break; + bool pages_saved = true; + for(size_t i = 0; i < data->pages_total; i++) { + furi_string_printf(temp_str, "%s %d", MF_ULTRALIGHT_PAGE_KEY, i); + if(!flipper_format_write_hex( + ff, + furi_string_get_cstr(temp_str), + data->page[i].data, + sizeof(MfUltralightPage))) { + pages_saved = false; + break; + } + } + if(!pages_saved) break; + + // Write authentication counter + if(!flipper_format_write_uint32( + ff, MF_ULTRALIGHT_FAILED_ATTEMPTS_KEY, &data->auth_attempts, 1)) + break; + + saved = true; + } while(false); + + furi_string_free(temp_str); + + return saved; +} + +bool mf_ultralight_is_equal(const MfUltralightData* data, const MfUltralightData* other) { + bool is_equal = false; + bool data_array_is_equal = true; + + do { + if(!iso14443_3a_is_equal(data->iso14443_3a_data, other->iso14443_3a_data)) break; + if(data->type != other->type) break; + if(data->pages_read != other->pages_read) break; + if(data->pages_total != other->pages_total) break; + if(data->auth_attempts != other->auth_attempts) break; + + if(memcmp(&data->version, &other->version, sizeof(data->version)) != 0) break; + if(memcmp(&data->signature, &other->signature, sizeof(data->signature)) != 0) break; + + for(size_t i = 0; i < COUNT_OF(data->counter); i++) { + if(memcmp(&data->counter[i], &other->counter[i], sizeof(data->counter[i])) != 0) { + data_array_is_equal = false; + break; + } + } + if(!data_array_is_equal) break; + + for(size_t i = 0; i < COUNT_OF(data->tearing_flag); i++) { + if(memcmp( + &data->tearing_flag[i], + &other->tearing_flag[i], + sizeof(data->tearing_flag[i])) != 0) { + data_array_is_equal = false; + break; + } + } + if(!data_array_is_equal) break; + + for(size_t i = 0; i < COUNT_OF(data->page); i++) { + if(memcmp(&data->page[i], &other->page[i], sizeof(data->page[i])) != 0) { + data_array_is_equal = false; + break; + } + } + if(!data_array_is_equal) break; + + is_equal = true; + } while(false); + + return is_equal; +} + +const char* + mf_ultralight_get_device_name(const MfUltralightData* data, NfcDeviceNameType name_type) { + furi_assert(data); + furi_assert(data->type < MfUltralightTypeNum); + + return mf_ultralight_get_device_name_by_type(data->type, name_type); +} + +const uint8_t* mf_ultralight_get_uid(const MfUltralightData* data, size_t* uid_len) { + furi_assert(data); + + return iso14443_3a_get_uid(data->iso14443_3a_data, uid_len); +} + +bool mf_ultralight_set_uid(MfUltralightData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + return iso14443_3a_set_uid(data->iso14443_3a_data, uid, uid_len); +} + +Iso14443_3aData* mf_ultralight_get_base_data(const MfUltralightData* data) { + furi_assert(data); + + return data->iso14443_3a_data; +} + +MfUltralightType mf_ultralight_get_type_by_version(MfUltralightVersion* version) { + furi_assert(version); + + MfUltralightType type = MfUltralightTypeUnknown; + + if(version->storage_size == 0x0B || version->storage_size == 0x00) { + type = MfUltralightTypeUL11; + } else if(version->storage_size == 0x0E) { + type = MfUltralightTypeUL21; + } else if(version->storage_size == 0x0F) { + type = MfUltralightTypeNTAG213; + } else if(version->storage_size == 0x11) { + type = MfUltralightTypeNTAG215; + } else if(version->prod_subtype == 5 && version->prod_ver_major == 2) { + if(version->prod_ver_minor == 1) { + if(version->storage_size == 0x13) { + type = MfUltralightTypeNTAGI2C1K; + } else if(version->storage_size == 0x15) { + type = MfUltralightTypeNTAGI2C2K; + } + } else if(version->prod_ver_minor == 2) { + if(version->storage_size == 0x13) { + type = MfUltralightTypeNTAGI2CPlus1K; + } else if(version->storage_size == 0x15) { + type = MfUltralightTypeNTAGI2CPlus2K; + } + } + } else if(version->storage_size == 0x13) { + type = MfUltralightTypeNTAG216; + } + + return type; +} + +uint16_t mf_ultralight_get_pages_total(MfUltralightType type) { + return mf_ultralight_features[type].total_pages; +} + +uint32_t mf_ultralight_get_feature_support_set(MfUltralightType type) { + return mf_ultralight_features[type].feature_set; +} + +bool mf_ultralight_detect_protocol(const Iso14443_3aData* iso14443_3a_data) { + furi_assert(iso14443_3a_data); + + bool mfu_detected = (iso14443_3a_data->atqa[0] == 0x44) && + (iso14443_3a_data->atqa[1] == 0x00) && (iso14443_3a_data->sak == 0x00); + + return mfu_detected; +} + +uint16_t mf_ultralight_get_config_page_num(MfUltralightType type) { + return mf_ultralight_features[type].config_page; +} + +uint8_t mf_ultralight_get_pwd_page_num(MfUltralightType type) { + uint8_t config_page = mf_ultralight_features[type].config_page; + return (config_page != 0) ? config_page + 2 : 0; +} + +bool mf_ultralight_is_page_pwd_or_pack(MfUltralightType type, uint16_t page) { + uint8_t pwd_page = mf_ultralight_get_pwd_page_num(type); + uint8_t pack_page = pwd_page + 1; + return ((pwd_page != 0) && (page == pwd_page || page == pack_page)); +} + +bool mf_ultralight_support_feature(const uint32_t feature_set, const uint32_t features_to_check) { + return (feature_set & features_to_check) != 0; +} + +bool mf_ultralight_get_config_page(const MfUltralightData* data, MfUltralightConfigPages** config) { + furi_assert(data); + furi_assert(config); + + bool config_pages_found = false; + + uint16_t config_page = mf_ultralight_features[data->type].config_page; + if(config_page != 0) { + *config = (MfUltralightConfigPages*)&data->page[config_page]; //-V1027 + config_pages_found = true; + } + + return config_pages_found; +} + +bool mf_ultralight_is_all_data_read(const MfUltralightData* data) { + furi_assert(data); + + bool all_read = false; + if(data->pages_read == data->pages_total || + (data->type == MfUltralightTypeMfulC && data->pages_read == data->pages_total - 4)) { + // Having read all the pages doesn't mean that we've got everything. + // By default PWD is 0xFFFFFFFF, but if read back it is always 0x00000000, + // so a default read on an auth-supported NTAG is never complete. + uint32_t feature_set = mf_ultralight_get_feature_support_set(data->type); + if(!mf_ultralight_support_feature(feature_set, MfUltralightFeatureSupportPasswordAuth)) { + all_read = true; + } else { + MfUltralightConfigPages* config = NULL; + if(mf_ultralight_get_config_page(data, &config)) { + uint32_t pass = + nfc_util_bytes2num(config->password.data, sizeof(MfUltralightAuthPassword)); + uint16_t pack = + nfc_util_bytes2num(config->pack.data, sizeof(MfUltralightAuthPack)); + all_read = ((pass != 0) || (pack != 0)); + } + } + } + + return all_read; +} + +bool mf_ultralight_is_counter_configured(const MfUltralightData* data) { + furi_assert(data); + + MfUltralightConfigPages* config = NULL; + bool configured = false; + + switch(data->type) { + case MfUltralightTypeNTAG213: + case MfUltralightTypeNTAG215: + case MfUltralightTypeNTAG216: + if(mf_ultralight_get_config_page(data, &config)) { + configured = config->access.nfc_cnt_en; + } + break; + + default: + configured = true; + break; + } + + return configured; +} diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight.h b/lib/nfc/protocols/mf_ultralight/mf_ultralight.h new file mode 100644 index 000000000..747f5937a --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight.h @@ -0,0 +1,229 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define MF_ULTRALIGHT_TEARING_FLAG_DEFAULT (0xBD) + +#define MF_ULTRALIGHT_CMD_GET_VERSION (0x60) +#define MF_ULTRALIGHT_CMD_READ_PAGE (0x30) +#define MF_ULTRALIGHT_CMD_FAST_READ (0x3A) +#define MF_ULTRALIGHT_CMD_SECTOR_SELECT (0xC2) +#define MF_ULTRALIGHT_CMD_COMP_WRITE (0xA0) +#define MF_ULTRALIGHT_CMD_WRITE_PAGE (0xA2) +#define MF_ULTRALIGHT_CMD_FAST_WRITE (0xA6) +#define MF_ULTRALIGHT_CMD_READ_SIG (0x3C) +#define MF_ULTRALIGHT_CMD_READ_CNT (0x39) +#define MF_ULTRALIGHT_CMD_INCR_CNT (0xA5) +#define MF_ULTRALIGHT_CMD_CHECK_TEARING (0x3E) +#define MF_ULTRALIGHT_CMD_PWD_AUTH (0x1B) +#define MF_ULTRALIGHT_CMD_AUTH (0x1A) +#define MF_ULTRALIGHT_CMD_VCSL (0x4B) + +#define MF_ULTRALIGHT_CMD_ACK (0x0A) +#define MF_ULTRALIGHT_CMD_NACK (0x00) +#define MF_ULTRALIGHT_CMD_AUTH_NAK (0x04) + +#define MF_ULTRALIGHT_MAX_CNTR_VAL (0x00FFFFFF) +#define MF_ULTRALIGHT_MAX_PAGE_NUM (510) +#define MF_ULTRALIGHT_PAGE_SIZE (4U) +#define MF_ULTRALIGHT_SIGNATURE_SIZE (32) +#define MF_ULTRALIGHT_COUNTER_SIZE (3) +#define MF_ULTRALIGHT_COUNTER_NUM (3) +#define MF_ULTRALIGHT_TEARING_FLAG_SIZE (1) +#define MF_ULTRALIGHT_TEARING_FLAG_NUM (3) +#define MF_ULTRALIGHT_AUTH_PASSWORD_SIZE (4) +#define MF_ULTRALIGHT_AUTH_PACK_SIZE (2) +#define MF_ULTRALIGHT_AUTH_RESPONSE_SIZE (9) + +typedef enum { + MfUltralightErrorNone, + MfUltralightErrorNotPresent, + MfUltralightErrorProtocol, + MfUltralightErrorAuth, + MfUltralightErrorTimeout, +} MfUltralightError; + +typedef enum { + MfUltralightTypeUnknown, + MfUltralightTypeNTAG203, + MfUltralightTypeMfulC, + MfUltralightTypeUL11, + MfUltralightTypeUL21, + MfUltralightTypeNTAG213, + MfUltralightTypeNTAG215, + MfUltralightTypeNTAG216, + MfUltralightTypeNTAGI2C1K, + MfUltralightTypeNTAGI2C2K, + MfUltralightTypeNTAGI2CPlus1K, + MfUltralightTypeNTAGI2CPlus2K, + + MfUltralightTypeNum, +} MfUltralightType; + +typedef enum { + MfUltralightFeatureSupportReadVersion = (1U << 0), + MfUltralightFeatureSupportReadSignature = (1U << 1), + MfUltralightFeatureSupportReadCounter = (1U << 2), + MfUltralightFeatureSupportCheckTearingFlag = (1U << 3), + MfUltralightFeatureSupportFastRead = (1U << 4), + MfUltralightFeatureSupportIncCounter = (1U << 5), + MfUltralightFeatureSupportFastWrite = (1U << 6), + MfUltralightFeatureSupportCompatibleWrite = (1U << 7), + MfUltralightFeatureSupportPasswordAuth = (1U << 8), + MfUltralightFeatureSupportVcsl = (1U << 9), + MfUltralightFeatureSupportSectorSelect = (1U << 10), + MfUltralightFeatureSupportSingleCounter = (1U << 11), + MfUltralightFeatureSupportAsciiMirror = (1U << 12), + MfUltralightFeatureSupportCounterInMemory = (1U << 13), + MfUltralightFeatureSupportDynamicLock = (1U << 14), + MfUltralightFeatureSupportAuthenticate = (1U << 15), +} MfUltralightFeatureSupport; + +typedef struct { + uint8_t data[MF_ULTRALIGHT_PAGE_SIZE]; +} MfUltralightPage; + +typedef struct { + MfUltralightPage page[4]; +} MfUltralightPageReadCommandData; + +typedef struct { + uint8_t header; + uint8_t vendor_id; + uint8_t prod_type; + uint8_t prod_subtype; + uint8_t prod_ver_major; + uint8_t prod_ver_minor; + uint8_t storage_size; + uint8_t protocol_type; +} MfUltralightVersion; + +typedef struct { + uint8_t data[MF_ULTRALIGHT_SIGNATURE_SIZE]; +} MfUltralightSignature; + +typedef union { + uint32_t counter; + uint8_t data[MF_ULTRALIGHT_COUNTER_SIZE]; +} MfUltralightCounter; + +typedef struct { + uint8_t data; +} MfUltralightTearingFlag; + +typedef struct { + uint8_t data[MF_ULTRALIGHT_AUTH_PASSWORD_SIZE]; +} MfUltralightAuthPassword; + +typedef struct { + uint8_t data[MF_ULTRALIGHT_AUTH_PACK_SIZE]; +} MfUltralightAuthPack; + +typedef enum { + MfUltralightMirrorNone, + MfUltralightMirrorUid, + MfUltralightMirrorCounter, + MfUltralightMirrorUidCounter, +} MfUltralightMirrorConf; + +typedef struct __attribute__((packed)) { + union { + uint8_t value; + struct { + uint8_t rfui1 : 2; + bool strg_mod_en : 1; + bool rfui2 : 1; + uint8_t mirror_byte : 2; + MfUltralightMirrorConf mirror_conf : 2; + }; + } mirror; + uint8_t rfui1; + uint8_t mirror_page; + uint8_t auth0; + union { + uint8_t value; + struct { + uint8_t authlim : 3; + bool nfc_cnt_pwd_prot : 1; + bool nfc_cnt_en : 1; + bool nfc_dis_sec1 : 1; // NTAG I2C Plus only + bool cfglck : 1; + bool prot : 1; + }; + } access; + uint8_t vctid; + uint8_t rfui2[2]; + MfUltralightAuthPassword password; + MfUltralightAuthPack pack; + uint8_t rfui3[2]; +} MfUltralightConfigPages; + +typedef struct { + Iso14443_3aData* iso14443_3a_data; + MfUltralightType type; + MfUltralightVersion version; + MfUltralightSignature signature; + MfUltralightCounter counter[MF_ULTRALIGHT_COUNTER_NUM]; + MfUltralightTearingFlag tearing_flag[MF_ULTRALIGHT_TEARING_FLAG_NUM]; + MfUltralightPage page[MF_ULTRALIGHT_MAX_PAGE_NUM]; + uint16_t pages_read; + uint16_t pages_total; + uint32_t auth_attempts; +} MfUltralightData; + +extern const NfcDeviceBase nfc_device_mf_ultralight; + +MfUltralightData* mf_ultralight_alloc(); + +void mf_ultralight_free(MfUltralightData* data); + +void mf_ultralight_reset(MfUltralightData* data); + +void mf_ultralight_copy(MfUltralightData* data, const MfUltralightData* other); + +bool mf_ultralight_verify(MfUltralightData* data, const FuriString* device_type); + +bool mf_ultralight_load(MfUltralightData* data, FlipperFormat* ff, uint32_t version); + +bool mf_ultralight_save(const MfUltralightData* data, FlipperFormat* ff); + +bool mf_ultralight_is_equal(const MfUltralightData* data, const MfUltralightData* other); + +const char* + mf_ultralight_get_device_name(const MfUltralightData* data, NfcDeviceNameType name_type); + +const uint8_t* mf_ultralight_get_uid(const MfUltralightData* data, size_t* uid_len); + +bool mf_ultralight_set_uid(MfUltralightData* data, const uint8_t* uid, size_t uid_len); + +Iso14443_3aData* mf_ultralight_get_base_data(const MfUltralightData* data); + +MfUltralightType mf_ultralight_get_type_by_version(MfUltralightVersion* version); + +uint16_t mf_ultralight_get_pages_total(MfUltralightType type); + +uint32_t mf_ultralight_get_feature_support_set(MfUltralightType type); + +uint16_t mf_ultralight_get_config_page_num(MfUltralightType type); + +uint8_t mf_ultralight_get_pwd_page_num(MfUltralightType type); + +bool mf_ultralight_is_page_pwd_or_pack(MfUltralightType type, uint16_t page_num); + +bool mf_ultralight_support_feature(const uint32_t feature_set, const uint32_t features_to_check); + +bool mf_ultralight_get_config_page(const MfUltralightData* data, MfUltralightConfigPages** config); + +bool mf_ultralight_is_all_data_read(const MfUltralightData* data); + +bool mf_ultralight_detect_protocol(const Iso14443_3aData* iso14443_3a_data); + +bool mf_ultralight_is_counter_configured(const MfUltralightData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener.c b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener.c new file mode 100644 index 000000000..70c6f6de2 --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener.c @@ -0,0 +1,772 @@ +#include "mf_ultralight_listener_i.h" +#include "mf_ultralight_listener_defs.h" + +#include + +#include + +#define TAG "MfUltralightListener" + +#define MF_ULTRALIGHT_LISTENER_MAX_TX_BUFF_SIZE (256) + +typedef enum { + MfUltralightListenerAccessTypeRead, + MfUltralightListenerAccessTypeWrite, +} MfUltralightListenerAccessType; + +typedef struct { + uint8_t cmd; + size_t cmd_len_bits; + MfUltralightListenerCommandCallback callback; +} MfUltralightListenerCmdHandler; + +static bool mf_ultralight_listener_check_access( + MfUltralightListener* instance, + uint16_t start_page, + MfUltralightListenerAccessType access_type) { + bool access_success = false; + bool is_write_op = (access_type == MfUltralightListenerAccessTypeWrite); + + do { + if(!mf_ultralight_support_feature( + instance->features, MfUltralightFeatureSupportPasswordAuth)) { + access_success = true; + break; + } + if(instance->auth_state != MfUltralightListenerAuthStateSuccess) { + if((instance->config->auth0 <= start_page) && + (instance->config->access.prot || is_write_op)) { + break; + } + } + if(instance->config->access.cfglck && is_write_op) { + uint16_t config_page_start = instance->data->pages_total - 4; + if((start_page == config_page_start) || (start_page == config_page_start + 1)) { + break; + } + } + + access_success = true; + } while(false); + + return access_success; +} + +static void mf_ultralight_listener_send_short_resp(MfUltralightListener* instance, uint8_t data) { + furi_assert(instance->tx_buffer); + + bit_buffer_set_size(instance->tx_buffer, 4); + bit_buffer_set_byte(instance->tx_buffer, 0, data); + iso14443_3a_listener_tx(instance->iso14443_3a_listener, instance->tx_buffer); +}; + +static void mf_ultralight_listener_perform_read( + MfUltralightPage* pages, + MfUltralightListener* instance, + uint16_t start_page, + uint8_t page_cnt, + bool do_i2c_page_check) { + uint16_t pages_total = instance->data->pages_total; + mf_ultralight_mirror_read_prepare(start_page, instance); + for(uint8_t i = 0, rollover = 0; i < page_cnt; i++) { + uint16_t page = start_page + i; + + bool page_restricted = !mf_ultralight_listener_check_access( + instance, page, MfUltralightListenerAccessTypeRead); + + if(do_i2c_page_check && !mf_ultralight_i2c_validate_pages(page, page, instance)) + memset(pages[i].data, 0, sizeof(MfUltralightPage)); + else if(mf_ultralight_is_page_pwd_or_pack(instance->data->type, page)) + memset(pages[i].data, 0, sizeof(MfUltralightPage)); + else { + if(do_i2c_page_check) + page = mf_ultralight_i2c_provide_page_by_requested(page, instance); + + page = page_restricted ? rollover++ : page % pages_total; + pages[i] = instance->data->page[page]; + + mf_ultralight_mirror_read_handler(page, pages[i].data, instance); + } + } + mf_ultralight_single_counter_try_increase(instance); +} + +static MfUltralightCommand mf_ultralight_listener_perform_write( + MfUltralightListener* instance, + const uint8_t* const rx_data, + uint16_t start_page, + bool do_i2c_check) { + MfUltralightCommand command = MfUltralightCommandProcessedACK; + + if(start_page < 2 && instance->sector == 0) + command = MfUltralightCommandNotProcessedNAK; + else if(start_page == 2 && instance->sector == 0) + mf_ultralight_static_lock_bytes_write(instance->static_lock, *((uint16_t*)&rx_data[2])); + else if(start_page == 3 && instance->sector == 0) + mf_ultralight_capability_container_write(&instance->data->page[start_page], rx_data); + else if(mf_ultralight_is_page_dynamic_lock(instance, start_page)) + mf_ultralight_dynamic_lock_bytes_write(instance->dynamic_lock, *((uint32_t*)rx_data)); + else { + uint16_t page = start_page; + if(do_i2c_check) page = mf_ultralight_i2c_provide_page_by_requested(start_page, instance); + + memcpy(instance->data->page[page].data, rx_data, sizeof(MfUltralightPage)); + } + + return command; +} + +static MfUltralightCommand + mf_ultralight_listener_read_page_handler(MfUltralightListener* instance, BitBuffer* buffer) { + uint16_t start_page = bit_buffer_get_byte(buffer, 1); + uint16_t pages_total = instance->data->pages_total; + MfUltralightCommand command = MfUltralightCommandNotProcessedNAK; + + FURI_LOG_D(TAG, "CMD_READ: %d", start_page); + + do { + bool do_i2c_check = mf_ultralight_is_i2c_tag(instance->data->type); + + if(do_i2c_check) { + if(!mf_ultralight_i2c_validate_pages(start_page, start_page, instance)) break; + } else if(pages_total < start_page) { + break; + } + + if(!mf_ultralight_listener_check_access( + instance, start_page, MfUltralightListenerAccessTypeRead)) { + break; + } + + MfUltralightPage pages[4] = {}; + mf_ultralight_listener_perform_read(pages, instance, start_page, 4, do_i2c_check); + + bit_buffer_copy_bytes(instance->tx_buffer, (uint8_t*)pages, sizeof(pages)); + iso14443_3a_listener_send_standard_frame( + instance->iso14443_3a_listener, instance->tx_buffer); + command = MfUltralightCommandProcessed; + + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_listener_fast_read_handler(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedSilent; + FURI_LOG_D(TAG, "CMD_FAST_READ"); + + do { + if(!mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportFastRead)) + break; + uint16_t pages_total = instance->data->pages_total; + uint16_t start_page = bit_buffer_get_byte(buffer, 1); + uint16_t end_page = bit_buffer_get_byte(buffer, 2); + bool do_i2c_check = mf_ultralight_is_i2c_tag(instance->data->type); + + if(do_i2c_check) { + if(!mf_ultralight_i2c_validate_pages(start_page, end_page, instance)) { + command = MfUltralightCommandNotProcessedNAK; + break; + } + } else if(end_page > pages_total - 1) { + command = MfUltralightCommandNotProcessedNAK; + break; + } + + if(end_page < start_page) { + command = MfUltralightCommandNotProcessedNAK; + break; + } + + if(!mf_ultralight_listener_check_access( + instance, start_page, MfUltralightListenerAccessTypeRead) || + !mf_ultralight_listener_check_access( + instance, end_page, MfUltralightListenerAccessTypeRead)) { + command = MfUltralightCommandNotProcessedNAK; + break; + } + + MfUltralightPage pages[64] = {}; + uint8_t page_cnt = (end_page - start_page) + 1; + mf_ultralight_listener_perform_read(pages, instance, start_page, page_cnt, do_i2c_check); + + bit_buffer_copy_bytes(instance->tx_buffer, (uint8_t*)pages, page_cnt * 4); + iso14443_3a_listener_send_standard_frame( + instance->iso14443_3a_listener, instance->tx_buffer); + command = MfUltralightCommandProcessed; + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_listener_write_page_handler(MfUltralightListener* instance, BitBuffer* buffer) { + uint8_t start_page = bit_buffer_get_byte(buffer, 1); + uint16_t pages_total = instance->data->pages_total; + MfUltralightCommand command = MfUltralightCommandNotProcessedNAK; + + FURI_LOG_D(TAG, "CMD_WRITE"); + + do { + bool do_i2c_check = mf_ultralight_is_i2c_tag(instance->data->type); + + if(do_i2c_check) { + if(!mf_ultralight_i2c_validate_pages(start_page, start_page, instance)) break; + } else if(pages_total < start_page) { + break; + } + + if(!mf_ultralight_listener_check_access( + instance, start_page, MfUltralightListenerAccessTypeWrite)) + break; + + if(mf_ultralight_static_lock_check_page(instance->static_lock, start_page)) break; + if(mf_ultralight_dynamic_lock_check_page(instance, start_page)) break; + + const uint8_t* rx_data = bit_buffer_get_data(buffer); + command = + mf_ultralight_listener_perform_write(instance, &rx_data[2], start_page, do_i2c_check); + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_listener_fast_write_handler(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedSilent; + FURI_LOG_D(TAG, "CMD_FAST_WRITE"); + + do { + if(!mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportFastWrite)) + break; + + uint8_t start_page = bit_buffer_get_byte(buffer, 1); + uint8_t end_page = bit_buffer_get_byte(buffer, 2); + if(start_page != 0xF0 || end_page != 0xFF) { + command = MfUltralightCommandNotProcessedNAK; + break; + } + + // No SRAM emulation support + + command = MfUltralightCommandProcessedACK; + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_listener_read_version_handler(MfUltralightListener* instance, BitBuffer* buffer) { + UNUSED(buffer); + MfUltralightCommand command = MfUltralightCommandNotProcessedSilent; + + FURI_LOG_D(TAG, "CMD_GET_VERSION"); + + if(mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportReadVersion)) { + bit_buffer_copy_bytes( + instance->tx_buffer, (uint8_t*)&instance->data->version, sizeof(MfUltralightVersion)); + iso14443_3a_listener_send_standard_frame( + instance->iso14443_3a_listener, instance->tx_buffer); + command = MfUltralightCommandProcessed; + } + + return command; +} + +static MfUltralightCommand mf_ultralight_listener_read_signature_handler( + MfUltralightListener* instance, + BitBuffer* buffer) { + UNUSED(buffer); + MfUltralightCommand command = MfUltralightCommandNotProcessedSilent; + + FURI_LOG_D(TAG, "CMD_READ_SIG"); + + if(mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportReadSignature)) { + bit_buffer_copy_bytes( + instance->tx_buffer, instance->data->signature.data, sizeof(MfUltralightSignature)); + iso14443_3a_listener_send_standard_frame( + instance->iso14443_3a_listener, instance->tx_buffer); + command = MfUltralightCommandProcessed; + } + + return command; +} + +static MfUltralightCommand + mf_ultralight_listener_read_counter_handler(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedNAK; + + FURI_LOG_D(TAG, "CMD_READ_CNT"); + + do { + uint8_t counter_num = bit_buffer_get_byte(buffer, 1); + if(!mf_ultralight_support_feature( + instance->features, MfUltralightFeatureSupportReadCounter)) + break; + + if(mf_ultralight_support_feature( + instance->features, MfUltralightFeatureSupportSingleCounter)) { + if(instance->config == NULL) break; + + if(!instance->config->access.nfc_cnt_en || counter_num != 2) break; + + if(instance->config->access.nfc_cnt_pwd_prot) { + if(instance->auth_state != MfUltralightListenerAuthStateSuccess) { + break; + } + } + } + + if(counter_num > 2) break; + uint8_t cnt_value[3] = { + (instance->data->counter[counter_num].counter >> 0) & 0xff, + (instance->data->counter[counter_num].counter >> 8) & 0xff, + (instance->data->counter[counter_num].counter >> 16) & 0xff, + }; + bit_buffer_copy_bytes(instance->tx_buffer, cnt_value, sizeof(cnt_value)); + iso14443_3a_listener_send_standard_frame( + instance->iso14443_3a_listener, instance->tx_buffer); + command = MfUltralightCommandProcessed; + } while(false); + + return command; +} + +static MfUltralightCommand mf_ultralight_listener_increase_counter_handler( + MfUltralightListener* instance, + BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedNAK; + + FURI_LOG_D(TAG, "CMD_INCR_CNT"); + + do { + if(!mf_ultralight_support_feature( + instance->features, MfUltralightFeatureSupportIncCounter)) { + command = MfUltralightCommandNotProcessedSilent; + break; + } + + uint8_t counter_num = bit_buffer_get_byte(buffer, 1); + if(counter_num > 2) break; + + if(instance->data->counter[counter_num].counter == MF_ULTRALIGHT_MAX_CNTR_VAL) { + command = MfUltralightCommandProcessed; + break; + } + + MfUltralightCounter buf_counter = {}; + bit_buffer_write_bytes_mid(buffer, buf_counter.data, 2, sizeof(buf_counter.data)); + uint32_t incr_value = buf_counter.counter; + + if(instance->data->counter[counter_num].counter + incr_value > MF_ULTRALIGHT_MAX_CNTR_VAL) + break; + + instance->data->counter[counter_num].counter += incr_value; + command = MfUltralightCommandProcessedACK; + } while(false); + + return command; +} + +static MfUltralightCommand mf_ultralight_listener_check_tearing_handler( + MfUltralightListener* instance, + BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedNAK; + + FURI_LOG_D(TAG, "CMD_CHECK_TEARING"); + + do { + uint8_t tearing_flag_num = bit_buffer_get_byte(buffer, 1); + if(!mf_ultralight_support_feature( + instance->features, + MfUltralightFeatureSupportCheckTearingFlag | + MfUltralightFeatureSupportSingleCounter)) { + break; + } + if(mf_ultralight_support_feature( + instance->features, MfUltralightFeatureSupportSingleCounter) && + (tearing_flag_num != 2)) { + break; + } + if(tearing_flag_num >= MF_ULTRALIGHT_TEARING_FLAG_NUM) { + break; + } + + bit_buffer_set_size_bytes(instance->tx_buffer, 1); + bit_buffer_set_byte( + instance->tx_buffer, 0, instance->data->tearing_flag[tearing_flag_num].data); + iso14443_3a_listener_send_standard_frame( + instance->iso14443_3a_listener, instance->tx_buffer); + command = MfUltralightCommandProcessed; + + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_listener_vcsl_handler(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedSilent; + UNUSED(instance); + UNUSED(buffer); + FURI_LOG_D(TAG, "CMD_VCSL"); + do { + if(!mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportVcsl)) + break; + + MfUltralightConfigPages* config; + if(!mf_ultralight_get_config_page(instance->data, &config)) break; + + bit_buffer_set_size_bytes(instance->tx_buffer, 1); + bit_buffer_set_byte(instance->tx_buffer, 0, config->vctid); + iso14443_3a_listener_send_standard_frame( + instance->iso14443_3a_listener, instance->tx_buffer); + command = MfUltralightCommandProcessed; + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_listener_auth_handler(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedNAK; + + FURI_LOG_D(TAG, "CMD_AUTH"); + + do { + if(!mf_ultralight_support_feature( + instance->features, MfUltralightFeatureSupportPasswordAuth)) + break; + + MfUltralightAuthPassword password; + bit_buffer_write_bytes_mid(buffer, password.data, 1, sizeof(password.data)); + + if(instance->callback) { + instance->mfu_event_data.password = password; + instance->mfu_event.type = MfUltralightListenerEventTypeAuth; + instance->callback(instance->generic_event, instance->context); + } + + bool auth_success = + mf_ultralight_auth_check_password(&instance->config->password, &password); + bool card_locked = mf_ultralight_auth_limit_check_and_update(instance, auth_success); + + if(card_locked) { + command = MfUltralightCommandNotProcessedAuthNAK; + break; + } + + if(!auth_success) break; + + bit_buffer_copy_bytes( + instance->tx_buffer, instance->config->pack.data, sizeof(MfUltralightAuthPack)); + instance->auth_state = MfUltralightListenerAuthStateSuccess; + iso14443_3a_listener_send_standard_frame( + instance->iso14443_3a_listener, instance->tx_buffer); + + command = MfUltralightCommandProcessed; + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_comp_write_handler_p2(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedNAK; + FURI_LOG_D(TAG, "CMD_CM_WR_2"); + + do { + if(bit_buffer_get_size_bytes(buffer) != 16) break; + + const uint8_t* rx_data = bit_buffer_get_data(buffer); + uint8_t start_page = instance->composite_cmd.data; + + command = mf_ultralight_listener_perform_write(instance, rx_data, start_page, false); + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_comp_write_handler_p1(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedSilent; + + FURI_LOG_D(TAG, "CMD_CM_WR_1"); + + do { + if(!mf_ultralight_support_feature( + instance->features, MfUltralightFeatureSupportCompatibleWrite)) + break; + + uint8_t start_page = bit_buffer_get_byte(buffer, 1); + uint16_t last_page = instance->data->pages_total - 1; + + if(start_page < 2 || start_page > last_page) { + command = MfUltralightCommandNotProcessedNAK; + break; + } + + if(!mf_ultralight_listener_check_access( + instance, start_page, MfUltralightListenerAccessTypeWrite)) { + command = MfUltralightCommandNotProcessedNAK; + break; + } + + if(mf_ultralight_static_lock_check_page(instance->static_lock, start_page) || + mf_ultralight_dynamic_lock_check_page(instance, start_page)) { + command = MfUltralightCommandNotProcessedNAK; + break; + } + + instance->composite_cmd.data = start_page; + command = MfUltralightCommandProcessedACK; + mf_ultralight_composite_command_set_next(instance, mf_ultralight_comp_write_handler_p2); + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_sector_select_handler_p2(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedNAK; + UNUSED(instance); + UNUSED(buffer); + FURI_LOG_D(TAG, "CMD_SEC_SEL_2"); + + do { + if(bit_buffer_get_size_bytes(buffer) != 4) break; + uint8_t sector = bit_buffer_get_byte(buffer, 0); + if(sector == 0xFF) break; + + instance->sector = sector; + command = MfUltralightCommandProcessedSilent; + } while(false); + + return command; +} + +static MfUltralightCommand + mf_ultralight_sector_select_handler_p1(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = MfUltralightCommandNotProcessedNAK; + UNUSED(buffer); + FURI_LOG_D(TAG, "CMD_SEC_SEL_1"); + + do { + if(!mf_ultralight_support_feature( + instance->features, MfUltralightFeatureSupportSectorSelect) && + bit_buffer_get_byte(buffer, 1) == 0xFF) + break; + + command = MfUltralightCommandProcessedACK; + mf_ultralight_composite_command_set_next(instance, mf_ultralight_sector_select_handler_p2); + } while(false); + + return command; +} + +static const MfUltralightListenerCmdHandler mf_ultralight_command[] = { + { + .cmd = MF_ULTRALIGHT_CMD_READ_PAGE, + .cmd_len_bits = 2 * 8, + .callback = mf_ultralight_listener_read_page_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_FAST_READ, + .cmd_len_bits = 3 * 8, + .callback = mf_ultralight_listener_fast_read_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_WRITE_PAGE, + .cmd_len_bits = 6 * 8, + .callback = mf_ultralight_listener_write_page_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_FAST_WRITE, + .cmd_len_bits = 67 * 8, + .callback = mf_ultralight_listener_fast_write_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_GET_VERSION, + .cmd_len_bits = 8, + .callback = mf_ultralight_listener_read_version_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_READ_SIG, + .cmd_len_bits = 2 * 8, + .callback = mf_ultralight_listener_read_signature_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_READ_CNT, + .cmd_len_bits = 2 * 8, + .callback = mf_ultralight_listener_read_counter_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_CHECK_TEARING, + .cmd_len_bits = 2 * 8, + .callback = mf_ultralight_listener_check_tearing_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_PWD_AUTH, + .cmd_len_bits = 5 * 8, + .callback = mf_ultralight_listener_auth_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_INCR_CNT, + .cmd_len_bits = 6 * 8, + .callback = mf_ultralight_listener_increase_counter_handler, + }, + { + .cmd = MF_ULTRALIGHT_CMD_SECTOR_SELECT, + .cmd_len_bits = 2 * 8, + .callback = mf_ultralight_sector_select_handler_p1, + }, + { + .cmd = MF_ULTRALIGHT_CMD_COMP_WRITE, + .cmd_len_bits = 2 * 8, + .callback = mf_ultralight_comp_write_handler_p1, + }, + { + .cmd = MF_ULTRALIGHT_CMD_VCSL, + .cmd_len_bits = 21 * 8, + .callback = mf_ultralight_listener_vcsl_handler, + }, +}; + +static void mf_ultralight_listener_prepare_emulation(MfUltralightListener* instance) { + MfUltralightData* data = instance->data; + instance->features = mf_ultralight_get_feature_support_set(data->type); + mf_ultralight_get_config_page(data, &instance->config); + mf_ultralight_mirror_prepare_emulation(instance); + mf_ultralight_static_lock_bytes_prepare(instance); + mf_ultralight_dynamic_lock_bytes_prepare(instance); +} + +static NfcCommand mf_ultralight_command_postprocess( + MfUltralightCommand mfu_command, + MfUltralightListener* instance) { + NfcCommand command = NfcCommandContinue; + + if(mfu_command == MfUltralightCommandProcessedACK) { + mf_ultralight_listener_send_short_resp(instance, MF_ULTRALIGHT_CMD_ACK); + command = NfcCommandContinue; + } else if(mfu_command == MfUltralightCommandProcessedSilent) { + command = NfcCommandReset; + } else if(mfu_command != MfUltralightCommandProcessed) { + instance->auth_state = MfUltralightListenerAuthStateIdle; + command = NfcCommandSleep; + + if(mfu_command == MfUltralightCommandNotProcessedNAK) { + mf_ultralight_listener_send_short_resp(instance, MF_ULTRALIGHT_CMD_NACK); + } else if(mfu_command == MfUltralightCommandNotProcessedAuthNAK) { + mf_ultralight_listener_send_short_resp(instance, MF_ULTRALIGHT_CMD_AUTH_NAK); + } + } + + return command; +} + +static NfcCommand mf_ultralight_reset_listener_state( + MfUltralightListener* instance, + Iso14443_3aListenerEventType event_type) { + mf_ultralight_composite_command_reset(instance); + mf_ultralight_single_counter_try_to_unlock(instance, event_type); + instance->sector = 0; + instance->auth_state = MfUltralightListenerAuthStateIdle; + return NfcCommandSleep; +} + +MfUltralightListener* mf_ultralight_listener_alloc( + Iso14443_3aListener* iso14443_3a_listener, + MfUltralightData* data) { + furi_assert(iso14443_3a_listener); + + MfUltralightListener* instance = malloc(sizeof(MfUltralightListener)); + instance->mirror.ascii_mirror_data = furi_string_alloc(); + instance->iso14443_3a_listener = iso14443_3a_listener; + instance->data = data; + mf_ultralight_static_lock_bytes_prepare(instance); + mf_ultralight_listener_prepare_emulation(instance); + mf_ultralight_composite_command_reset(instance); + instance->sector = 0; + instance->tx_buffer = bit_buffer_alloc(MF_ULTRALIGHT_LISTENER_MAX_TX_BUFF_SIZE); + + instance->mfu_event.data = &instance->mfu_event_data; + instance->generic_event.protocol = NfcProtocolMfUltralight; + instance->generic_event.instance = instance; + instance->generic_event.event_data = &instance->mfu_event; + + return instance; +} + +void mf_ultralight_listener_free(MfUltralightListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + furi_assert(instance->tx_buffer); + + bit_buffer_free(instance->tx_buffer); + furi_string_free(instance->mirror.ascii_mirror_data); + free(instance); +} + +const MfUltralightData* mf_ultralight_listener_get_data(MfUltralightListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +void mf_ultralight_listener_set_callback( + MfUltralightListener* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + + instance->callback = callback; + instance->context = context; +} + +NfcCommand mf_ultralight_listener_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + furi_assert(event.event_data); + + MfUltralightListener* instance = context; + Iso14443_3aListenerEvent* iso14443_3a_event = event.event_data; + BitBuffer* rx_buffer = iso14443_3a_event->data->buffer; + NfcCommand command = NfcCommandContinue; + + if(iso14443_3a_event->type == Iso14443_3aListenerEventTypeReceivedStandardFrame) { + MfUltralightCommand mfu_command = MfUltralightCommandNotFound; + size_t size = bit_buffer_get_size(rx_buffer); + uint8_t cmd = bit_buffer_get_byte(rx_buffer, 0); + + if(mf_ultralight_composite_command_in_progress(instance)) { + mfu_command = mf_ultralight_composite_command_run(instance, rx_buffer); + } else { + for(size_t i = 0; i < COUNT_OF(mf_ultralight_command); i++) { + if(size != mf_ultralight_command[i].cmd_len_bits) continue; + if(cmd != mf_ultralight_command[i].cmd) continue; + mfu_command = mf_ultralight_command[i].callback(instance, rx_buffer); + + if(mfu_command != MfUltralightCommandNotFound) break; + } + } + command = mf_ultralight_command_postprocess(mfu_command, instance); + } else if( + iso14443_3a_event->type == Iso14443_3aListenerEventTypeReceivedData || + iso14443_3a_event->type == Iso14443_3aListenerEventTypeFieldOff || + iso14443_3a_event->type == Iso14443_3aListenerEventTypeHalted) { + command = mf_ultralight_reset_listener_state(instance, iso14443_3a_event->type); + } + + return command; +} + +const NfcListenerBase mf_ultralight_listener = { + .alloc = (NfcListenerAlloc)mf_ultralight_listener_alloc, + .free = (NfcListenerFree)mf_ultralight_listener_free, + .get_data = (NfcListenerGetData)mf_ultralight_listener_get_data, + .set_callback = (NfcListenerSetCallback)mf_ultralight_listener_set_callback, + .run = (NfcListenerRun)mf_ultralight_listener_run, +}; diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener.h b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener.h new file mode 100644 index 000000000..fa6a6bd7e --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener.h @@ -0,0 +1,28 @@ +#pragma once + +#include "mf_ultralight.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct MfUltralightListener MfUltralightListener; + +typedef enum { + MfUltralightListenerEventTypeAuth, +} MfUltralightListenerEventType; + +typedef struct { + union { + MfUltralightAuthPassword password; + }; +} MfUltralightListenerEventData; + +typedef struct { + MfUltralightListenerEventType type; + MfUltralightListenerEventData* data; +} MfUltralightListenerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener_defs.h b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener_defs.h new file mode 100644 index 000000000..aa3e11b8c --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener_defs.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NfcListenerBase mf_ultralight_listener; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener_i.c b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener_i.c new file mode 100644 index 000000000..64647492d --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener_i.c @@ -0,0 +1,579 @@ +#include "mf_ultralight_listener_i.h" + +#include + +#define MF_ULTRALIGHT_STATIC_BIT_LOCK_OTP_CC 0 +#define MF_ULTRALIGHT_STATIC_BIT_LOCK_BL_9_4 1 +#define MF_ULTRALIGHT_STATIC_BIT_LOCK_BL_15_10 2 + +#define MF_ULTRALIGHT_BIT_ACTIVE(lock_bits, bit) (((lock_bits) & (1U << (bit))) != 0) +#define MF_ULTRALIGHT_BITS_SET(lock_bits, mask) ((lock_bits) |= (mask)) +#define MF_ULTRALIGHT_BITS_CLR(lock_bits, mask) ((lock_bits) &= ~(mask)) + +#define MF_ULTRALIGHT_PAGE_LOCKED(lock_bits, page) MF_ULTRALIGHT_BIT_ACTIVE(lock_bits, page) + +#define MF_ULTRALIGHT_STATIC_BIT_OTP_CC_LOCKED(lock_bits) \ + MF_ULTRALIGHT_BIT_ACTIVE(lock_bits, MF_ULTRALIGHT_STATIC_BIT_LOCK_OTP_CC) + +#define MF_ULTRALIGHT_STATIC_BITS_9_4_LOCKED(lock_bits) \ + MF_ULTRALIGHT_BIT_ACTIVE(lock_bits, MF_ULTRALIGHT_STATIC_BIT_LOCK_BL_9_4) + +#define MF_ULTRALIGHT_STATIC_BITS_15_10_LOCKED(lock_bits) \ + MF_ULTRALIGHT_BIT_ACTIVE(lock_bits, MF_ULTRALIGHT_STATIC_BIT_LOCK_BL_15_10) + +#define MF_ULTRALIGHT_STATIC_LOCK_L_OTP_CC_MASK (1U << 3) +#define MF_ULTRALIGHT_STATIC_LOCK_L_9_4_MASK \ + ((1U << 9) | (1U << 8) | (1U << 7) | (1U << 6) | (1U << 5) | (1U << 4)) +#define MF_ULTRALIGHT_STATIC_LOCK_L_15_10_MASK \ + ((1U << 15) | (1U << 14) | (1U << 13) | (1U << 12) | (1U << 11) | (1U << 10)) + +#define MF_ULTRALIGHT_PAGE_IN_BOUNDS(page, start, end) (((page) >= (start)) && ((page) <= (end))) + +#define MF_ULTRALIGHT_I2C_PAGE_ON_SESSION_REG(page) \ + MF_ULTRALIGHT_PAGE_IN_BOUNDS(page, 0x00EC, 0x00ED) + +#define MF_ULTRALIGHT_I2C_PAGE_ON_MIRRORED_SESSION_REG(page) \ + MF_ULTRALIGHT_PAGE_IN_BOUNDS(page, 0x00F8, 0x00F9) + +#define MF_ULTRALIGHT_AUTH_RESET_ATTEMPTS(instance) (instance->data->auth_attempts = 0) +#define MF_ULTRALIGHT_AUTH_INCREASE_ATTEMPTS(instance) (instance->data->auth_attempts++) + +static MfUltralightMirrorConf mf_ultralight_mirror_check_mode( + const MfUltralightConfigPages* const config, + const MfUltralightListenerAuthState auth_state) { + MfUltralightMirrorConf mirror_mode = config->mirror.mirror_conf; + + if(mirror_mode == MfUltralightMirrorNone || mirror_mode == MfUltralightMirrorUid) + return mirror_mode; + + if(!config->access.nfc_cnt_en || + (config->access.nfc_cnt_pwd_prot && auth_state != MfUltralightListenerAuthStateSuccess)) { + mirror_mode = mirror_mode == MfUltralightMirrorCounter ? MfUltralightMirrorNone : + MfUltralightMirrorUid; + } + return mirror_mode; +} + +static bool mf_ultralight_mirror_check_boundaries(MfUltralightListener* instance) { + const MfUltralightConfigPages* const conf = instance->config; + + uint8_t last_user_page = mf_ultralight_get_config_page_num(instance->data->type) - 2; + + uint8_t max_page_offset = 0; + uint8_t max_byte_offset = 2; + + MfUltralightMirrorConf mode = mf_ultralight_mirror_check_mode(conf, instance->auth_state); + + bool result = false; + bool again = false; + do { + if(mode == MfUltralightMirrorNone) { + break; + } else if(mode == MfUltralightMirrorUid) { + max_page_offset = 3; + } else if(mode == MfUltralightMirrorCounter) { + max_page_offset = 1; + } else if(mode == MfUltralightMirrorUidCounter) { + max_page_offset = 5; + max_byte_offset = 3; + } + + instance->mirror.actual_mode = mode; + + if(conf->mirror_page <= 3) break; + if(conf->mirror_page < last_user_page - max_page_offset) { + result = true; + break; + } + if(conf->mirror_page == last_user_page - max_page_offset) { + result = (conf->mirror.mirror_byte <= max_byte_offset); + break; + } + + if(conf->mirror_page > last_user_page - max_page_offset && + mode == MfUltralightMirrorUidCounter) { + mode = MfUltralightMirrorUid; + again = true; + } + } while(again); + + return result; +} + +static bool mf_ultralight_mirror_enabled(MfUltralightListener* instance) { + bool mirror_enabled = false; + if(mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportAsciiMirror) && + (instance->config != NULL) && mf_ultralight_mirror_check_boundaries(instance)) { + mirror_enabled = true; + } + instance->mirror.enabled = mirror_enabled; + return instance->mirror.enabled; +} + +static uint8_t mf_ultralight_get_mirror_data_size(MfUltralightMirrorConf mode) { + switch(mode) { + case MfUltralightMirrorUid: + return 14; + case MfUltralightMirrorCounter: + return 6; + case MfUltralightMirrorUidCounter: + return 21; + default: + return 0; + } +} + +static uint8_t mf_ultralight_get_mirror_last_page(MfUltralightListener* instance) { + uint8_t strSize = mf_ultralight_get_mirror_data_size(instance->mirror.actual_mode); + return (instance->config->mirror_page + 1U + strSize / 4); +} + +static uint8_t mf_ultralight_get_ascii_offset(uint8_t start_page, MfUltralightListener* instance) { + uint8_t start_offset = 0; + if(instance->config->mirror.mirror_conf == MfUltralightMirrorCounter) start_offset = 15; + + uint8_t ascii_offset = start_offset; + + if(start_page > instance->config->mirror_page) + ascii_offset = (start_page - instance->config->mirror_page) * 4 - + instance->config->mirror.mirror_byte + start_offset; + + return ascii_offset; +} + +static uint8_t mf_ultralight_get_ascii_end(MfUltralightMirrorConf mode) { + return (mode == MfUltralightMirrorUid) ? 14 : 21; +} + +static uint8_t mf_ultralight_get_byte_offset( + uint8_t current_page, + const MfUltralightConfigPages* const config) { + return (current_page > config->mirror_page) ? 0 : config->mirror.mirror_byte; +} + +static void mf_ultralight_format_mirror_data( + FuriString* str, + const uint8_t* const data, + const uint8_t data_len) { + for(uint8_t i = 0; i < data_len; i++) furi_string_cat_printf(str, "%02X", data[i]); +} + +void mf_ultralight_mirror_read_prepare(uint8_t start_page, MfUltralightListener* instance) { + if(mf_ultralight_mirror_enabled(instance)) { + instance->mirror.ascii_offset = mf_ultralight_get_ascii_offset(start_page, instance); + instance->mirror.ascii_end = mf_ultralight_get_ascii_end(instance->mirror.actual_mode); + + instance->mirror.mirror_last_page = mf_ultralight_get_mirror_last_page(instance); + } +} + +void mf_ultralight_mirror_read_handler( + uint8_t mirror_page_num, + uint8_t* dest, + MfUltralightListener* instance) { + if(instance->mirror.enabled && mirror_page_num >= instance->config->mirror_page && + mirror_page_num <= instance->mirror.mirror_last_page) { + uint8_t byte_offset = mf_ultralight_get_byte_offset(mirror_page_num, instance->config); + + uint8_t ascii_offset = instance->mirror.ascii_offset; + uint8_t ascii_end = instance->mirror.ascii_end; + uint8_t* source = (uint8_t*)furi_string_get_cstr(instance->mirror.ascii_mirror_data); + for(uint8_t j = byte_offset; (j < 4) && (ascii_offset < ascii_end); j++) { + dest[j] = source[ascii_offset]; + ascii_offset++; + } + instance->mirror.ascii_offset = ascii_offset; + } +} + +void mf_ultralight_mirror_prepare_emulation(MfUltralightListener* instance) { + mf_ultralight_format_mirror_data( + instance->mirror.ascii_mirror_data, + instance->data->iso14443_3a_data->uid, + instance->data->iso14443_3a_data->uid_len); + + furi_string_push_back(instance->mirror.ascii_mirror_data, 'x'); + + mf_ultraligt_mirror_format_counter(instance); +} + +void mf_ultraligt_mirror_format_counter(MfUltralightListener* instance) { + furi_string_left( + instance->mirror.ascii_mirror_data, instance->data->iso14443_3a_data->uid_len * 2 + 1); + + uint8_t* c = instance->data->counter[2].data; + furi_string_cat_printf(instance->mirror.ascii_mirror_data, "%02X%02X%02X", c[2], c[1], c[0]); +} + +bool mf_ultralight_composite_command_in_progress(MfUltralightListener* instance) { + return (instance->composite_cmd.callback != NULL); +} + +MfUltralightCommand + mf_ultralight_composite_command_run(MfUltralightListener* instance, BitBuffer* buffer) { + MfUltralightCommand command = (instance->composite_cmd.callback)(instance, buffer); + mf_ultralight_composite_command_reset(instance); + return command; +} + +void mf_ultralight_composite_command_reset(MfUltralightListener* instance) { + instance->composite_cmd.callback = NULL; + instance->composite_cmd.data = 0; +} + +void mf_ultralight_composite_command_set_next( + MfUltralightListener* instance, + const MfUltralightListenerCommandCallback handler) { + instance->composite_cmd.callback = handler; +} + +void mf_ultralight_single_counter_try_increase(MfUltralightListener* instance) { + if(mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportSingleCounter) && + instance->config->access.nfc_cnt_en && !instance->single_counter_increased) { + if(instance->data->counter[2].counter < MF_ULTRALIGHT_MAX_CNTR_VAL) { + instance->data->counter[2].counter++; + mf_ultraligt_mirror_format_counter(instance); + } + instance->single_counter_increased = true; + } +} + +void mf_ultralight_single_counter_try_to_unlock( + MfUltralightListener* instance, + Iso14443_3aListenerEventType type) { + if(mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportSingleCounter) && + type == Iso14443_3aListenerEventTypeFieldOff) { + instance->single_counter_increased = false; + } +} + +static bool mf_ultralight_i2c_page_validator_for_sector0( + uint16_t start_page, + uint16_t end_page, + MfUltralightType type) { + UNUSED(type); + bool valid = false; + if(type == MfUltralightTypeNTAGI2CPlus1K || type == MfUltralightTypeNTAGI2CPlus2K) { + if(start_page <= 0xE9 && end_page <= 0xE9) { + valid = true; + } else if( + MF_ULTRALIGHT_I2C_PAGE_ON_SESSION_REG(start_page) && + MF_ULTRALIGHT_I2C_PAGE_ON_SESSION_REG(end_page)) { + valid = true; + } + } else if(type == MfUltralightTypeNTAGI2C1K) { + if((start_page <= 0xE2) || MF_ULTRALIGHT_PAGE_IN_BOUNDS(start_page, 0x00E8, 0x00E9)) { + valid = true; + } + } else if(type == MfUltralightTypeNTAGI2C2K) { + valid = (start_page <= 0xFF && end_page <= 0xFF); + } + + return valid; +} + +static bool mf_ultralight_i2c_page_validator_for_sector1( + uint16_t start_page, + uint16_t end_page, + MfUltralightType type) { + bool valid = false; + if(type == MfUltralightTypeNTAGI2CPlus2K) { + valid = (start_page <= 0xFF && end_page <= 0xFF); + } else if(type == MfUltralightTypeNTAGI2C2K) { + valid = (MF_ULTRALIGHT_PAGE_IN_BOUNDS(start_page, 0x00E8, 0x00E9) || (start_page <= 0xE0)); + } else if(type == MfUltralightTypeNTAGI2C1K || type == MfUltralightTypeNTAGI2CPlus1K) { + valid = false; + } + + return valid; +} + +static bool mf_ultralight_i2c_page_validator_for_sector2( + uint16_t start_page, + uint16_t end_page, + MfUltralightType type) { + UNUSED(start_page); + UNUSED(end_page); + UNUSED(type); + return false; +} + +static bool mf_ultralight_i2c_page_validator_for_sector3( + uint16_t start_page, + uint16_t end_page, + MfUltralightType type) { + UNUSED(type); + UNUSED(end_page); + return MF_ULTRALIGHT_I2C_PAGE_ON_MIRRORED_SESSION_REG(start_page); +} + +typedef bool ( + *MfUltralightI2CValidator)(uint16_t start_page, uint16_t end_page, MfUltralightType type); + +typedef uint16_t (*MfUltralightI2CPageProvider)(uint16_t page, MfUltralightType type); + +const MfUltralightI2CValidator validation_methods[] = { + mf_ultralight_i2c_page_validator_for_sector0, + mf_ultralight_i2c_page_validator_for_sector1, + mf_ultralight_i2c_page_validator_for_sector2, + mf_ultralight_i2c_page_validator_for_sector3, +}; + +bool mf_ultralight_i2c_validate_pages( + uint16_t start_page, + uint16_t end_page, + MfUltralightListener* instance) { + bool valid = false; + if(instance->sector < COUNT_OF(validation_methods)) { + MfUltralightI2CValidator validate = validation_methods[instance->sector]; + valid = validate(start_page, end_page, instance->data->type); + } + return valid; +} + +bool mf_ultralight_is_i2c_tag(MfUltralightType type) { + return type == MfUltralightTypeNTAGI2C1K || type == MfUltralightTypeNTAGI2C2K || + type == MfUltralightTypeNTAGI2CPlus1K || type == MfUltralightTypeNTAGI2CPlus2K; +} + +static uint16_t mf_ultralight_i2c_page_provider_for_sector0(uint16_t page, MfUltralightType type) { + uint8_t new_page = page; + if(type == MfUltralightTypeNTAGI2CPlus1K || type == MfUltralightTypeNTAGI2CPlus2K) { + if(page == 0x00EC) { + new_page = 234; + } else if(page == 0x00ED) { + new_page = 235; + } + } else if(type == MfUltralightTypeNTAGI2C1K) { + if(page == 0x00E8) { + new_page = 232; + } else if(page == 0x00E9) { + new_page = 233; + } + } else if(type == MfUltralightTypeNTAGI2C2K) { + new_page = page; + } + return new_page; +} + +static uint16_t mf_ultralight_i2c_page_provider_for_sector1(uint16_t page, MfUltralightType type) { + UNUSED(type); + uint16_t new_page = page; + if(type == MfUltralightTypeNTAGI2CPlus2K) new_page = page + 236; + if(type == MfUltralightTypeNTAGI2C2K) new_page = page + 256; + return new_page; +} + +static uint16_t mf_ultralight_i2c_page_provider_for_sector2(uint16_t page, MfUltralightType type) { + UNUSED(type); + return page; +} + +static uint16_t mf_ultralight_i2c_page_provider_for_sector3(uint16_t page, MfUltralightType type) { + uint16_t new_page = page; + if(type == MfUltralightTypeNTAGI2CPlus1K || type == MfUltralightTypeNTAGI2CPlus2K) { + if(page == 0x00F8) + new_page = 234; + else if(page == 0x00F9) + new_page = 235; + } else if(type == MfUltralightTypeNTAGI2C1K || type == MfUltralightTypeNTAGI2C2K) { + if(page == 0x00F8) + new_page = (type == MfUltralightTypeNTAGI2C1K) ? 227 : 481; + else if(page == 0x00F9) + new_page = (type == MfUltralightTypeNTAGI2C1K) ? 228 : 482; + } + return new_page; +} + +const MfUltralightI2CPageProvider provider_methods[] = { + mf_ultralight_i2c_page_provider_for_sector0, + mf_ultralight_i2c_page_provider_for_sector1, + mf_ultralight_i2c_page_provider_for_sector2, + mf_ultralight_i2c_page_provider_for_sector3, +}; + +uint16_t + mf_ultralight_i2c_provide_page_by_requested(uint16_t page, MfUltralightListener* instance) { + uint16_t result = page; + if(instance->sector < COUNT_OF(provider_methods)) { + MfUltralightI2CPageProvider provider = provider_methods[instance->sector]; + result = provider(page, instance->data->type); + } + return result; +} + +void mf_ultralight_static_lock_bytes_prepare(MfUltralightListener* instance) { + instance->static_lock = (uint16_t*)&instance->data->page[2].data[2]; +} + +void mf_ultralight_static_lock_bytes_write( + MfUltralightStaticLockData* const lock_bits, + uint16_t new_bits) { + uint16_t current_locks = *lock_bits; + + if(MF_ULTRALIGHT_STATIC_BIT_OTP_CC_LOCKED(current_locks)) + MF_ULTRALIGHT_BITS_CLR(new_bits, MF_ULTRALIGHT_STATIC_LOCK_L_OTP_CC_MASK); + + if(MF_ULTRALIGHT_STATIC_BITS_9_4_LOCKED(current_locks)) + MF_ULTRALIGHT_BITS_CLR(new_bits, MF_ULTRALIGHT_STATIC_LOCK_L_9_4_MASK); + + if(MF_ULTRALIGHT_STATIC_BITS_15_10_LOCKED(current_locks)) + MF_ULTRALIGHT_BITS_CLR(new_bits, MF_ULTRALIGHT_STATIC_LOCK_L_15_10_MASK); + + MF_ULTRALIGHT_BITS_SET(current_locks, new_bits); + *lock_bits = current_locks; +} + +bool mf_ultralight_static_lock_check_page( + const MfUltralightStaticLockData* const lock_bits, + uint16_t page) { + bool locked = false; + if(MF_ULTRALIGHT_PAGE_IN_BOUNDS(page, 0x0003, 0x000F)) { + uint16_t current_locks = *lock_bits; + locked = MF_ULTRALIGHT_PAGE_LOCKED(current_locks, page); + } + return locked; +} + +void mf_ultralight_capability_container_write( + MfUltralightPage* const current_page, + const uint8_t* const new_data) { + for(uint8_t i = 0; i < MF_ULTRALIGHT_PAGE_SIZE; i++) { + current_page->data[i] |= new_data[i]; + } +} + +static uint16_t mf_ultralight_dynamic_lock_page_num(const MfUltralightData* data) { + uint16_t lock_page; + if(data->type == MfUltralightTypeNTAGI2C1K) + lock_page = 226; + else if(data->type == MfUltralightTypeNTAGI2C2K) + lock_page = 480; + else + lock_page = mf_ultralight_get_config_page_num(data->type) - 1; + return lock_page; +} + +void mf_ultralight_dynamic_lock_bytes_prepare(MfUltralightListener* instance) { + if(mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportDynamicLock)) { + uint16_t lock_page = mf_ultralight_dynamic_lock_page_num(instance->data); + instance->dynamic_lock = (uint32_t*)instance->data->page[lock_page].data; + } else { + instance->dynamic_lock = NULL; + } +} + +bool mf_ultralight_is_page_dynamic_lock(const MfUltralightListener* instance, uint16_t page) { + bool is_lock = false; + if(mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportDynamicLock)) { + uint16_t linear_page = page + instance->sector * 256; + + uint16_t lock_page = mf_ultralight_dynamic_lock_page_num(instance->data); + is_lock = linear_page == lock_page; + } + return is_lock; +} + +void mf_ultralight_dynamic_lock_bytes_write( + MfUltralightDynamicLockData* const lock_bits, + uint32_t new_bits) { + furi_assert(lock_bits != NULL); + new_bits &= 0x00FFFFFF; + uint32_t current_lock = *lock_bits; + for(uint8_t i = 0; i < 8; i++) { + uint8_t bl_bit = i + 16; + + if(MF_ULTRALIGHT_BIT_ACTIVE(current_lock, bl_bit)) { + uint8_t lock_bit = i * 2; + uint32_t mask = (1U << lock_bit) | (1U << (lock_bit + 1)); + MF_ULTRALIGHT_BITS_CLR(new_bits, mask); + } + } + MF_ULTRALIGHT_BITS_SET(current_lock, new_bits); + *lock_bits = current_lock; +} + +static uint8_t mf_ultralight_dynamic_lock_granularity(MfUltralightType type) { + switch(type) { + case MfUltralightTypeUL21: + case MfUltralightTypeNTAG213: + return 2; + case MfUltralightTypeNTAG215: + case MfUltralightTypeNTAG216: + case MfUltralightTypeNTAGI2C1K: + case MfUltralightTypeNTAGI2CPlus1K: + return 16; + case MfUltralightTypeNTAGI2C2K: + case MfUltralightTypeNTAGI2CPlus2K: + return 32; + default: + return 1; + } +} + +static uint16_t mf_ultralight_get_upper_page_bound(MfUltralightType type) { + uint16_t upper_page_bound; + + if(type == MfUltralightTypeNTAGI2CPlus2K) + upper_page_bound = 511; + else if(type == MfUltralightTypeNTAGI2C2K) + upper_page_bound = 479; + else if(type == MfUltralightTypeNTAGI2C1K) + upper_page_bound = 225; + else { + upper_page_bound = mf_ultralight_get_config_page_num(type) - 2; + } + + return upper_page_bound; +} + +bool mf_ultralight_dynamic_lock_check_page(const MfUltralightListener* instance, uint16_t page) { + UNUSED(page); + bool locked = false; + uint16_t upper_page_bound = mf_ultralight_get_upper_page_bound(instance->data->type); + uint16_t linear_page = page + instance->sector * 256; + + if(mf_ultralight_support_feature(instance->features, MfUltralightFeatureSupportDynamicLock) && + MF_ULTRALIGHT_PAGE_IN_BOUNDS(linear_page, 0x0010, upper_page_bound)) { + uint8_t granularity = mf_ultralight_dynamic_lock_granularity(instance->data->type); + uint8_t bit = (linear_page - 16) / granularity; + uint16_t current_locks = *instance->dynamic_lock; + locked = MF_ULTRALIGHT_PAGE_LOCKED(current_locks, bit); + } + return locked; +} + +static bool mf_ultralight_auth_check_attempts(const MfUltralightListener* instance) { + uint8_t authlim = ((instance->data->type == MfUltralightTypeNTAGI2CPlus1K) || + (instance->data->type == MfUltralightTypeNTAGI2CPlus2K)) ? + (1U << instance->config->access.authlim) : + instance->config->access.authlim; + + return (instance->data->auth_attempts >= authlim); +} + +bool mf_ultralight_auth_limit_check_and_update(MfUltralightListener* instance, bool auth_success) { + bool card_locked = false; + + do { + if(instance->config->access.authlim == 0) break; + card_locked = mf_ultralight_auth_check_attempts(instance); + if(card_locked) break; + + if(auth_success) { + MF_ULTRALIGHT_AUTH_RESET_ATTEMPTS(instance); + } else { + MF_ULTRALIGHT_AUTH_INCREASE_ATTEMPTS(instance); + } + + card_locked = mf_ultralight_auth_check_attempts(instance); + } while(false); + + return card_locked; +} + +bool mf_ultralight_auth_check_password( + const MfUltralightAuthPassword* config_pass, + const MfUltralightAuthPassword* auth_pass) { + return memcmp(config_pass->data, auth_pass->data, sizeof(MfUltralightAuthPassword)) == 0; +} \ No newline at end of file diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener_i.h b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener_i.h new file mode 100644 index 000000000..ba448d087 --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_listener_i.h @@ -0,0 +1,123 @@ +#pragma once + +#include "mf_ultralight_listener.h" +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + MfUltralightListenerAuthStateIdle, + MfUltralightListenerAuthStateSuccess, +} MfUltralightListenerAuthState; + +typedef enum { + MfUltralightCommandNotFound, + MfUltralightCommandProcessed, + MfUltralightCommandProcessedACK, + MfUltralightCommandProcessedSilent, + MfUltralightCommandNotProcessedNAK, + MfUltralightCommandNotProcessedSilent, + MfUltralightCommandNotProcessedAuthNAK, +} MfUltralightCommand; + +typedef MfUltralightCommand ( + *MfUltralightListenerCommandCallback)(MfUltralightListener* instance, BitBuffer* buf); + +typedef uint8_t MfUltralightListenerCompositeCommandData; + +typedef struct { + MfUltralightListenerCompositeCommandData data; + MfUltralightListenerCommandCallback callback; +} MfUltralightListenerCompositeCommandContext; + +typedef struct { + uint8_t enabled; + uint8_t ascii_offset; + uint8_t ascii_end; + uint8_t mirror_last_page; + MfUltralightMirrorConf actual_mode; + FuriString* ascii_mirror_data; +} MfUltralightMirrorMode; + +typedef uint16_t MfUltralightStaticLockData; +typedef uint32_t MfUltralightDynamicLockData; + +struct MfUltralightListener { + Iso14443_3aListener* iso14443_3a_listener; + MfUltralightListenerAuthState auth_state; + MfUltralightData* data; + BitBuffer* tx_buffer; + MfUltralightFeatureSupport features; + MfUltralightConfigPages* config; + MfUltralightStaticLockData* static_lock; + MfUltralightDynamicLockData* dynamic_lock; + + NfcGenericEvent generic_event; + MfUltralightListenerEvent mfu_event; + MfUltralightListenerEventData mfu_event_data; + NfcGenericCallback callback; + uint8_t sector; + bool single_counter_increased; + MfUltralightMirrorMode mirror; + MfUltralightListenerCompositeCommandContext composite_cmd; + void* context; +}; + +void mf_ultralight_single_counter_try_increase(MfUltralightListener* instance); +void mf_ultralight_single_counter_try_to_unlock( + MfUltralightListener* instance, + Iso14443_3aListenerEventType type); + +void mf_ultralight_mirror_prepare_emulation(MfUltralightListener* instance); +void mf_ultraligt_mirror_format_counter(MfUltralightListener* instance); +void mf_ultralight_mirror_read_prepare(uint8_t start_page, MfUltralightListener* instance); +void mf_ultralight_mirror_read_handler( + uint8_t mirror_page_num, + uint8_t* dest, + MfUltralightListener* instance); + +void mf_ultralight_composite_command_set_next( + MfUltralightListener* instance, + const MfUltralightListenerCommandCallback handler); +void mf_ultralight_composite_command_reset(MfUltralightListener* instance); +bool mf_ultralight_composite_command_in_progress(MfUltralightListener* instance); +MfUltralightCommand + mf_ultralight_composite_command_run(MfUltralightListener* instance, BitBuffer* buffer); + +bool mf_ultralight_is_i2c_tag(MfUltralightType type); +bool mf_ultralight_i2c_validate_pages( + uint16_t start_page, + uint16_t end_page, + MfUltralightListener* instance); + +uint16_t + mf_ultralight_i2c_provide_page_by_requested(uint16_t page, MfUltralightListener* instance); + +void mf_ultralight_static_lock_bytes_prepare(MfUltralightListener* instance); +void mf_ultralight_static_lock_bytes_write( + MfUltralightStaticLockData* const lock_bits, + uint16_t new_bits); +bool mf_ultralight_static_lock_check_page( + const MfUltralightStaticLockData* const lock_bits, + uint16_t page); + +void mf_ultralight_capability_container_write( + MfUltralightPage* const current_page, + const uint8_t* const new_data); + +void mf_ultralight_dynamic_lock_bytes_prepare(MfUltralightListener* instance); +bool mf_ultralight_is_page_dynamic_lock(const MfUltralightListener* instance, uint16_t start_page); +void mf_ultralight_dynamic_lock_bytes_write( + MfUltralightDynamicLockData* const lock_bits, + uint32_t new_bits); +bool mf_ultralight_dynamic_lock_check_page(const MfUltralightListener* instance, uint16_t page); +bool mf_ultralight_auth_limit_check_and_update(MfUltralightListener* instance, bool auth_success); +bool mf_ultralight_auth_check_password( + const MfUltralightAuthPassword* config_pass, + const MfUltralightAuthPassword* auth_pass); +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller.c b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller.c new file mode 100644 index 000000000..bf0ced38d --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller.c @@ -0,0 +1,591 @@ +#include "mf_ultralight_poller_i.h" + +#include + +#include + +#define TAG "MfUltralightPoller" + +typedef NfcCommand (*MfUltralightPollerReadHandler)(MfUltralightPoller* instance); + +static bool mf_ultralight_poller_ntag_i2c_addr_lin_to_tag_ntag_i2c_1k( + uint16_t lin_addr, + uint8_t* sector, + uint8_t* tag, + uint8_t* pages_left) { + bool tag_calculated = false; + // 0 - 226: sector 0 + // 227 - 228: config registers + // 229 - 230: session registers + + if(lin_addr > 230) { + *pages_left = 0; + } else if(lin_addr >= 229) { + *sector = 3; + *pages_left = 2 - (lin_addr - 229); + *tag = lin_addr - 229 + 248; + tag_calculated = true; + } else if(lin_addr >= 227) { + *sector = 0; + *pages_left = 2 - (lin_addr - 227); + *tag = lin_addr - 227 + 232; + tag_calculated = true; + } else { + *sector = 0; + *pages_left = 227 - lin_addr; + *tag = lin_addr; + tag_calculated = true; + } + + return tag_calculated; +} + +static bool mf_ultralight_poller_ntag_i2c_addr_lin_to_tag_ntag_i2c_2k( + uint16_t lin_addr, + uint8_t* sector, + uint8_t* tag, + uint8_t* pages_left) { + bool tag_calculated = false; + // 0 - 255: sector 0 + // 256 - 480: sector 1 + // 481 - 482: config registers + // 483 - 484: session registers + + if(lin_addr > 484) { + *pages_left = 0; + } else if(lin_addr >= 483) { + *sector = 3; + *pages_left = 2 - (lin_addr - 483); + *tag = lin_addr - 483 + 248; + tag_calculated = true; + } else if(lin_addr >= 481) { + *sector = 1; + *pages_left = 2 - (lin_addr - 481); + *tag = lin_addr - 481 + 232; + tag_calculated = true; + } else if(lin_addr >= 256) { + *sector = 1; + *pages_left = 225 - (lin_addr - 256); + *tag = lin_addr - 256; + tag_calculated = true; + } else { + *sector = 0; + *pages_left = 256 - lin_addr; + *tag = lin_addr; + tag_calculated = true; + } + + return tag_calculated; +} + +static bool mf_ultralight_poller_ntag_i2c_addr_lin_to_tag_ntag_i2c_plus_1k( + uint16_t lin_addr, + uint8_t* sector, + uint8_t* tag, + uint8_t* pages_left) { + bool tag_calculated = false; + // 0 - 233: sector 0 + registers + // 234 - 235: session registers + + if(lin_addr > 235) { + *pages_left = 0; + } else if(lin_addr >= 234) { + *sector = 0; + *pages_left = 2 - (lin_addr - 234); + *tag = lin_addr - 234 + 236; + tag_calculated = true; + } else { + *sector = 0; + *pages_left = 234 - lin_addr; + *tag = lin_addr; + tag_calculated = true; + } + + return tag_calculated; +} + +static bool mf_ultralight_poller_ntag_i2c_addr_lin_to_tag_ntag_i2c_plus_2k( + uint16_t lin_addr, + uint8_t* sector, + uint8_t* tag, + uint8_t* pages_left) { + bool tag_calculated = false; + // 0 - 233: sector 0 + registers + // 234 - 235: session registers + // 236 - 491: sector 1 + + if(lin_addr > 491) { + *pages_left = 0; + } else if(lin_addr >= 236) { + *sector = 1; + *pages_left = 256 - (lin_addr - 236); + *tag = lin_addr - 236; + tag_calculated = true; + } else if(lin_addr >= 234) { + *sector = 0; + *pages_left = 2 - (lin_addr - 234); + *tag = lin_addr - 234 + 236; + tag_calculated = true; + } else { + *sector = 0; + *pages_left = 234 - lin_addr; + *tag = lin_addr; + tag_calculated = true; + } + + return tag_calculated; +} + +bool mf_ultralight_poller_ntag_i2c_addr_lin_to_tag( + MfUltralightPoller* instance, + uint16_t lin_addr, + uint8_t* sector, + uint8_t* tag, + uint8_t* pages_left) { + furi_assert(instance); + furi_assert(sector); + furi_assert(tag); + furi_assert(pages_left); + + bool tag_calculated = false; + + if(instance->data->type == MfUltralightTypeNTAGI2C1K) { + tag_calculated = mf_ultralight_poller_ntag_i2c_addr_lin_to_tag_ntag_i2c_1k( + lin_addr, sector, tag, pages_left); + } else if(instance->data->type == MfUltralightTypeNTAGI2C2K) { + tag_calculated = mf_ultralight_poller_ntag_i2c_addr_lin_to_tag_ntag_i2c_2k( + lin_addr, sector, tag, pages_left); + } else if(instance->data->type == MfUltralightTypeNTAGI2CPlus1K) { + tag_calculated = mf_ultralight_poller_ntag_i2c_addr_lin_to_tag_ntag_i2c_plus_1k( + lin_addr, sector, tag, pages_left); + } else if(instance->data->type == MfUltralightTypeNTAGI2CPlus2K) { + tag_calculated = mf_ultralight_poller_ntag_i2c_addr_lin_to_tag_ntag_i2c_plus_2k( + lin_addr, sector, tag, pages_left); + } + + return tag_calculated; +} + +MfUltralightPoller* mf_ultralight_poller_alloc(Iso14443_3aPoller* iso14443_3a_poller) { + furi_assert(iso14443_3a_poller); + + MfUltralightPoller* instance = malloc(sizeof(MfUltralightPoller)); + instance->iso14443_3a_poller = iso14443_3a_poller; + instance->tx_buffer = bit_buffer_alloc(MF_ULTRALIGHT_MAX_BUFF_SIZE); + instance->rx_buffer = bit_buffer_alloc(MF_ULTRALIGHT_MAX_BUFF_SIZE); + instance->data = mf_ultralight_alloc(); + + instance->mfu_event.data = &instance->mfu_event_data; + + instance->general_event.protocol = NfcProtocolMfUltralight; + instance->general_event.event_data = &instance->mfu_event; + instance->general_event.instance = instance; + + return instance; +} + +void mf_ultralight_poller_free(MfUltralightPoller* instance) { + furi_assert(instance); + furi_assert(instance->data); + furi_assert(instance->tx_buffer); + furi_assert(instance->rx_buffer); + + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + mf_ultralight_free(instance->data); + free(instance); +} + +static void mf_ultralight_poller_set_callback( + MfUltralightPoller* instance, + NfcGenericCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +const MfUltralightData* mf_ultralight_poller_get_data(MfUltralightPoller* instance) { + furi_assert(instance); + + return instance->data; +} + +static NfcCommand mf_ultralight_poller_handler_idle(MfUltralightPoller* instance) { + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + iso14443_3a_copy( + instance->data->iso14443_3a_data, + iso14443_3a_poller_get_data(instance->iso14443_3a_poller)); + instance->counters_read = 0; + instance->counters_total = 3; + instance->tearing_flag_read = 0; + instance->tearing_flag_total = 3; + instance->pages_read = 0; + instance->state = MfUltralightPollerStateReadVersion; + + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_read_version(MfUltralightPoller* instance) { + instance->error = mf_ultralight_poller_async_read_version(instance, &instance->data->version); + if(instance->error == MfUltralightErrorNone) { + FURI_LOG_D(TAG, "Read version success"); + instance->data->type = mf_ultralight_get_type_by_version(&instance->data->version); + instance->state = MfUltralightPollerStateGetFeatureSet; + } else { + FURI_LOG_D(TAG, "Didn't response. Check Ultralight C"); + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + instance->state = MfUltralightPollerStateDetectMfulC; + } + + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_check_ultralight_c(MfUltralightPoller* instance) { + instance->error = mf_ultralight_poller_async_authenticate(instance); + if(instance->error == MfUltralightErrorNone) { + FURI_LOG_D(TAG, "Ultralight C detected"); + instance->data->type = MfUltralightTypeMfulC; + instance->state = MfUltralightPollerStateGetFeatureSet; + } else { + FURI_LOG_D(TAG, "Didn't response. Check NTAG 203"); + instance->state = MfUltralightPollerStateDetectNtag203; + } + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_check_ntag_203(MfUltralightPoller* instance) { + MfUltralightPageReadCommandData data = {}; + instance->error = mf_ultralight_poller_async_read_page(instance, 41, &data); + if(instance->error == MfUltralightErrorNone) { + FURI_LOG_D(TAG, "NTAG203 detected"); + instance->data->type = MfUltralightTypeNTAG203; + } else { + FURI_LOG_D(TAG, "Original Ultralight detected"); + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + instance->data->type = MfUltralightTypeUnknown; + } + instance->state = MfUltralightPollerStateGetFeatureSet; + + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_get_feature_set(MfUltralightPoller* instance) { + instance->feature_set = mf_ultralight_get_feature_support_set(instance->data->type); + instance->pages_total = mf_ultralight_get_pages_total(instance->data->type); + instance->data->pages_total = instance->pages_total; + FURI_LOG_D( + TAG, + "%s detected. Total pages: %d", + mf_ultralight_get_device_name(instance->data, NfcDeviceNameTypeFull), + instance->pages_total); + + instance->state = MfUltralightPollerStateReadSignature; + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_read_signature(MfUltralightPoller* instance) { + MfUltralightPollerState next_state = MfUltralightPollerStateAuth; + if(mf_ultralight_support_feature( + instance->feature_set, MfUltralightFeatureSupportReadSignature)) { + FURI_LOG_D(TAG, "Reading signature"); + instance->error = + mf_ultralight_poller_async_read_signature(instance, &instance->data->signature); + if(instance->error != MfUltralightErrorNone) { + FURI_LOG_D(TAG, "Read signature failed"); + next_state = MfUltralightPollerStateReadFailed; + } + } else { + FURI_LOG_D(TAG, "Skip reading signature"); + } + instance->state = next_state; + + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_read_counters(MfUltralightPoller* instance) { + do { + if(!mf_ultralight_support_feature( + instance->feature_set, MfUltralightFeatureSupportReadCounter) || + !mf_ultralight_is_counter_configured(instance->data)) { + FURI_LOG_D(TAG, "Skip reading counters"); + instance->state = MfUltralightPollerStateReadTearingFlags; + break; + } + + MfUltralightConfigPages* config = NULL; + mf_ultralight_get_config_page(instance->data, &config); + + if(config->access.nfc_cnt_pwd_prot && !instance->auth_context.auth_success) { + FURI_LOG_D(TAG, "Counter reading is protected with password"); + instance->state = MfUltralightPollerStateReadTearingFlags; + break; + } + + if(instance->counters_read == instance->counters_total) { + instance->state = MfUltralightPollerStateReadTearingFlags; + break; + } + + if(mf_ultralight_support_feature( + instance->feature_set, MfUltralightFeatureSupportSingleCounter)) { + instance->counters_read = 2; + } + + FURI_LOG_D(TAG, "Reading counter %d", instance->counters_read); + instance->error = mf_ultralight_poller_async_read_counter( + instance, instance->counters_read, &instance->data->counter[instance->counters_read]); + if(instance->error != MfUltralightErrorNone) { + FURI_LOG_D(TAG, "Failed to read %d counter", instance->counters_read); + instance->state = MfUltralightPollerStateReadTearingFlags; + } else { + instance->counters_read++; + } + + } while(false); + + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_read_tearing_flags(MfUltralightPoller* instance) { + if(mf_ultralight_support_feature( + instance->feature_set, + MfUltralightFeatureSupportCheckTearingFlag | MfUltralightFeatureSupportSingleCounter)) { + if(instance->tearing_flag_read == instance->tearing_flag_total) { + instance->state = MfUltralightPollerStateTryDefaultPass; + } else { + bool single_counter = mf_ultralight_support_feature( + instance->feature_set, MfUltralightFeatureSupportSingleCounter); + if(single_counter) instance->tearing_flag_read = 2; + + FURI_LOG_D(TAG, "Reading tearing flag %d", instance->tearing_flag_read); + instance->error = mf_ultralight_poller_async_read_tearing_flag( + instance, + instance->tearing_flag_read, + &instance->data->tearing_flag[instance->tearing_flag_read]); + if((instance->error == MfUltralightErrorProtocol) && single_counter) { + instance->tearing_flag_read++; + } else if(instance->error != MfUltralightErrorNone) { + FURI_LOG_D(TAG, "Reading tearing flag %d failed", instance->tearing_flag_read); + instance->state = MfUltralightPollerStateTryDefaultPass; + } else { + instance->tearing_flag_read++; + } + } + } else { + FURI_LOG_D(TAG, "Skip reading tearing flags"); + instance->state = MfUltralightPollerStateTryDefaultPass; + } + + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_auth(MfUltralightPoller* instance) { + NfcCommand command = NfcCommandContinue; + if(mf_ultralight_support_feature( + instance->feature_set, MfUltralightFeatureSupportPasswordAuth)) { + instance->mfu_event.type = MfUltralightPollerEventTypeAuthRequest; + + command = instance->callback(instance->general_event, instance->context); + if(!instance->mfu_event.data->auth_context.skip_auth) { + instance->auth_context.password = instance->mfu_event.data->auth_context.password; + uint32_t pass = nfc_util_bytes2num( + instance->auth_context.password.data, sizeof(MfUltralightAuthPassword)); + FURI_LOG_D(TAG, "Trying to authenticate with password %08lX", pass); + instance->error = + mf_ultralight_poller_async_auth_pwd(instance, &instance->auth_context); + if(instance->error == MfUltralightErrorNone) { + FURI_LOG_D(TAG, "Auth success"); + instance->auth_context.auth_success = true; + instance->mfu_event.data->auth_context = instance->auth_context; + instance->mfu_event.type = MfUltralightPollerEventTypeAuthSuccess; + command = instance->callback(instance->general_event, instance->context); + } else { + FURI_LOG_D(TAG, "Auth failed"); + instance->auth_context.auth_success = false; + instance->mfu_event.type = MfUltralightPollerEventTypeAuthFailed; + command = instance->callback(instance->general_event, instance->context); + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + } + } + } + instance->state = MfUltralightPollerStateReadPages; + + return command; +} + +static NfcCommand mf_ultralight_poller_handler_read_pages(MfUltralightPoller* instance) { + MfUltralightPageReadCommandData data = {}; + uint16_t start_page = instance->pages_read; + if(MF_ULTRALIGHT_IS_NTAG_I2C(instance->data->type)) { + uint8_t tag = 0; + uint8_t sector = 0; + uint8_t pages_left = 0; + if(mf_ultralight_poller_ntag_i2c_addr_lin_to_tag( + instance, start_page, §or, &tag, &pages_left)) { + instance->error = + mf_ultralight_poller_async_read_page_from_sector(instance, sector, tag, &data); + } else { + FURI_LOG_D(TAG, "Failed to calculate sector and tag from %d page", start_page); + instance->error = MfUltralightErrorProtocol; + } + } else { + instance->error = mf_ultralight_poller_async_read_page(instance, start_page, &data); + } + + if(instance->error == MfUltralightErrorNone) { + for(size_t i = 0; i < 4; i++) { + if(start_page + i < instance->pages_total) { + FURI_LOG_D(TAG, "Read page %d success", start_page + i); + instance->data->page[start_page + i] = data.page[i]; + instance->pages_read++; + instance->data->pages_read = instance->pages_read; + } + } + if(instance->pages_read == instance->pages_total) { + instance->state = MfUltralightPollerStateReadCounters; + } + } else { + FURI_LOG_D(TAG, "Read page %d failed", instance->pages_read); + if(instance->pages_read) { + instance->state = MfUltralightPollerStateReadCounters; + } else { + instance->state = MfUltralightPollerStateReadFailed; + } + } + + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_try_default_pass(MfUltralightPoller* instance) { + do { + if(!mf_ultralight_support_feature( + instance->feature_set, MfUltralightFeatureSupportPasswordAuth)) + break; + + MfUltralightConfigPages* config = NULL; + mf_ultralight_get_config_page(instance->data, &config); + if(instance->auth_context.auth_success) { + config->password = instance->auth_context.password; + config->pack = instance->auth_context.pack; + } else if(config->access.authlim == 0) { + FURI_LOG_D(TAG, "No limits in authentication. Trying default password"); + nfc_util_num2bytes( + MF_ULTRALIGHT_DEFAULT_PASSWORD, + sizeof(MfUltralightAuthPassword), + instance->auth_context.password.data); + instance->error = + mf_ultralight_poller_async_auth_pwd(instance, &instance->auth_context); + if(instance->error == MfUltralightErrorNone) { + FURI_LOG_D(TAG, "Default password detected"); + nfc_util_num2bytes( + MF_ULTRALIGHT_DEFAULT_PASSWORD, + sizeof(MfUltralightAuthPassword), + config->password.data); + config->pack = instance->auth_context.pack; + } + } + + if(instance->pages_read != instance->pages_total) { + // Probably password protected, fix AUTH0 and PROT so before AUTH0 + // can be written and since AUTH0 won't be readable, like on the + // original card + config->auth0 = instance->pages_read; + config->access.prot = true; + } + } while(false); + + instance->state = MfUltralightPollerStateReadSuccess; + return NfcCommandContinue; +} + +static NfcCommand mf_ultralight_poller_handler_read_fail(MfUltralightPoller* instance) { + FURI_LOG_D(TAG, "Read Failed"); + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + instance->mfu_event.data->error = instance->error; + NfcCommand command = instance->callback(instance->general_event, instance->context); + instance->state = MfUltralightPollerStateIdle; + return command; +} + +static NfcCommand mf_ultralight_poller_handler_read_success(MfUltralightPoller* instance) { + FURI_LOG_D(TAG, "Read success"); + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + instance->mfu_event.type = MfUltralightPollerEventTypeReadSuccess; + NfcCommand command = instance->callback(instance->general_event, instance->context); + return command; +} + +static const MfUltralightPollerReadHandler + mf_ultralight_poller_read_handler[MfUltralightPollerStateNum] = { + [MfUltralightPollerStateIdle] = mf_ultralight_poller_handler_idle, + [MfUltralightPollerStateReadVersion] = mf_ultralight_poller_handler_read_version, + [MfUltralightPollerStateDetectMfulC] = mf_ultralight_poller_handler_check_ultralight_c, + [MfUltralightPollerStateDetectNtag203] = mf_ultralight_poller_handler_check_ntag_203, + [MfUltralightPollerStateGetFeatureSet] = mf_ultralight_poller_handler_get_feature_set, + [MfUltralightPollerStateReadSignature] = mf_ultralight_poller_handler_read_signature, + [MfUltralightPollerStateReadCounters] = mf_ultralight_poller_handler_read_counters, + [MfUltralightPollerStateReadTearingFlags] = + mf_ultralight_poller_handler_read_tearing_flags, + [MfUltralightPollerStateAuth] = mf_ultralight_poller_handler_auth, + [MfUltralightPollerStateTryDefaultPass] = mf_ultralight_poller_handler_try_default_pass, + [MfUltralightPollerStateReadPages] = mf_ultralight_poller_handler_read_pages, + [MfUltralightPollerStateReadFailed] = mf_ultralight_poller_handler_read_fail, + [MfUltralightPollerStateReadSuccess] = mf_ultralight_poller_handler_read_success, + +}; + +static NfcCommand mf_ultralight_poller_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + + MfUltralightPoller* instance = context; + furi_assert(instance->callback); + + const Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + + NfcCommand command = NfcCommandContinue; + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + command = mf_ultralight_poller_read_handler[instance->state](instance); + } else if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeError) { + instance->mfu_event.type = MfUltralightPollerEventTypeReadFailed; + command = instance->callback(instance->general_event, instance->context); + } + + return command; +} + +static bool mf_ultralight_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + + bool protocol_detected = false; + MfUltralightPoller* instance = context; + const Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + MfUltralightPageReadCommandData read_page_cmd_data = {}; + MfUltralightError error = + mf_ultralight_poller_async_read_page(instance, 0, &read_page_cmd_data); + protocol_detected = (error == MfUltralightErrorNone); + iso14443_3a_poller_halt(instance->iso14443_3a_poller); + } + + return protocol_detected; +} + +const NfcPollerBase mf_ultralight_poller = { + .alloc = (NfcPollerAlloc)mf_ultralight_poller_alloc, + .free = (NfcPollerFree)mf_ultralight_poller_free, + .set_callback = (NfcPollerSetCallback)mf_ultralight_poller_set_callback, + .run = (NfcPollerRun)mf_ultralight_poller_run, + .detect = (NfcPollerDetect)mf_ultralight_poller_detect, + .get_data = (NfcPollerGetData)mf_ultralight_poller_get_data, +}; diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller.h b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller.h new file mode 100644 index 000000000..2d4ef33ea --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller.h @@ -0,0 +1,41 @@ +#pragma once + +#include "mf_ultralight.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct MfUltralightPoller MfUltralightPoller; + +typedef enum { + MfUltralightPollerEventTypeAuthRequest, + MfUltralightPollerEventTypeAuthSuccess, + MfUltralightPollerEventTypeAuthFailed, + MfUltralightPollerEventTypeReadSuccess, + MfUltralightPollerEventTypeReadFailed, +} MfUltralightPollerEventType; + +typedef struct { + MfUltralightAuthPassword password; + MfUltralightAuthPack pack; + bool auth_success; + bool skip_auth; +} MfUltralightPollerAuthContext; + +typedef struct { + union { + MfUltralightPollerAuthContext auth_context; + MfUltralightError error; + }; +} MfUltralightPollerEventData; + +typedef struct { + MfUltralightPollerEventType type; + MfUltralightPollerEventData* data; +} MfUltralightPollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_defs.h b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_defs.h new file mode 100644 index 000000000..80b0d7b6e --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcPollerBase mf_ultralight_poller; diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_i.c b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_i.c new file mode 100644 index 000000000..795b03e65 --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_i.c @@ -0,0 +1,308 @@ +#include "mf_ultralight_poller_i.h" + +#include + +#define TAG "MfUltralightPoller" + +MfUltralightError mf_ultralight_process_error(Iso14443_3aError error) { + MfUltralightError ret = MfUltralightErrorNone; + + switch(error) { + case Iso14443_3aErrorNone: + ret = MfUltralightErrorNone; + break; + case Iso14443_3aErrorNotPresent: + ret = MfUltralightErrorNotPresent; + break; + case Iso14443_3aErrorColResFailed: + case Iso14443_3aErrorCommunication: + case Iso14443_3aErrorWrongCrc: + ret = MfUltralightErrorProtocol; + break; + case Iso14443_3aErrorTimeout: + ret = MfUltralightErrorTimeout; + break; + default: + ret = MfUltralightErrorProtocol; + break; + } + + return ret; +} + +MfUltralightError mf_ultralight_poller_async_auth_pwd( + MfUltralightPoller* instance, + MfUltralightPollerAuthContext* data) { + uint8_t auth_cmd[5] = {MF_ULTRALIGHT_CMD_PWD_AUTH}; //-V1009 + memccpy(&auth_cmd[1], data->password.data, 0, MF_ULTRALIGHT_AUTH_PASSWORD_SIZE); + bit_buffer_copy_bytes(instance->tx_buffer, auth_cmd, sizeof(auth_cmd)); + + MfUltralightError ret = MfUltralightErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + do { + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_ultralight_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != MF_ULTRALIGHT_AUTH_PACK_SIZE) { + ret = MfUltralightErrorAuth; + break; + } + bit_buffer_write_bytes(instance->rx_buffer, data->pack.data, MF_ULTRALIGHT_AUTH_PACK_SIZE); + } while(false); + + return ret; +} + +MfUltralightError mf_ultralight_poller_async_authenticate(MfUltralightPoller* instance) { + uint8_t auth_cmd[2] = {MF_ULTRALIGHT_CMD_AUTH, 0x00}; + bit_buffer_copy_bytes(instance->tx_buffer, auth_cmd, sizeof(auth_cmd)); + + MfUltralightError ret = MfUltralightErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + do { + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_ultralight_process_error(error); + break; + } + if((bit_buffer_get_size_bytes(instance->rx_buffer) != MF_ULTRALIGHT_AUTH_RESPONSE_SIZE) && + (bit_buffer_get_byte(instance->rx_buffer, 0) != 0xAF)) { + ret = MfUltralightErrorAuth; + break; + } + //Save encrypted PICC random number RndB here if needed + } while(false); + + return ret; +} + +MfUltralightError mf_ultralight_poller_async_read_page_from_sector( + MfUltralightPoller* instance, + uint8_t sector, + uint8_t tag, + MfUltralightPageReadCommandData* data) { + MfUltralightError ret = MfUltralightErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + const uint8_t select_sector_cmd[2] = {MF_ULTRALIGHT_CMD_SECTOR_SELECT, 0xff}; + bit_buffer_copy_bytes(instance->tx_buffer, select_sector_cmd, sizeof(select_sector_cmd)); + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorWrongCrc) { + FURI_LOG_D(TAG, "Failed to issue sector select command"); + ret = mf_ultralight_process_error(error); + break; + } + + const uint8_t read_sector_cmd[4] = {sector, 0x00, 0x00, 0x00}; + bit_buffer_copy_bytes(instance->tx_buffer, read_sector_cmd, sizeof(read_sector_cmd)); + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorTimeout) { + // This is NOT a typo! The tag ACKs by not sending a response within 1ms. + FURI_LOG_D(TAG, "Sector %u select NAK'd", sector); + ret = MfUltralightErrorProtocol; + break; + } + + ret = mf_ultralight_poller_async_read_page(instance, tag, data); + } while(false); + + return ret; +} + +MfUltralightError mf_ultralight_poller_async_read_page( + MfUltralightPoller* instance, + uint8_t start_page, + MfUltralightPageReadCommandData* data) { + MfUltralightError ret = MfUltralightErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t read_page_cmd[2] = {MF_ULTRALIGHT_CMD_READ_PAGE, start_page}; + bit_buffer_copy_bytes(instance->tx_buffer, read_page_cmd, sizeof(read_page_cmd)); + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_ultralight_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != + sizeof(MfUltralightPageReadCommandData)) { + ret = MfUltralightErrorProtocol; + break; + } + bit_buffer_write_bytes(instance->rx_buffer, data, sizeof(MfUltralightPageReadCommandData)); + } while(false); + + return ret; +} + +MfUltralightError mf_ultralight_poller_async_write_page( + MfUltralightPoller* instance, + uint8_t page, + MfUltralightPage* data) { + MfUltralightError ret = MfUltralightErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t write_page_cmd[MF_ULTRALIGHT_PAGE_SIZE + 2] = {MF_ULTRALIGHT_CMD_WRITE_PAGE, page}; + memcpy(&write_page_cmd[2], data->data, MF_ULTRALIGHT_PAGE_SIZE); + bit_buffer_copy_bytes(instance->tx_buffer, write_page_cmd, sizeof(write_page_cmd)); + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorWrongCrc) { + ret = mf_ultralight_process_error(error); + break; + } + if(bit_buffer_get_size(instance->rx_buffer) != 4) { + ret = MfUltralightErrorProtocol; + break; + } + if(!bit_buffer_starts_with_byte(instance->rx_buffer, MF_ULTRALIGHT_CMD_ACK)) { + ret = MfUltralightErrorProtocol; + break; + } + } while(false); + + return ret; +} + +MfUltralightError mf_ultralight_poller_async_read_version( + MfUltralightPoller* instance, + MfUltralightVersion* data) { + MfUltralightError ret = MfUltralightErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + const uint8_t get_version_cmd = MF_ULTRALIGHT_CMD_GET_VERSION; + bit_buffer_copy_bytes(instance->tx_buffer, &get_version_cmd, sizeof(get_version_cmd)); + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_ultralight_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != sizeof(MfUltralightVersion)) { + FURI_LOG_I( + TAG, "Read Version failed: %zu", bit_buffer_get_size_bytes(instance->rx_buffer)); + ret = MfUltralightErrorProtocol; + break; + } + bit_buffer_write_bytes(instance->rx_buffer, data, sizeof(MfUltralightVersion)); + } while(false); + + return ret; +} + +MfUltralightError mf_ultralight_poller_async_read_signature( + MfUltralightPoller* instance, + MfUltralightSignature* data) { + MfUltralightError ret = MfUltralightErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + const uint8_t read_signature_cmd[2] = {MF_ULTRALIGHT_CMD_READ_SIG, 0x00}; + bit_buffer_copy_bytes(instance->tx_buffer, read_signature_cmd, sizeof(read_signature_cmd)); + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_ultralight_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != sizeof(MfUltralightSignature)) { + ret = MfUltralightErrorProtocol; + break; + } + bit_buffer_write_bytes(instance->rx_buffer, data, sizeof(MfUltralightSignature)); + } while(false); + + return ret; +} + +MfUltralightError mf_ultralight_poller_async_read_counter( + MfUltralightPoller* instance, + uint8_t counter_num, + MfUltralightCounter* data) { + MfUltralightError ret = MfUltralightErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t read_counter_cmd[2] = {MF_ULTRALIGHT_CMD_READ_CNT, counter_num}; + bit_buffer_copy_bytes(instance->tx_buffer, read_counter_cmd, sizeof(read_counter_cmd)); + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_ultralight_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != MF_ULTRALIGHT_COUNTER_SIZE) { + ret = MfUltralightErrorProtocol; + break; + } + bit_buffer_write_bytes(instance->rx_buffer, data->data, MF_ULTRALIGHT_COUNTER_SIZE); + } while(false); + + return ret; +} + +MfUltralightError mf_ultralight_poller_async_read_tearing_flag( + MfUltralightPoller* instance, + uint8_t tearing_falg_num, + MfUltralightTearingFlag* data) { + MfUltralightError ret = MfUltralightErrorNone; + Iso14443_3aError error = Iso14443_3aErrorNone; + + do { + uint8_t check_tearing_cmd[2] = {MF_ULTRALIGHT_CMD_CHECK_TEARING, tearing_falg_num}; + bit_buffer_copy_bytes(instance->tx_buffer, check_tearing_cmd, sizeof(check_tearing_cmd)); + error = iso14443_3a_poller_send_standard_frame( + instance->iso14443_3a_poller, + instance->tx_buffer, + instance->rx_buffer, + MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC); + if(error != Iso14443_3aErrorNone) { + ret = mf_ultralight_process_error(error); + break; + } + if(bit_buffer_get_size_bytes(instance->rx_buffer) != sizeof(MfUltralightTearingFlag)) { + ret = MfUltralightErrorProtocol; + break; + } + bit_buffer_write_bytes(instance->rx_buffer, data, sizeof(MfUltralightTearingFlag)); + } while(false); + + return ret; +} diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_i.h b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_i.h new file mode 100644 index 000000000..13490cf1a --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_i.h @@ -0,0 +1,148 @@ +#pragma once + +#include "mf_ultralight_poller.h" +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define MF_ULTRALIGHT_POLLER_STANDARD_FWT_FC (60000) +#define MF_ULTRALIGHT_MAX_BUFF_SIZE (64) + +#define MF_ULTRALIGHT_DEFAULT_PASSWORD (0xffffffffUL) + +#define MF_ULTRALIGHT_IS_NTAG_I2C(type) \ + (((type) == MfUltralightTypeNTAGI2C1K) || ((type) == MfUltralightTypeNTAGI2C2K) || \ + ((type) == MfUltralightTypeNTAGI2CPlus1K) || ((type) == MfUltralightTypeNTAGI2CPlus2K)) + +typedef struct { + MfUltralightPage page; + uint8_t page_to_write; +} MfUltralightPollerWritePageCommand; + +typedef struct { + MfUltralightPageReadCommandData data; + uint8_t start_page; +} MfUltralightPollerReadPageCommand; + +typedef struct { + MfUltralightCounter data; + uint8_t counter_num; +} MfUltralightPollerReadCounterCommand; + +typedef struct { + MfUltralightTearingFlag data; + uint8_t tearing_flag_num; +} MfUltralightPollerReadTearingFlagCommand; + +typedef union { + MfUltralightPollerWritePageCommand write_cmd; + MfUltralightPollerReadPageCommand read_cmd; + MfUltralightVersion version; + MfUltralightSignature signature; + MfUltralightPollerReadCounterCommand counter_cmd; + MfUltralightPollerReadTearingFlagCommand tearing_flag_cmd; + MfUltralightData* data; +} MfUltralightPollerContextData; + +typedef enum { + MfUltralightPollerStateIdle, + MfUltralightPollerStateReadVersion, + MfUltralightPollerStateDetectMfulC, + MfUltralightPollerStateDetectNtag203, + MfUltralightPollerStateGetFeatureSet, + MfUltralightPollerStateReadSignature, + MfUltralightPollerStateReadCounters, + MfUltralightPollerStateReadTearingFlags, + MfUltralightPollerStateAuth, + MfUltralightPollerStateReadPages, + MfUltralightPollerStateTryDefaultPass, + MfUltralightPollerStateReadFailed, + MfUltralightPollerStateReadSuccess, + + MfUltralightPollerStateNum, +} MfUltralightPollerState; + +struct MfUltralightPoller { + Iso14443_3aPoller* iso14443_3a_poller; + MfUltralightPollerState state; + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + MfUltralightData* data; + MfUltralightPollerAuthContext auth_context; + uint32_t feature_set; + uint16_t pages_read; + uint16_t pages_total; + uint8_t counters_read; + uint8_t counters_total; + uint8_t tearing_flag_read; + uint8_t tearing_flag_total; + MfUltralightError error; + + NfcGenericEvent general_event; + MfUltralightPollerEvent mfu_event; + MfUltralightPollerEventData mfu_event_data; + NfcGenericCallback callback; + void* context; +}; + +MfUltralightError mf_ultralight_process_error(Iso14443_3aError error); + +MfUltralightPoller* mf_ultralight_poller_alloc(Iso14443_3aPoller* iso14443_3a_poller); + +void mf_ultralight_poller_free(MfUltralightPoller* instance); + +const MfUltralightData* mf_ultralight_poller_get_data(MfUltralightPoller* instance); + +bool mf_ultralight_poller_ntag_i2c_addr_lin_to_tag( + MfUltralightPoller* instance, + uint16_t lin_addr, + uint8_t* sector, + uint8_t* tag, + uint8_t* pages_left); + +MfUltralightError mf_ultralight_poller_async_auth_pwd( + MfUltralightPoller* instance, + MfUltralightPollerAuthContext* data); + +MfUltralightError mf_ultralight_poller_async_authenticate(MfUltralightPoller* instance); + +MfUltralightError mf_ultralight_poller_async_read_page( + MfUltralightPoller* instance, + uint8_t start_page, + MfUltralightPageReadCommandData* data); + +MfUltralightError mf_ultralight_poller_async_read_page_from_sector( + MfUltralightPoller* instance, + uint8_t sector, + uint8_t tag, + MfUltralightPageReadCommandData* data); + +MfUltralightError mf_ultralight_poller_async_write_page( + MfUltralightPoller* instance, + uint8_t page, + MfUltralightPage* data); + +MfUltralightError mf_ultralight_poller_async_read_version( + MfUltralightPoller* instance, + MfUltralightVersion* data); + +MfUltralightError mf_ultralight_poller_async_read_signature( + MfUltralightPoller* instance, + MfUltralightSignature* data); + +MfUltralightError mf_ultralight_poller_async_read_counter( + MfUltralightPoller* instance, + uint8_t counter_num, + MfUltralightCounter* data); + +MfUltralightError mf_ultralight_poller_async_read_tearing_flag( + MfUltralightPoller* instance, + uint8_t tearing_falg_num, + MfUltralightTearingFlag* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_sync_api.c b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_sync_api.c new file mode 100644 index 000000000..739df597d --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_sync_api.c @@ -0,0 +1,287 @@ +#include "mf_ultralight_poller_i.h" + +#include + +#include + +#define MF_ULTRALIGHT_POLLER_COMPLETE_EVENT (1UL << 0) + +typedef enum { + MfUltralightPollerCmdTypeReadPage, + MfUltralightPollerCmdTypeWritePage, + MfUltralightPollerCmdTypeReadVersion, + MfUltralightPollerCmdTypeReadSignature, + MfUltralightPollerCmdTypeReadCounter, + MfUltralightPollerCmdTypeReadTearingFlag, + + MfUltralightPollerCmdTypeNum, +} MfUltralightPollerCmdType; + +typedef struct { + MfUltralightPollerCmdType cmd_type; + FuriThreadId thread_id; + MfUltralightError error; + MfUltralightPollerContextData data; +} MfUltralightPollerContext; + +typedef MfUltralightError (*MfUltralightPollerCmdHandler)( + MfUltralightPoller* poller, + MfUltralightPollerContextData* data); + +MfUltralightError mf_ultralight_poller_read_page_handler( + MfUltralightPoller* poller, + MfUltralightPollerContextData* data) { + return mf_ultralight_poller_async_read_page( + poller, data->read_cmd.start_page, &data->read_cmd.data); +} + +MfUltralightError mf_ultralight_poller_write_page_handler( + MfUltralightPoller* poller, + MfUltralightPollerContextData* data) { + return mf_ultralight_poller_async_write_page( + poller, data->write_cmd.page_to_write, &data->write_cmd.page); +} + +MfUltralightError mf_ultralight_poller_read_version_handler( + MfUltralightPoller* poller, + MfUltralightPollerContextData* data) { + return mf_ultralight_poller_async_read_version(poller, &data->version); +} + +MfUltralightError mf_ultralight_poller_read_signature_handler( + MfUltralightPoller* poller, + MfUltralightPollerContextData* data) { + return mf_ultralight_poller_async_read_signature(poller, &data->signature); +} + +MfUltralightError mf_ultralight_poller_read_counter_handler( + MfUltralightPoller* poller, + MfUltralightPollerContextData* data) { + return mf_ultralight_poller_async_read_counter( + poller, data->counter_cmd.counter_num, &data->counter_cmd.data); +} + +MfUltralightError mf_ultralight_poller_read_tearing_flag_handler( + MfUltralightPoller* poller, + MfUltralightPollerContextData* data) { + return mf_ultralight_poller_async_read_tearing_flag( + poller, data->tearing_flag_cmd.tearing_flag_num, &data->tearing_flag_cmd.data); +} + +static const MfUltralightPollerCmdHandler + mf_ultralight_poller_cmd_handlers[MfUltralightPollerCmdTypeNum] = { + [MfUltralightPollerCmdTypeReadPage] = mf_ultralight_poller_read_page_handler, + [MfUltralightPollerCmdTypeWritePage] = mf_ultralight_poller_write_page_handler, + [MfUltralightPollerCmdTypeReadVersion] = mf_ultralight_poller_read_version_handler, + [MfUltralightPollerCmdTypeReadSignature] = mf_ultralight_poller_read_signature_handler, + [MfUltralightPollerCmdTypeReadCounter] = mf_ultralight_poller_read_counter_handler, + [MfUltralightPollerCmdTypeReadTearingFlag] = + mf_ultralight_poller_read_tearing_flag_handler, +}; + +static NfcCommand mf_ultralight_poller_cmd_callback(NfcGenericEvent event, void* context) { + furi_assert(event.instance); + furi_assert(event.protocol == NfcProtocolIso14443_3a); + furi_assert(event.event_data); + furi_assert(context); + + MfUltralightPollerContext* poller_context = context; + Iso14443_3aPollerEvent* iso14443_3a_event = event.event_data; + Iso14443_3aPoller* iso14443_3a_poller = event.instance; + MfUltralightPoller* mfu_poller = mf_ultralight_poller_alloc(iso14443_3a_poller); + + if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeReady) { + poller_context->error = mf_ultralight_poller_cmd_handlers[poller_context->cmd_type]( + mfu_poller, &poller_context->data); + } else if(iso14443_3a_event->type == Iso14443_3aPollerEventTypeError) { + poller_context->error = mf_ultralight_process_error(iso14443_3a_event->data->error); + } + + furi_thread_flags_set(poller_context->thread_id, MF_ULTRALIGHT_POLLER_COMPLETE_EVENT); + + mf_ultralight_poller_free(mfu_poller); + + return NfcCommandStop; +} + +static MfUltralightError + mf_ultralight_poller_cmd_execute(Nfc* nfc, MfUltralightPollerContext* poller_ctx) { + furi_assert(poller_ctx->cmd_type < MfUltralightPollerCmdTypeNum); + + poller_ctx->thread_id = furi_thread_get_current_id(); + + NfcPoller* poller = nfc_poller_alloc(nfc, NfcProtocolIso14443_3a); + nfc_poller_start(poller, mf_ultralight_poller_cmd_callback, poller_ctx); + furi_thread_flags_wait(MF_ULTRALIGHT_POLLER_COMPLETE_EVENT, FuriFlagWaitAny, FuriWaitForever); + furi_thread_flags_clear(MF_ULTRALIGHT_POLLER_COMPLETE_EVENT); + + nfc_poller_stop(poller); + nfc_poller_free(poller); + + return poller_ctx->error; +} + +MfUltralightError mf_ultralight_poller_read_page(Nfc* nfc, uint16_t page, MfUltralightPage* data) { + furi_assert(nfc); + furi_assert(data); + + MfUltralightPollerContext poller_context = { + .cmd_type = MfUltralightPollerCmdTypeReadPage, + .data.read_cmd.start_page = page, + }; + + MfUltralightError error = mf_ultralight_poller_cmd_execute(nfc, &poller_context); + + if(error == MfUltralightErrorNone) { + *data = poller_context.data.read_cmd.data.page[0]; + } + + return error; +} + +MfUltralightError + mf_ultralight_poller_write_page(Nfc* nfc, uint16_t page, MfUltralightPage* data) { + furi_assert(nfc); + furi_assert(data); + + MfUltralightPollerContext poller_context = { + .cmd_type = MfUltralightPollerCmdTypeWritePage, + .data.write_cmd = + { + .page_to_write = page, + .page = *data, + }, + }; + + MfUltralightError error = mf_ultralight_poller_cmd_execute(nfc, &poller_context); + + return error; +} + +MfUltralightError mf_ultralight_poller_read_version(Nfc* nfc, MfUltralightVersion* data) { + furi_assert(nfc); + furi_assert(data); + + MfUltralightPollerContext poller_context = { + .cmd_type = MfUltralightPollerCmdTypeReadVersion, + }; + + MfUltralightError error = mf_ultralight_poller_cmd_execute(nfc, &poller_context); + + if(error == MfUltralightErrorNone) { + *data = poller_context.data.version; + } + + return error; +} + +MfUltralightError mf_ultralight_poller_read_signature(Nfc* nfc, MfUltralightSignature* data) { + furi_assert(nfc); + furi_assert(data); + + MfUltralightPollerContext poller_context = { + .cmd_type = MfUltralightPollerCmdTypeReadSignature, + }; + + MfUltralightError error = mf_ultralight_poller_cmd_execute(nfc, &poller_context); + + if(error == MfUltralightErrorNone) { + *data = poller_context.data.signature; + } + + return error; +} + +MfUltralightError + mf_ultralight_poller_read_counter(Nfc* nfc, uint8_t counter_num, MfUltralightCounter* data) { + furi_assert(nfc); + furi_assert(data); + + MfUltralightPollerContext poller_context = { + .cmd_type = MfUltralightPollerCmdTypeReadCounter, + .data.counter_cmd.counter_num = counter_num, + }; + + MfUltralightError error = mf_ultralight_poller_cmd_execute(nfc, &poller_context); + + if(error == MfUltralightErrorNone) { + *data = poller_context.data.counter_cmd.data; + } + + return error; +} + +MfUltralightError mf_ultralight_poller_read_tearing_flag( + Nfc* nfc, + uint8_t flag_num, + MfUltralightTearingFlag* data) { + furi_assert(nfc); + furi_assert(data); + + MfUltralightPollerContext poller_context = { + .cmd_type = MfUltralightPollerCmdTypeReadTearingFlag, + .data.tearing_flag_cmd.tearing_flag_num = flag_num, + }; + + MfUltralightError error = mf_ultralight_poller_cmd_execute(nfc, &poller_context); + + if(error == MfUltralightErrorNone) { + *data = poller_context.data.tearing_flag_cmd.data; + } + + return error; +} + +static NfcCommand mf_ultralight_poller_read_callback(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.instance); + furi_assert(event.event_data); + furi_assert(event.protocol == NfcProtocolMfUltralight); + + NfcCommand command = NfcCommandContinue; + MfUltralightPollerContext* poller_context = context; + MfUltralightPoller* mfu_poller = event.instance; + MfUltralightPollerEvent* mfu_event = event.event_data; + + if(mfu_event->type == MfUltralightPollerEventTypeReadSuccess) { + mf_ultralight_copy(poller_context->data.data, mf_ultralight_poller_get_data(mfu_poller)); + poller_context->error = MfUltralightErrorNone; + command = NfcCommandStop; + } else if(mfu_event->type == MfUltralightPollerEventTypeReadFailed) { + poller_context->error = mfu_event->data->error; + command = NfcCommandStop; + } else if(mfu_event->type == MfUltralightPollerEventTypeAuthRequest) { + mfu_event->data->auth_context.skip_auth = true; + } + + if(command == NfcCommandStop) { + furi_thread_flags_set(poller_context->thread_id, MF_ULTRALIGHT_POLLER_COMPLETE_EVENT); + } + + return command; +} + +MfUltralightError mf_ultralight_poller_read_card(Nfc* nfc, MfUltralightData* data) { + furi_assert(nfc); + furi_assert(data); + + MfUltralightPollerContext poller_context = {}; + poller_context.thread_id = furi_thread_get_current_id(); + poller_context.data.data = mf_ultralight_alloc(); + + NfcPoller* poller = nfc_poller_alloc(nfc, NfcProtocolMfUltralight); + nfc_poller_start(poller, mf_ultralight_poller_read_callback, &poller_context); + furi_thread_flags_wait(MF_ULTRALIGHT_POLLER_COMPLETE_EVENT, FuriFlagWaitAny, FuriWaitForever); + furi_thread_flags_clear(MF_ULTRALIGHT_POLLER_COMPLETE_EVENT); + + nfc_poller_stop(poller); + nfc_poller_free(poller); + + if(poller_context.error == MfUltralightErrorNone) { + mf_ultralight_copy(data, poller_context.data.data); + } + + mf_ultralight_free(poller_context.data.data); + + return poller_context.error; +} diff --git a/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_sync_api.h b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_sync_api.h new file mode 100644 index 000000000..a0124ae09 --- /dev/null +++ b/lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_sync_api.h @@ -0,0 +1,30 @@ +#pragma once + +#include "mf_ultralight.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +MfUltralightError mf_ultralight_poller_read_page(Nfc* nfc, uint16_t page, MfUltralightPage* data); + +MfUltralightError mf_ultralight_poller_write_page(Nfc* nfc, uint16_t page, MfUltralightPage* data); + +MfUltralightError mf_ultralight_poller_read_version(Nfc* nfc, MfUltralightVersion* data); + +MfUltralightError mf_ultralight_poller_read_signature(Nfc* nfc, MfUltralightSignature* data); + +MfUltralightError + mf_ultralight_poller_read_counter(Nfc* nfc, uint8_t counter_num, MfUltralightCounter* data); + +MfUltralightError mf_ultralight_poller_read_tearing_flag( + Nfc* nfc, + uint8_t flag_num, + MfUltralightTearingFlag* data); + +MfUltralightError mf_ultralight_poller_read_card(Nfc* nfc, MfUltralightData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/mifare_classic.c b/lib/nfc/protocols/mifare_classic.c deleted file mode 100644 index 87dfddd79..000000000 --- a/lib/nfc/protocols/mifare_classic.c +++ /dev/null @@ -1,1627 +0,0 @@ -#include "mifare_classic.h" -#include "nfca.h" -#include "nfc_util.h" -#include - -// Algorithm from https://github.com/RfidResearchGroup/proxmark3.git - -#define TAG "MfClassic" - -#define MF_CLASSIC_ACK_CMD 0xAU -#define MF_CLASSIC_NACK_BUF_VALID_CMD 0x0U -#define MF_CLASSIC_NACK_BUF_INVALID_CMD 0x4U -#define MF_CLASSIC_AUTH_KEY_A_CMD 0x60U -#define MF_CLASSIC_AUTH_KEY_B_CMD 0x61U -#define MF_CLASSIC_READ_BLOCK_CMD 0x30U -#define MF_CLASSIC_WRITE_BLOCK_CMD 0xA0U -#define MF_CLASSIC_TRANSFER_CMD 0xB0U -#define MF_CLASSIC_DECREMENT_CMD 0xC0U -#define MF_CLASSIC_INCREMENT_CMD 0xC1U -#define MF_CLASSIC_RESTORE_CMD 0xC2U - -const char* mf_classic_get_type_str(MfClassicType type) { - if(type == MfClassicTypeMini) { - return "MIFARE Mini 0.3K"; - } else if(type == MfClassicType1k) { - return "MIFARE Classic 1K"; - } else if(type == MfClassicType4k) { - return "MIFARE Classic 4K"; - } else { - return "Unknown"; - } -} - -static uint8_t mf_classic_get_first_block_num_of_sector(uint8_t sector) { - furi_assert(sector < 40); - if(sector < 32) { - return sector * 4; - } else { - return 32 * 4 + (sector - 32) * 16; - } -} - -uint8_t mf_classic_get_sector_trailer_block_num_by_sector(uint8_t sector) { - furi_assert(sector < 40); - if(sector < 32) { - return sector * 4 + 3; - } else { - return 32 * 4 + (sector - 32) * 16 + 15; - } -} - -uint8_t mf_classic_get_sector_by_block(uint8_t block) { - if(block < 128) { - return (block | 0x03) / 4; - } else { - return 32 + ((block | 0xf) - 32 * 4) / 16; - } -} - -static uint8_t mf_classic_get_blocks_num_in_sector(uint8_t sector) { - furi_assert(sector < 40); - return sector < 32 ? 4 : 16; -} - -uint8_t mf_classic_get_sector_trailer_num_by_block(uint8_t block) { - if(block < 128) { - return block | 0x03; - } else { - return block | 0x0f; - } -} - -bool mf_classic_is_sector_trailer(uint8_t block) { - return block == mf_classic_get_sector_trailer_num_by_block(block); -} - -MfClassicSectorTrailer* - mf_classic_get_sector_trailer_by_sector(MfClassicData* data, uint8_t sector) { - furi_assert(data); - uint8_t sec_tr_block_num = mf_classic_get_sector_trailer_block_num_by_sector(sector); - return (MfClassicSectorTrailer*)data->block[sec_tr_block_num].value; -} - -uint8_t mf_classic_get_total_sectors_num(MfClassicType type) { - if(type == MfClassicTypeMini) { - return MF_MINI_TOTAL_SECTORS_NUM; - } else if(type == MfClassicType1k) { - return MF_CLASSIC_1K_TOTAL_SECTORS_NUM; - } else if(type == MfClassicType4k) { - return MF_CLASSIC_4K_TOTAL_SECTORS_NUM; - } else { - return 0; - } -} - -uint16_t mf_classic_get_total_block_num(MfClassicType type) { - if(type == MfClassicTypeMini) { - return 20; - } else if(type == MfClassicType1k) { - return 64; - } else if(type == MfClassicType4k) { - return 256; - } else { - return 0; - } -} - -bool mf_classic_is_block_read(MfClassicData* data, uint8_t block_num) { - furi_assert(data); - - return (FURI_BIT(data->block_read_mask[block_num / 32], block_num % 32) == 1); -} - -void mf_classic_set_block_read(MfClassicData* data, uint8_t block_num, MfClassicBlock* block_data) { - furi_assert(data); - - if(mf_classic_is_sector_trailer(block_num)) { - memcpy(&data->block[block_num].value[6], &block_data->value[6], 4); - } else { - memcpy(data->block[block_num].value, block_data->value, MF_CLASSIC_BLOCK_SIZE); - } - FURI_BIT_SET(data->block_read_mask[block_num / 32], block_num % 32); -} - -bool mf_classic_is_sector_data_read(MfClassicData* data, uint8_t sector_num) { - furi_assert(data); - - uint8_t first_block = mf_classic_get_first_block_num_of_sector(sector_num); - uint8_t total_blocks = mf_classic_get_blocks_num_in_sector(sector_num); - bool data_read = true; - for(size_t i = first_block; i < first_block + total_blocks; i++) { - data_read &= mf_classic_is_block_read(data, i); - } - - return data_read; -} - -void mf_classic_set_sector_data_not_read(MfClassicData* data) { - furi_assert(data); - memset(data->block_read_mask, 0, sizeof(data->block_read_mask)); -} - -bool mf_classic_is_key_found(MfClassicData* data, uint8_t sector_num, MfClassicKey key_type) { - furi_assert(data); - - bool key_found = false; - if(key_type == MfClassicKeyA) { - key_found = (FURI_BIT(data->key_a_mask, sector_num) == 1); - } else if(key_type == MfClassicKeyB) { - key_found = (FURI_BIT(data->key_b_mask, sector_num) == 1); - } - - return key_found; -} - -void mf_classic_set_key_found( - MfClassicData* data, - uint8_t sector_num, - MfClassicKey key_type, - uint64_t key) { - furi_assert(data); - - uint8_t key_arr[6] = {}; - MfClassicSectorTrailer* sec_trailer = - mf_classic_get_sector_trailer_by_sector(data, sector_num); - nfc_util_num2bytes(key, 6, key_arr); - if(key_type == MfClassicKeyA) { - memcpy(sec_trailer->key_a, key_arr, sizeof(sec_trailer->key_a)); - FURI_BIT_SET(data->key_a_mask, sector_num); - } else if(key_type == MfClassicKeyB) { - memcpy(sec_trailer->key_b, key_arr, sizeof(sec_trailer->key_b)); - FURI_BIT_SET(data->key_b_mask, sector_num); - } -} - -void mf_classic_set_key_not_found(MfClassicData* data, uint8_t sector_num, MfClassicKey key_type) { - furi_assert(data); - - if(key_type == MfClassicKeyA) { - FURI_BIT_CLEAR(data->key_a_mask, sector_num); - } else if(key_type == MfClassicKeyB) { - FURI_BIT_CLEAR(data->key_b_mask, sector_num); - } -} - -bool mf_classic_is_sector_read(MfClassicData* data, uint8_t sector_num) { - furi_assert(data); - - bool sector_read = false; - do { - if(!mf_classic_is_key_found(data, sector_num, MfClassicKeyA)) break; - if(!mf_classic_is_key_found(data, sector_num, MfClassicKeyB)) break; - uint8_t start_block = mf_classic_get_first_block_num_of_sector(sector_num); - uint8_t total_blocks = mf_classic_get_blocks_num_in_sector(sector_num); - uint8_t block_read = true; - for(size_t i = start_block; i < start_block + total_blocks; i++) { - block_read = mf_classic_is_block_read(data, i); - if(!block_read) break; - } - sector_read = block_read; - } while(false); - - return sector_read; -} - -void mf_classic_get_read_sectors_and_keys( - MfClassicData* data, - uint8_t* sectors_read, - uint8_t* keys_found) { - furi_assert(data); - furi_assert(sectors_read); - furi_assert(keys_found); - - *sectors_read = 0; - *keys_found = 0; - uint8_t sectors_total = mf_classic_get_total_sectors_num(data->type); - for(size_t i = 0; i < sectors_total; i++) { - if(mf_classic_is_key_found(data, i, MfClassicKeyA)) { - *keys_found += 1; - } - if(mf_classic_is_key_found(data, i, MfClassicKeyB)) { - *keys_found += 1; - } - uint8_t first_block = mf_classic_get_first_block_num_of_sector(i); - uint8_t total_blocks_in_sec = mf_classic_get_blocks_num_in_sector(i); - bool blocks_read = true; - for(size_t j = first_block; j < first_block + total_blocks_in_sec; j++) { - blocks_read = mf_classic_is_block_read(data, j); - if(!blocks_read) break; - } - if(blocks_read) { - *sectors_read += 1; - } - } -} - -bool mf_classic_is_card_read(MfClassicData* data) { - furi_assert(data); - - uint8_t sectors_total = mf_classic_get_total_sectors_num(data->type); - uint8_t sectors_read = 0; - uint8_t keys_found = 0; - mf_classic_get_read_sectors_and_keys(data, §ors_read, &keys_found); - bool card_read = (sectors_read == sectors_total) && (keys_found == sectors_total * 2); - - return card_read; -} - -bool mf_classic_is_allowed_access_sector_trailer( - MfClassicData* data, - uint8_t block_num, - MfClassicKey key, - MfClassicAction action) { - uint8_t* sector_trailer = data->block[block_num].value; - uint8_t AC = ((sector_trailer[7] >> 5) & 0x04) | ((sector_trailer[8] >> 2) & 0x02) | - ((sector_trailer[8] >> 7) & 0x01); - switch(action) { - case MfClassicActionKeyARead: { - return false; - } - case MfClassicActionKeyAWrite: - case MfClassicActionKeyBWrite: { - return ( - (key == MfClassicKeyA && (AC == 0x00 || AC == 0x01)) || - (key == MfClassicKeyB && (AC == 0x04 || AC == 0x03))); - } - case MfClassicActionKeyBRead: { - return (key == MfClassicKeyA && (AC == 0x00 || AC == 0x02 || AC == 0x01)); - } - case MfClassicActionACRead: { - return ( - (key == MfClassicKeyA) || - (key == MfClassicKeyB && !(AC == 0x00 || AC == 0x02 || AC == 0x01))); - } - case MfClassicActionACWrite: { - return ( - (key == MfClassicKeyA && (AC == 0x01)) || - (key == MfClassicKeyB && (AC == 0x03 || AC == 0x05))); - } - default: - return false; - } - return true; -} - -bool mf_classic_is_allowed_access_data_block( - MfClassicData* data, - uint8_t block_num, - MfClassicKey key, - MfClassicAction action) { - uint8_t* sector_trailer = - data->block[mf_classic_get_sector_trailer_num_by_block(block_num)].value; - - if(block_num == 0 && action == MfClassicActionDataWrite) { - return false; - } - - uint8_t sector_block; - if(block_num <= 128) { - sector_block = block_num & 0x03; - } else { - sector_block = (block_num & 0x0f) / 5; - } - - uint8_t AC; - switch(sector_block) { - case 0x00: { - AC = ((sector_trailer[7] >> 2) & 0x04) | ((sector_trailer[8] << 1) & 0x02) | - ((sector_trailer[8] >> 4) & 0x01); - break; - } - case 0x01: { - AC = ((sector_trailer[7] >> 3) & 0x04) | ((sector_trailer[8] >> 0) & 0x02) | - ((sector_trailer[8] >> 5) & 0x01); - break; - } - case 0x02: { - AC = ((sector_trailer[7] >> 4) & 0x04) | ((sector_trailer[8] >> 1) & 0x02) | - ((sector_trailer[8] >> 6) & 0x01); - break; - } - default: - return false; - } - - switch(action) { - case MfClassicActionDataRead: { - return ( - (key == MfClassicKeyA && !(AC == 0x03 || AC == 0x05 || AC == 0x07)) || - (key == MfClassicKeyB && !(AC == 0x07))); - } - case MfClassicActionDataWrite: { - return ( - (key == MfClassicKeyA && (AC == 0x00)) || - (key == MfClassicKeyB && (AC == 0x00 || AC == 0x04 || AC == 0x06 || AC == 0x03))); - } - case MfClassicActionDataInc: { - return ( - (key == MfClassicKeyA && (AC == 0x00)) || - (key == MfClassicKeyB && (AC == 0x00 || AC == 0x06))); - } - case MfClassicActionDataDec: { - return ( - (key == MfClassicKeyA && (AC == 0x00 || AC == 0x06 || AC == 0x01)) || - (key == MfClassicKeyB && (AC == 0x00 || AC == 0x06 || AC == 0x01))); - } - default: - return false; - } - - return false; -} - -static bool mf_classic_is_allowed_access( - MfClassicEmulator* emulator, - uint8_t block_num, - MfClassicKey key, - MfClassicAction action) { - if(mf_classic_is_sector_trailer(block_num)) { - return mf_classic_is_allowed_access_sector_trailer( - &emulator->data, block_num, key, action); - } else { - return mf_classic_is_allowed_access_data_block(&emulator->data, block_num, key, action); - } -} - -bool mf_classic_is_value_block(MfClassicData* data, uint8_t block_num) { - // Check if key A can write, if it can, it's transport configuration, not data block - return !mf_classic_is_allowed_access_data_block( - data, block_num, MfClassicKeyA, MfClassicActionDataWrite) && - (mf_classic_is_allowed_access_data_block( - data, block_num, MfClassicKeyB, MfClassicActionDataInc) || - mf_classic_is_allowed_access_data_block( - data, block_num, MfClassicKeyB, MfClassicActionDataDec)); -} - -bool mf_classic_check_card_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK) { - UNUSED(ATQA1); - if((ATQA0 == 0x44 || ATQA0 == 0x04) && - (SAK == 0x08 || SAK == 0x88 || SAK == 0x09 || SAK == 0x89)) { - return true; - } else if((ATQA0 == 0x01) && (ATQA1 == 0x0F) && (SAK == 0x01)) { - //skylanders support - return true; - } else if( - ((ATQA0 == 0x42 || ATQA0 == 0x02) && (SAK == 0x18)) || - ((ATQA0 == 0x02 || ATQA0 == 0x04 || ATQA0 == 0x08) && (SAK == 0x38))) { - return true; - } else { - return false; - } -} - -MfClassicType mf_classic_get_classic_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK) { - UNUSED(ATQA1); - if((ATQA0 == 0x44 || ATQA0 == 0x04)) { - if((SAK == 0x08 || SAK == 0x88)) { - return MfClassicType1k; - } else if((SAK == 0x38)) { - return MfClassicType4k; - } else if((SAK == 0x09 || SAK == 0x89)) { - return MfClassicTypeMini; - } - } else if((ATQA0 == 0x01) && (ATQA1 == 0x0F) && (SAK == 0x01)) { - //skylanders support - return MfClassicType1k; - } else if( - ((ATQA0 == 0x42 || ATQA0 == 0x02) && (SAK == 0x18)) || - ((ATQA0 == 0x02 || ATQA0 == 0x08) && (SAK == 0x38))) { - return MfClassicType4k; - } - return MfClassicType1k; -} - -void mf_classic_reader_add_sector( - MfClassicReader* reader, - uint8_t sector, - uint64_t key_a, - uint64_t key_b) { - furi_assert(reader); - furi_assert(sector < MF_CLASSIC_SECTORS_MAX); - furi_assert((key_a != MF_CLASSIC_NO_KEY) || (key_b != MF_CLASSIC_NO_KEY)); - - if(reader->sectors_to_read < MF_CLASSIC_SECTORS_MAX) { - reader->sector_reader[reader->sectors_to_read].key_a = key_a; - reader->sector_reader[reader->sectors_to_read].key_b = key_b; - reader->sector_reader[reader->sectors_to_read].sector_num = sector; - reader->sectors_to_read++; - } -} - -bool mf_classic_block_to_value(const uint8_t* block, int32_t* value, uint8_t* addr) { - uint32_t v = *(uint32_t*)&block[0]; - uint32_t v_inv = *(uint32_t*)&block[4]; - uint32_t v1 = *(uint32_t*)&block[8]; - - bool val_checks = - ((v == v1) && (v == ~v_inv) && (block[12] == (~block[13] & 0xFF)) && - (block[14] == (~block[15] & 0xFF)) && (block[12] == block[14])); - if(value) { - *value = (int32_t)v; - } - if(addr) { - *addr = block[12]; - } - return val_checks; -} - -void mf_classic_value_to_block(int32_t value, uint8_t addr, uint8_t* block) { - uint32_t v_inv = ~((uint32_t)value); - - memcpy(block, &value, 4); //-V1086 - memcpy(block + 4, &v_inv, 4); //-V1086 - memcpy(block + 8, &value, 4); //-V1086 - - block[12] = addr; - block[13] = ~addr & 0xFF; - block[14] = addr; - block[15] = ~addr & 0xFF; -} - -void mf_classic_auth_init_context(MfClassicAuthContext* auth_ctx, uint8_t sector) { - furi_assert(auth_ctx); - auth_ctx->sector = sector; - auth_ctx->key_a = MF_CLASSIC_NO_KEY; - auth_ctx->key_b = MF_CLASSIC_NO_KEY; -} - -static bool mf_classic_auth( - FuriHalNfcTxRxContext* tx_rx, - uint32_t block, - uint64_t key, - MfClassicKey key_type, - Crypto1* crypto, - bool skip_activate, - uint32_t cuid) { - bool auth_success = false; - memset(tx_rx->tx_data, 0, sizeof(tx_rx->tx_data)); - memset(tx_rx->tx_parity, 0, sizeof(tx_rx->tx_parity)); - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - - do { - if(!skip_activate && !furi_hal_nfc_activate_nfca(200, &cuid)) break; - if(key_type == MfClassicKeyA) { - tx_rx->tx_data[0] = MF_CLASSIC_AUTH_KEY_A_CMD; - } else { - tx_rx->tx_data[0] = MF_CLASSIC_AUTH_KEY_B_CMD; - } - tx_rx->tx_data[1] = block; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRxNoCrc; - tx_rx->tx_bits = 2 * 8; - if(!furi_hal_nfc_tx_rx(tx_rx, 6)) break; - - uint32_t nt = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4); - crypto1_init(crypto, key); - crypto1_word(crypto, nt ^ cuid, 0); - uint8_t nr[4] = {}; - nfc_util_num2bytes(prng_successor(DWT->CYCCNT, 32), 4, nr); - for(uint8_t i = 0; i < 4; i++) { - tx_rx->tx_data[i] = crypto1_byte(crypto, nr[i], 0) ^ nr[i]; - tx_rx->tx_parity[0] |= - (((crypto1_filter(crypto->odd) ^ nfc_util_odd_parity8(nr[i])) & 0x01) << (7 - i)); - } - nt = prng_successor(nt, 32); - for(uint8_t i = 4; i < 8; i++) { - nt = prng_successor(nt, 8); - tx_rx->tx_data[i] = crypto1_byte(crypto, 0x00, 0) ^ (nt & 0xff); - tx_rx->tx_parity[0] |= - (((crypto1_filter(crypto->odd) ^ nfc_util_odd_parity8(nt & 0xff)) & 0x01) - << (7 - i)); - } - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw; - tx_rx->tx_bits = 8 * 8; - if(!furi_hal_nfc_tx_rx(tx_rx, 6)) break; - if(tx_rx->rx_bits == 32) { - crypto1_word(crypto, 0, 0); - auth_success = true; - } - } while(false); - - return auth_success; -} - -bool mf_classic_authenticate( - FuriHalNfcTxRxContext* tx_rx, - uint8_t block_num, - uint64_t key, - MfClassicKey key_type) { - furi_assert(tx_rx); - - Crypto1 crypto = {}; - bool key_found = mf_classic_auth(tx_rx, block_num, key, key_type, &crypto, false, 0); - furi_hal_nfc_sleep(); - return key_found; -} - -bool mf_classic_authenticate_skip_activate( - FuriHalNfcTxRxContext* tx_rx, - uint8_t block_num, - uint64_t key, - MfClassicKey key_type, - bool skip_activate, - uint32_t cuid) { - furi_assert(tx_rx); - - Crypto1 crypto = {}; - bool key_found = - mf_classic_auth(tx_rx, block_num, key, key_type, &crypto, skip_activate, cuid); - furi_hal_nfc_sleep(); - return key_found; -} - -bool mf_classic_auth_attempt( - FuriHalNfcTxRxContext* tx_rx, - Crypto1* crypto, - MfClassicAuthContext* auth_ctx, - uint64_t key) { - furi_assert(tx_rx); - furi_assert(auth_ctx); - bool found_key = false; - bool need_halt = (auth_ctx->key_a == MF_CLASSIC_NO_KEY) && - (auth_ctx->key_b == MF_CLASSIC_NO_KEY); - - if(auth_ctx->key_a == MF_CLASSIC_NO_KEY) { - // Try AUTH with key A - if(mf_classic_auth( - tx_rx, - mf_classic_get_sector_trailer_block_num_by_sector(auth_ctx->sector), - key, - MfClassicKeyA, - crypto, - false, - 0)) { - auth_ctx->key_a = key; - found_key = true; - } - } - - if(need_halt) { - furi_hal_nfc_sleep(); - } - - if(auth_ctx->key_b == MF_CLASSIC_NO_KEY) { - // Try AUTH with key B - if(mf_classic_auth( - tx_rx, - mf_classic_get_sector_trailer_block_num_by_sector(auth_ctx->sector), - key, - MfClassicKeyB, - crypto, - false, - 0)) { - auth_ctx->key_b = key; - found_key = true; - } - } - - return found_key; -} - -bool mf_classic_read_block( - FuriHalNfcTxRxContext* tx_rx, - Crypto1* crypto, - uint8_t block_num, - MfClassicBlock* block) { - furi_assert(tx_rx); - furi_assert(crypto); - furi_assert(block); - - bool read_block_success = false; - uint8_t plain_cmd[4] = {MF_CLASSIC_READ_BLOCK_CMD, block_num, 0x00, 0x00}; - nfca_append_crc16(plain_cmd, 2); - - crypto1_encrypt( - crypto, NULL, plain_cmd, sizeof(plain_cmd) * 8, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_bits = sizeof(plain_cmd) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw; - - if(furi_hal_nfc_tx_rx(tx_rx, 50)) { - if(tx_rx->rx_bits == 8 * (MF_CLASSIC_BLOCK_SIZE + 2)) { - uint8_t block_received[MF_CLASSIC_BLOCK_SIZE + 2]; - crypto1_decrypt(crypto, tx_rx->rx_data, tx_rx->rx_bits, block_received); - uint16_t crc_calc = nfca_get_crc16(block_received, MF_CLASSIC_BLOCK_SIZE); - uint16_t crc_received = (block_received[MF_CLASSIC_BLOCK_SIZE + 1] << 8) | - block_received[MF_CLASSIC_BLOCK_SIZE]; - if(crc_received != crc_calc) { - FURI_LOG_E( - TAG, - "Incorrect CRC while reading block %d. Expected %04X, Received %04X", - block_num, - crc_received, - crc_calc); - } else { - memcpy(block->value, block_received, MF_CLASSIC_BLOCK_SIZE); - read_block_success = true; - } - } - } - return read_block_success; -} - -void mf_classic_read_sector(FuriHalNfcTxRxContext* tx_rx, MfClassicData* data, uint8_t sec_num) { - furi_assert(tx_rx); - furi_assert(data); - - furi_hal_nfc_sleep(); - bool key_a_found = mf_classic_is_key_found(data, sec_num, MfClassicKeyA); - bool key_b_found = mf_classic_is_key_found(data, sec_num, MfClassicKeyB); - uint8_t start_block = mf_classic_get_first_block_num_of_sector(sec_num); - uint8_t total_blocks = mf_classic_get_blocks_num_in_sector(sec_num); - MfClassicBlock block_tmp = {}; - uint64_t key = 0; - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(data, sec_num); - Crypto1 crypto = {}; - - uint8_t blocks_read = 0; - do { - if(!key_a_found) break; - FURI_LOG_D(TAG, "Try to read blocks with key A"); - key = nfc_util_bytes2num(sec_tr->key_a, sizeof(sec_tr->key_a)); - if(!mf_classic_auth(tx_rx, start_block, key, MfClassicKeyA, &crypto, false, 0)) { - mf_classic_set_key_not_found(data, sec_num, MfClassicKeyA); - FURI_LOG_D(TAG, "Key %dA not found in read", sec_num); - break; - } - - for(size_t i = start_block; i < start_block + total_blocks; i++) { - if(!mf_classic_is_block_read(data, i)) { - if(mf_classic_read_block(tx_rx, &crypto, i, &block_tmp)) { - mf_classic_set_block_read(data, i, &block_tmp); - blocks_read++; - } else if(i > start_block) { - // Try to re-auth to read block in case prevous block was protected from read - furi_hal_nfc_sleep(); - if(!mf_classic_auth(tx_rx, i, key, MfClassicKeyA, &crypto, false, 0)) { - mf_classic_set_key_not_found(data, sec_num, MfClassicKeyA); - FURI_LOG_D(TAG, "Key %dA not found in read", sec_num); - break; - } - if(mf_classic_read_block(tx_rx, &crypto, i, &block_tmp)) { - mf_classic_set_block_read(data, i, &block_tmp); - blocks_read++; - } - } - } else { - blocks_read++; - } - } - FURI_LOG_D(TAG, "Read %d blocks out of %d", blocks_read, total_blocks); - } while(false); - do { - if(blocks_read == total_blocks) break; - if(!key_b_found) break; - if(key_a_found) { - furi_hal_nfc_sleep(); - } - FURI_LOG_D(TAG, "Try to read blocks with key B"); - key = nfc_util_bytes2num(sec_tr->key_b, sizeof(sec_tr->key_b)); - if(!mf_classic_auth(tx_rx, start_block, key, MfClassicKeyB, &crypto, false, 0)) { - mf_classic_set_key_not_found(data, sec_num, MfClassicKeyB); - FURI_LOG_D(TAG, "Key %dB not found in read", sec_num); - break; - } - - for(size_t i = start_block; i < start_block + total_blocks; i++) { - if(!mf_classic_is_block_read(data, i)) { - if(mf_classic_read_block(tx_rx, &crypto, i, &block_tmp)) { - mf_classic_set_block_read(data, i, &block_tmp); - blocks_read++; - } else if(i > start_block) { - // Try to re-auth to read block in case prevous block was protected from read - furi_hal_nfc_sleep(); - if(!mf_classic_auth(tx_rx, i, key, MfClassicKeyB, &crypto, false, 0)) { - mf_classic_set_key_not_found(data, sec_num, MfClassicKeyB); - FURI_LOG_D(TAG, "Key %dB not found in read", sec_num); - break; - } - if(mf_classic_read_block(tx_rx, &crypto, i, &block_tmp)) { - mf_classic_set_block_read(data, i, &block_tmp); - blocks_read++; - } - } - } else { - blocks_read++; - } - } - FURI_LOG_D(TAG, "Read %d blocks out of %d", blocks_read, total_blocks); - } while(false); -} - -static bool mf_classic_read_sector_with_reader( - FuriHalNfcTxRxContext* tx_rx, - Crypto1* crypto, - MfClassicSectorReader* sector_reader, - MfClassicSector* sector) { - furi_assert(tx_rx); - furi_assert(sector_reader); - furi_assert(sector); - - uint64_t key; - MfClassicKey key_type; - uint8_t first_block; - bool sector_read = false; - - furi_hal_nfc_sleep(); - do { - // Activate card - first_block = mf_classic_get_first_block_num_of_sector(sector_reader->sector_num); - if(sector_reader->key_a != MF_CLASSIC_NO_KEY) { - key = sector_reader->key_a; - key_type = MfClassicKeyA; - } else if(sector_reader->key_b != MF_CLASSIC_NO_KEY) { - key = sector_reader->key_b; - key_type = MfClassicKeyB; - } else { - break; - } - - // Auth to first block in sector - if(!mf_classic_auth(tx_rx, first_block, key, key_type, crypto, false, 0)) { - // Set key to MF_CLASSIC_NO_KEY to prevent further attempts - if(key_type == MfClassicKeyA) { - sector_reader->key_a = MF_CLASSIC_NO_KEY; - } else { - sector_reader->key_b = MF_CLASSIC_NO_KEY; - } - break; - } - sector->total_blocks = mf_classic_get_blocks_num_in_sector(sector_reader->sector_num); - - // Read blocks - for(uint8_t i = 0; i < sector->total_blocks; i++) { - if(mf_classic_read_block(tx_rx, crypto, first_block + i, §or->block[i])) continue; - if(i == 0) continue; - // Try to auth to read next block in case previous is locked - furi_hal_nfc_sleep(); - if(!mf_classic_auth(tx_rx, first_block + i, key, key_type, crypto, false, 0)) continue; - mf_classic_read_block(tx_rx, crypto, first_block + i, §or->block[i]); - } - // Save sector keys in last block - if(sector_reader->key_a != MF_CLASSIC_NO_KEY) { - nfc_util_num2bytes( - sector_reader->key_a, 6, §or->block[sector->total_blocks - 1].value[0]); - } - if(sector_reader->key_b != MF_CLASSIC_NO_KEY) { - nfc_util_num2bytes( - sector_reader->key_b, 6, §or->block[sector->total_blocks - 1].value[10]); - } - - sector_read = true; - } while(false); - - return sector_read; -} - -uint8_t mf_classic_read_card( - FuriHalNfcTxRxContext* tx_rx, - MfClassicReader* reader, - MfClassicData* data) { - furi_assert(tx_rx); - furi_assert(reader); - furi_assert(data); - - uint8_t sectors_read = 0; - data->type = reader->type; - data->key_a_mask = 0; - data->key_b_mask = 0; - MfClassicSector temp_sector = {}; - for(uint8_t i = 0; i < reader->sectors_to_read; i++) { - if(mf_classic_read_sector_with_reader( - tx_rx, &reader->crypto, &reader->sector_reader[i], &temp_sector)) { - uint8_t first_block = - mf_classic_get_first_block_num_of_sector(reader->sector_reader[i].sector_num); - for(uint8_t j = 0; j < temp_sector.total_blocks; j++) { - mf_classic_set_block_read(data, first_block + j, &temp_sector.block[j]); - } - if(reader->sector_reader[i].key_a != MF_CLASSIC_NO_KEY) { - mf_classic_set_key_found( - data, - reader->sector_reader[i].sector_num, - MfClassicKeyA, - reader->sector_reader[i].key_a); - } - if(reader->sector_reader[i].key_b != MF_CLASSIC_NO_KEY) { - mf_classic_set_key_found( - data, - reader->sector_reader[i].sector_num, - MfClassicKeyB, - reader->sector_reader[i].key_b); - } - sectors_read++; - } - } - - return sectors_read; -} - -uint8_t mf_classic_update_card(FuriHalNfcTxRxContext* tx_rx, MfClassicData* data) { - furi_assert(tx_rx); - furi_assert(data); - - uint8_t total_sectors = mf_classic_get_total_sectors_num(data->type); - - for(size_t i = 0; i < total_sectors; i++) { - mf_classic_read_sector(tx_rx, data, i); - } - uint8_t sectors_read = 0; - uint8_t keys_found = 0; - mf_classic_get_read_sectors_and_keys(data, §ors_read, &keys_found); - FURI_LOG_D(TAG, "Read %d sectors and %d keys", sectors_read, keys_found); - - return sectors_read; -} - -bool mf_classic_emulator( - MfClassicEmulator* emulator, - FuriHalNfcTxRxContext* tx_rx, - bool is_reader_analyzer) { - furi_assert(emulator); - furi_assert(tx_rx); - uint8_t plain_data[MF_CLASSIC_MAX_DATA_SIZE]; - MfClassicKey access_key = MfClassicKeyA; - bool need_reset = false; - bool need_nack = false; - bool is_encrypted = false; - uint8_t sector = 0; - - // Used for decrement and increment - copy to block on transfer - uint8_t transfer_buf[MF_CLASSIC_BLOCK_SIZE]; - bool transfer_buf_valid = false; - - // Process commands - while(!need_reset && !need_nack) { //-V654 - memset(plain_data, 0, MF_CLASSIC_MAX_DATA_SIZE); - if(!is_encrypted) { - crypto1_reset(&emulator->crypto); - memcpy(plain_data, tx_rx->rx_data, tx_rx->rx_bits / 8); - } else { - if(!furi_hal_nfc_tx_rx(tx_rx, 300)) { - FURI_LOG_D( - TAG, - "Error in tx rx. Tx: %d bits, Rx: %d bits", - tx_rx->tx_bits, - tx_rx->rx_bits); - need_reset = true; - break; - } - crypto1_decrypt(&emulator->crypto, tx_rx->rx_data, tx_rx->rx_bits, plain_data); - } - - // After increment, decrement or restore the only allowed command is transfer - uint8_t cmd = plain_data[0]; - if(transfer_buf_valid && cmd != MF_CLASSIC_TRANSFER_CMD) { - need_nack = true; - break; - } - - if(cmd == NFCA_CMD_HALT && plain_data[1] == 0x00) { - FURI_LOG_T(TAG, "Halt received"); - need_reset = true; - break; - } - - if(cmd == NFCA_CMD_RATS) { - // Mifare Classic doesn't support ATS, NACK it and start listening again - FURI_LOG_T(TAG, "RATS received"); - need_nack = true; - break; - } - - if(cmd == MF_CLASSIC_AUTH_KEY_A_CMD || cmd == MF_CLASSIC_AUTH_KEY_B_CMD) { - uint8_t block = plain_data[1]; - uint64_t key = 0; - uint8_t sector_trailer_block = mf_classic_get_sector_trailer_num_by_block(block); - sector = mf_classic_get_sector_by_block(block); - MfClassicSectorTrailer* sector_trailer = - (MfClassicSectorTrailer*)emulator->data.block[sector_trailer_block].value; - if(cmd == MF_CLASSIC_AUTH_KEY_A_CMD) { - if(mf_classic_is_key_found( - &emulator->data, mf_classic_get_sector_by_block(block), MfClassicKeyA) || - is_reader_analyzer) { - key = nfc_util_bytes2num(sector_trailer->key_a, 6); - access_key = MfClassicKeyA; - } else { - FURI_LOG_D(TAG, "Key not known"); - need_nack = true; - break; - } - } else { - if(mf_classic_is_key_found( - &emulator->data, mf_classic_get_sector_by_block(block), MfClassicKeyB) || - is_reader_analyzer) { - key = nfc_util_bytes2num(sector_trailer->key_b, 6); - access_key = MfClassicKeyB; - } else { - FURI_LOG_D(TAG, "Key not known"); - need_nack = true; - break; - } - } - - uint32_t nonce = prng_successor(DWT->CYCCNT, 32) ^ 0xAA; - uint8_t nt[4]; - uint8_t nt_keystream[4]; - nfc_util_num2bytes(nonce, 4, nt); - nfc_util_num2bytes(nonce ^ emulator->cuid, 4, nt_keystream); - crypto1_init(&emulator->crypto, key); - if(!is_encrypted) { - crypto1_word(&emulator->crypto, emulator->cuid ^ nonce, 0); - memcpy(tx_rx->tx_data, nt, sizeof(nt)); - tx_rx->tx_parity[0] = 0; - nfc_util_odd_parity(tx_rx->tx_data, tx_rx->tx_parity, sizeof(nt)); - tx_rx->tx_bits = sizeof(nt) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - } else { - crypto1_encrypt( - &emulator->crypto, - nt_keystream, - nt, - sizeof(nt) * 8, - tx_rx->tx_data, - tx_rx->tx_parity); - tx_rx->tx_bits = sizeof(nt) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - } - - if(!furi_hal_nfc_tx_rx(tx_rx, 500)) { - FURI_LOG_E(TAG, "Error in NT exchange"); - need_reset = true; - break; - } - - if(tx_rx->rx_bits != 64) { - need_reset = true; - break; - } - - uint32_t nr = nfc_util_bytes2num(tx_rx->rx_data, 4); - uint32_t ar = nfc_util_bytes2num(&tx_rx->rx_data[4], 4); - - crypto1_word(&emulator->crypto, nr, 1); - uint32_t cardRr = ar ^ crypto1_word(&emulator->crypto, 0, 0); - if(cardRr != prng_successor(nonce, 64)) { - FURI_LOG_T( - TAG, - "Wrong AUTH on block %u! %08lX != %08lX", - block, - cardRr, - prng_successor(nonce, 64)); - // Don't send NACK, as the tag doesn't send it - need_reset = true; - break; - } - - uint32_t ans = prng_successor(nonce, 96); - uint8_t response[4] = {}; - nfc_util_num2bytes(ans, 4, response); - crypto1_encrypt( - &emulator->crypto, - NULL, - response, - sizeof(response) * 8, - tx_rx->tx_data, - tx_rx->tx_parity); - tx_rx->tx_bits = sizeof(response) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - - is_encrypted = true; - continue; - } - - if(!is_encrypted) { - FURI_LOG_T(TAG, "Invalid command before auth session established: %02X", cmd); - need_nack = true; - break; - } - - // Mifare Classic commands always have block number after command - uint8_t block = plain_data[1]; - if(mf_classic_get_sector_by_block(block) != sector) { - // Don't allow access to sectors other than authorized - FURI_LOG_T( - TAG, - "Trying to access block %u from not authorized sector (command: %02X)", - block, - cmd); - need_nack = true; - break; - } - - switch(cmd) { - case MF_CLASSIC_READ_BLOCK_CMD: { - uint8_t block_data[MF_CLASSIC_BLOCK_SIZE + 2] = {}; - memcpy(block_data, emulator->data.block[block].value, MF_CLASSIC_BLOCK_SIZE); - if(mf_classic_is_sector_trailer(block)) { - if(!mf_classic_is_allowed_access( - emulator, block, access_key, MfClassicActionKeyARead)) { - memset(block_data, 0, 6); //-V1086 - } - if(!mf_classic_is_allowed_access( - emulator, block, access_key, MfClassicActionKeyBRead)) { - memset(&block_data[10], 0, 6); - } - if(!mf_classic_is_allowed_access( - emulator, block, access_key, MfClassicActionACRead)) { - memset(&block_data[6], 0, 4); - } - } else if( - !mf_classic_is_allowed_access( - emulator, block, access_key, MfClassicActionDataRead) || - !mf_classic_is_block_read(&emulator->data, block)) { - need_nack = true; - break; - } - - nfca_append_crc16(block_data, 16); - - crypto1_encrypt( - &emulator->crypto, - NULL, - block_data, - sizeof(block_data) * 8, - tx_rx->tx_data, - tx_rx->tx_parity); - tx_rx->tx_bits = (MF_CLASSIC_BLOCK_SIZE + 2) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - break; - } - - case MF_CLASSIC_WRITE_BLOCK_CMD: { - // Send ACK - uint8_t ack = MF_CLASSIC_ACK_CMD; - crypto1_encrypt(&emulator->crypto, NULL, &ack, 4, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - tx_rx->tx_bits = 4; - - if(!furi_hal_nfc_tx_rx(tx_rx, 300)) { - need_reset = true; - break; - } - - if(tx_rx->rx_bits != (MF_CLASSIC_BLOCK_SIZE + 2) * 8) { - need_reset = true; - break; - } - - crypto1_decrypt(&emulator->crypto, tx_rx->rx_data, tx_rx->rx_bits, plain_data); - uint8_t block_data[MF_CLASSIC_BLOCK_SIZE] = {}; - memcpy(block_data, emulator->data.block[block].value, MF_CLASSIC_BLOCK_SIZE); - - if(!mf_classic_is_block_read(&emulator->data, block)) { - // Don't allow writing to the block for which we haven't read data yet - need_nack = true; - break; - } - - if(mf_classic_is_sector_trailer(block)) { - if(mf_classic_is_allowed_access( - emulator, block, access_key, MfClassicActionKeyAWrite)) { - memcpy(block_data, plain_data, 6); //-V1086 - } - if(mf_classic_is_allowed_access( - emulator, block, access_key, MfClassicActionKeyBWrite)) { - memcpy(&block_data[10], &plain_data[10], 6); - } - if(mf_classic_is_allowed_access( - emulator, block, access_key, MfClassicActionACWrite)) { - memcpy(&block_data[6], &plain_data[6], 4); - } - } else { - if(mf_classic_is_allowed_access( - emulator, block, access_key, MfClassicActionDataWrite)) { - memcpy(block_data, plain_data, MF_CLASSIC_BLOCK_SIZE); - } else { - need_nack = true; - break; - } - } - - if(memcmp(block_data, emulator->data.block[block].value, MF_CLASSIC_BLOCK_SIZE) != 0) { - memcpy(emulator->data.block[block].value, block_data, MF_CLASSIC_BLOCK_SIZE); - emulator->data_changed = true; - } - - // Send ACK - ack = MF_CLASSIC_ACK_CMD; - crypto1_encrypt(&emulator->crypto, NULL, &ack, 4, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - tx_rx->tx_bits = 4; - break; - } - - case MF_CLASSIC_DECREMENT_CMD: - case MF_CLASSIC_INCREMENT_CMD: - case MF_CLASSIC_RESTORE_CMD: { - MfClassicAction action = (cmd == MF_CLASSIC_INCREMENT_CMD) ? MfClassicActionDataInc : - MfClassicActionDataDec; - - if(!mf_classic_is_allowed_access(emulator, block, access_key, action)) { - need_nack = true; - break; - } - - int32_t prev_value; - uint8_t addr; - if(!mf_classic_block_to_value(emulator->data.block[block].value, &prev_value, &addr)) { - need_nack = true; - break; - } - - // Send ACK - uint8_t ack = MF_CLASSIC_ACK_CMD; - crypto1_encrypt(&emulator->crypto, NULL, &ack, 4, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - tx_rx->tx_bits = 4; - - if(!furi_hal_nfc_tx_rx(tx_rx, 300)) { - need_reset = true; - break; - } - - if(tx_rx->rx_bits != (sizeof(int32_t) + 2) * 8) { - need_reset = true; - break; - } - - crypto1_decrypt(&emulator->crypto, tx_rx->rx_data, tx_rx->rx_bits, plain_data); - int32_t value = *(int32_t*)&plain_data[0]; - if(value < 0) { - value = -value; - } - if(cmd == MF_CLASSIC_DECREMENT_CMD) { - value = -value; - } else if(cmd == MF_CLASSIC_RESTORE_CMD) { - value = 0; - } - - mf_classic_value_to_block(prev_value + value, addr, transfer_buf); - transfer_buf_valid = true; - // Commands do not ACK - tx_rx->tx_bits = 0; - break; - } - - case MF_CLASSIC_TRANSFER_CMD: { - if(!mf_classic_is_allowed_access(emulator, block, access_key, MfClassicActionDataDec)) { - need_nack = true; - break; - } - if(memcmp(transfer_buf, emulator->data.block[block].value, MF_CLASSIC_BLOCK_SIZE) != - 0) { - memcpy(emulator->data.block[block].value, transfer_buf, MF_CLASSIC_BLOCK_SIZE); - emulator->data_changed = true; - } - transfer_buf_valid = false; - - uint8_t ack = MF_CLASSIC_ACK_CMD; - crypto1_encrypt(&emulator->crypto, NULL, &ack, 4, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - tx_rx->tx_bits = 4; - break; - } - - default: - FURI_LOG_T(TAG, "Unknown command: %02X", cmd); - need_nack = true; - break; - } - } - - if(need_nack && !need_reset) { - // Send NACK - uint8_t nack = transfer_buf_valid ? MF_CLASSIC_NACK_BUF_VALID_CMD : - MF_CLASSIC_NACK_BUF_INVALID_CMD; - if(is_encrypted) { - crypto1_encrypt(&emulator->crypto, NULL, &nack, 4, tx_rx->tx_data, tx_rx->tx_parity); - } else { - tx_rx->tx_data[0] = nack; - } - tx_rx->tx_rx_type = FuriHalNfcTxRxTransparent; - tx_rx->tx_bits = 4; - furi_hal_nfc_tx_rx(tx_rx, 300); - need_reset = true; - } - - return !need_reset; -} - -void mf_classic_halt(FuriHalNfcTxRxContext* tx_rx, Crypto1* crypto) { - furi_assert(tx_rx); - - uint8_t plain_data[4] = {NFCA_CMD_HALT, 0x00, 0x00, 0x00}; - - nfca_append_crc16(plain_data, 2); - if(crypto) { - crypto1_encrypt( - crypto, NULL, plain_data, sizeof(plain_data) * 8, tx_rx->tx_data, tx_rx->tx_parity); - } else { - memcpy(tx_rx->tx_data, plain_data, sizeof(plain_data)); - nfc_util_odd_parity(tx_rx->tx_data, tx_rx->tx_parity, sizeof(plain_data)); - } - - tx_rx->tx_bits = sizeof(plain_data) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw; - furi_hal_nfc_tx_rx(tx_rx, 50); -} - -bool mf_classic_write_block( - FuriHalNfcTxRxContext* tx_rx, - Crypto1* crypto, - uint8_t block_num, - MfClassicBlock* src_block) { - furi_assert(tx_rx); - furi_assert(crypto); - furi_assert(src_block); - - bool write_success = false; - uint8_t plain_data[MF_CLASSIC_BLOCK_SIZE + 2] = {}; - uint8_t resp; - - do { - // Send write command - plain_data[0] = MF_CLASSIC_WRITE_BLOCK_CMD; - plain_data[1] = block_num; - nfca_append_crc16(plain_data, 2); - crypto1_encrypt(crypto, NULL, plain_data, 4 * 8, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_bits = 4 * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw; - - if(furi_hal_nfc_tx_rx(tx_rx, 50)) { - if(tx_rx->rx_bits == 4) { - crypto1_decrypt(crypto, tx_rx->rx_data, 4, &resp); - if(resp != 0x0A) { - FURI_LOG_D(TAG, "NACK received on write cmd: %02X", resp); - break; - } - } else { - FURI_LOG_D(TAG, "Not ACK received"); - break; - } - } else { - FURI_LOG_D(TAG, "Failed to send write cmd"); - break; - } - - // Send data - memcpy(plain_data, src_block->value, MF_CLASSIC_BLOCK_SIZE); - nfca_append_crc16(plain_data, MF_CLASSIC_BLOCK_SIZE); - crypto1_encrypt( - crypto, - NULL, - plain_data, - (MF_CLASSIC_BLOCK_SIZE + 2) * 8, - tx_rx->tx_data, - tx_rx->tx_parity); - tx_rx->tx_bits = (MF_CLASSIC_BLOCK_SIZE + 2) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw; - if(furi_hal_nfc_tx_rx(tx_rx, 50)) { - if(tx_rx->rx_bits == 4) { - crypto1_decrypt(crypto, tx_rx->rx_data, 4, &resp); - if(resp != MF_CLASSIC_ACK_CMD) { - FURI_LOG_D(TAG, "NACK received on sending data"); - break; - } - } else { - FURI_LOG_D(TAG, "Not ACK received"); - break; - } - } else { - FURI_LOG_D(TAG, "Failed to send data"); - break; - } - - write_success = true; - } while(false); - - return write_success; -} - -bool mf_classic_auth_write_block( - FuriHalNfcTxRxContext* tx_rx, - MfClassicBlock* src_block, - uint8_t block_num, - MfClassicKey key_type, - uint64_t key) { - furi_assert(tx_rx); - furi_assert(src_block); - - Crypto1 crypto = {}; - bool write_success = false; - - do { - furi_hal_nfc_sleep(); - if(!mf_classic_auth(tx_rx, block_num, key, key_type, &crypto, false, 0)) { - FURI_LOG_D(TAG, "Auth fail"); - break; - } - - if(!mf_classic_write_block(tx_rx, &crypto, block_num, src_block)) { - FURI_LOG_D(TAG, "Write fail"); - break; - } - write_success = true; - - mf_classic_halt(tx_rx, &crypto); - } while(false); - - return write_success; -} - -bool mf_classic_transfer(FuriHalNfcTxRxContext* tx_rx, Crypto1* crypto, uint8_t block_num) { - furi_assert(tx_rx); - furi_assert(crypto); - - // Send transfer command - uint8_t plain_data[4] = {MF_CLASSIC_TRANSFER_CMD, block_num, 0, 0}; - uint8_t resp = 0; - bool transfer_success = false; - - nfca_append_crc16(plain_data, 2); - crypto1_encrypt( - crypto, NULL, plain_data, sizeof(plain_data) * 8, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_bits = sizeof(plain_data) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw; - - do { - if(furi_hal_nfc_tx_rx(tx_rx, 50)) { - if(tx_rx->rx_bits == 4) { - crypto1_decrypt(crypto, tx_rx->rx_data, 4, &resp); - if(resp != 0x0A) { - FURI_LOG_D(TAG, "NACK received on transfer cmd: %02X", resp); - break; - } - } else { - FURI_LOG_D(TAG, "Not ACK received"); - break; - } - } else { - FURI_LOG_D(TAG, "Failed to send transfer cmd"); - break; - } - - transfer_success = true; - } while(false); - - return transfer_success; -} - -bool mf_classic_value_cmd( - FuriHalNfcTxRxContext* tx_rx, - Crypto1* crypto, - uint8_t block_num, - uint8_t cmd, - int32_t d_value) { - furi_assert(tx_rx); - furi_assert(crypto); - furi_assert( - cmd == MF_CLASSIC_INCREMENT_CMD || cmd == MF_CLASSIC_DECREMENT_CMD || - cmd == MF_CLASSIC_RESTORE_CMD); - furi_assert(d_value >= 0); - - uint8_t plain_data[sizeof(d_value) + 2] = {}; - uint8_t resp = 0; - bool success = false; - - do { - // Send cmd - plain_data[0] = cmd; - plain_data[1] = block_num; - nfca_append_crc16(plain_data, 2); - crypto1_encrypt(crypto, NULL, plain_data, 4 * 8, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_bits = 4 * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw; - - if(furi_hal_nfc_tx_rx(tx_rx, 50)) { - if(tx_rx->rx_bits == 4) { - crypto1_decrypt(crypto, tx_rx->rx_data, 4, &resp); - if(resp != 0x0A) { - FURI_LOG_D(TAG, "NACK received on write cmd: %02X", resp); - break; - } - } else { - FURI_LOG_D(TAG, "Not ACK received"); - break; - } - } else { - FURI_LOG_D(TAG, "Failed to send write cmd"); - break; - } - - // Send data - memcpy(plain_data, &d_value, sizeof(d_value)); - nfca_append_crc16(plain_data, sizeof(d_value)); - crypto1_encrypt( - crypto, NULL, plain_data, (sizeof(d_value) + 2) * 8, tx_rx->tx_data, tx_rx->tx_parity); - tx_rx->tx_bits = (sizeof(d_value) + 2) * 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw; - // inc, dec, restore do not ACK, but they do NACK - if(furi_hal_nfc_tx_rx(tx_rx, 50)) { - if(tx_rx->rx_bits == 4) { - crypto1_decrypt(crypto, tx_rx->rx_data, 4, &resp); - if(resp != 0x0A) { - FURI_LOG_D(TAG, "NACK received on transfer cmd: %02X", resp); - break; - } - } else { - FURI_LOG_D(TAG, "Not NACK received"); - break; - } - } - - success = true; - - } while(false); - - return success; -} - -bool mf_classic_value_cmd_full( - FuriHalNfcTxRxContext* tx_rx, - MfClassicBlock* src_block, - uint8_t block_num, - MfClassicKey key_type, - uint64_t key, - int32_t d_value) { - furi_assert(tx_rx); - furi_assert(src_block); - - Crypto1 crypto = {}; - uint8_t cmd; - bool success = false; - - if(d_value > 0) { - cmd = MF_CLASSIC_INCREMENT_CMD; - } else if(d_value < 0) { - cmd = MF_CLASSIC_DECREMENT_CMD; - d_value = -d_value; - } else { - cmd = MF_CLASSIC_RESTORE_CMD; - } - - do { - furi_hal_nfc_sleep(); - if(!mf_classic_auth(tx_rx, block_num, key, key_type, &crypto, false, 0)) { - FURI_LOG_D(TAG, "Value cmd auth fail"); - break; - } - if(!mf_classic_value_cmd(tx_rx, &crypto, block_num, cmd, d_value)) { - FURI_LOG_D(TAG, "Value cmd inc/dec/res fail"); - break; - } - - if(!mf_classic_transfer(tx_rx, &crypto, block_num)) { - FURI_LOG_D(TAG, "Value cmd transfer fail"); - break; - } - - success = true; - - // Send Halt - mf_classic_halt(tx_rx, &crypto); - } while(false); - - return success; -} - -bool mf_classic_write_sector( - FuriHalNfcTxRxContext* tx_rx, - MfClassicData* dest_data, - MfClassicData* src_data, - uint8_t sec_num) { - furi_assert(tx_rx); - furi_assert(dest_data); - furi_assert(src_data); - - uint8_t first_block = mf_classic_get_first_block_num_of_sector(sec_num); - uint8_t total_blocks = mf_classic_get_blocks_num_in_sector(sec_num); - MfClassicSectorTrailer* sec_tr = mf_classic_get_sector_trailer_by_sector(dest_data, sec_num); - bool key_a_found = mf_classic_is_key_found(dest_data, sec_num, MfClassicKeyA); - bool key_b_found = mf_classic_is_key_found(dest_data, sec_num, MfClassicKeyB); - - bool write_success = true; - for(size_t i = first_block; i < first_block + total_blocks; i++) { - // Compare blocks - if(memcmp(dest_data->block[i].value, src_data->block[i].value, MF_CLASSIC_BLOCK_SIZE) != - 0) { - if(mf_classic_is_value_block(dest_data, i)) { - bool key_a_inc_allowed = mf_classic_is_allowed_access_data_block( - dest_data, i, MfClassicKeyA, MfClassicActionDataInc); - bool key_b_inc_allowed = mf_classic_is_allowed_access_data_block( - dest_data, i, MfClassicKeyB, MfClassicActionDataInc); - bool key_a_dec_allowed = mf_classic_is_allowed_access_data_block( - dest_data, i, MfClassicKeyA, MfClassicActionDataDec); - bool key_b_dec_allowed = mf_classic_is_allowed_access_data_block( - dest_data, i, MfClassicKeyB, MfClassicActionDataDec); - - int32_t src_value, dst_value; - - mf_classic_block_to_value(src_data->block[i].value, &src_value, NULL); - mf_classic_block_to_value(dest_data->block[i].value, &dst_value, NULL); - - int32_t diff = src_value - dst_value; - - if(diff > 0) { - if(key_a_found && key_a_inc_allowed) { - FURI_LOG_I(TAG, "Incrementing block %d with key A by %ld", i, diff); - uint64_t key = nfc_util_bytes2num(sec_tr->key_a, 6); - if(!mf_classic_value_cmd_full( - tx_rx, &src_data->block[i], i, MfClassicKeyA, key, diff)) { - FURI_LOG_E(TAG, "Failed to increment block %d", i); - write_success = false; - break; - } - } else if(key_b_found && key_b_inc_allowed) { - FURI_LOG_I(TAG, "Incrementing block %d with key B by %ld", i, diff); - uint64_t key = nfc_util_bytes2num(sec_tr->key_b, 6); - if(!mf_classic_value_cmd_full( - tx_rx, &src_data->block[i], i, MfClassicKeyB, key, diff)) { - FURI_LOG_E(TAG, "Failed to increment block %d", i); - write_success = false; - break; - } - } else { - FURI_LOG_E(TAG, "Failed to increment block %d", i); - } - } else if(diff < 0) { - if(key_a_found && key_a_dec_allowed) { - FURI_LOG_I(TAG, "Decrementing block %d with key A by %ld", i, -diff); - uint64_t key = nfc_util_bytes2num(sec_tr->key_a, 6); - if(!mf_classic_value_cmd_full( - tx_rx, &src_data->block[i], i, MfClassicKeyA, key, diff)) { - FURI_LOG_E(TAG, "Failed to decrement block %d", i); - write_success = false; - break; - } - } else if(key_b_found && key_b_dec_allowed) { - FURI_LOG_I(TAG, "Decrementing block %d with key B by %ld", i, diff); - uint64_t key = nfc_util_bytes2num(sec_tr->key_b, 6); - if(!mf_classic_value_cmd_full( - tx_rx, &src_data->block[i], i, MfClassicKeyB, key, diff)) { - FURI_LOG_E(TAG, "Failed to decrement block %d", i); - write_success = false; - break; - } - } else { - FURI_LOG_E(TAG, "Failed to decrement block %d", i); - } - } else { - FURI_LOG_E(TAG, "Value block %d address changed, cannot write it", i); - } - } else { - bool key_a_write_allowed = mf_classic_is_allowed_access_data_block( - dest_data, i, MfClassicKeyA, MfClassicActionDataWrite); - bool key_b_write_allowed = mf_classic_is_allowed_access_data_block( - dest_data, i, MfClassicKeyB, MfClassicActionDataWrite); - - if(key_a_found && key_a_write_allowed) { - FURI_LOG_I(TAG, "Writing block %d with key A", i); - uint64_t key = nfc_util_bytes2num(sec_tr->key_a, 6); - if(!mf_classic_auth_write_block( - tx_rx, &src_data->block[i], i, MfClassicKeyA, key)) { - FURI_LOG_E(TAG, "Failed to write block %d", i); - write_success = false; - break; - } - } else if(key_b_found && key_b_write_allowed) { - FURI_LOG_I(TAG, "Writing block %d with key A", i); - uint64_t key = nfc_util_bytes2num(sec_tr->key_b, 6); - if(!mf_classic_auth_write_block( - tx_rx, &src_data->block[i], i, MfClassicKeyB, key)) { - FURI_LOG_E(TAG, "Failed to write block %d", i); - write_success = false; - break; - } - } else { - FURI_LOG_E(TAG, "Failed to find key with write access"); - write_success = false; - break; - } - } - } else { - FURI_LOG_D(TAG, "Blocks %d are equal", i); - } - } - - return write_success; -} diff --git a/lib/nfc/protocols/mifare_classic.h b/lib/nfc/protocols/mifare_classic.h deleted file mode 100644 index 7efe81b8c..000000000 --- a/lib/nfc/protocols/mifare_classic.h +++ /dev/null @@ -1,251 +0,0 @@ -#pragma once - -#include - -#include "crypto1.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define MF_CLASSIC_BLOCK_SIZE (16) -#define MF_CLASSIC_TOTAL_BLOCKS_MAX (256) -#define MF_MINI_TOTAL_SECTORS_NUM (5) -#define MF_CLASSIC_1K_TOTAL_SECTORS_NUM (16) -#define MF_CLASSIC_4K_TOTAL_SECTORS_NUM (40) - -#define MF_CLASSIC_SECTORS_MAX (40) -#define MF_CLASSIC_BLOCKS_IN_SECTOR_MAX (16) - -#define MF_CLASSIC_NO_KEY (0xFFFFFFFFFFFFFFFF) -#define MF_CLASSIC_MAX_DATA_SIZE (16) -#define MF_CLASSIC_KEY_SIZE (6) -#define MF_CLASSIC_ACCESS_BYTES_SIZE (4) - -typedef enum { - MfClassicType1k, - MfClassicType4k, - MfClassicTypeMini, -} MfClassicType; - -typedef enum { - MfClassicKeyA, - MfClassicKeyB, -} MfClassicKey; - -typedef enum { - MfClassicActionDataRead, - MfClassicActionDataWrite, - MfClassicActionDataInc, - MfClassicActionDataDec, - - MfClassicActionKeyARead, - MfClassicActionKeyAWrite, - MfClassicActionKeyBRead, - MfClassicActionKeyBWrite, - MfClassicActionACRead, - MfClassicActionACWrite, -} MfClassicAction; - -typedef struct { - uint8_t value[MF_CLASSIC_BLOCK_SIZE]; -} MfClassicBlock; - -typedef struct { - uint8_t key_a[MF_CLASSIC_KEY_SIZE]; - uint8_t access_bits[MF_CLASSIC_ACCESS_BYTES_SIZE]; - uint8_t key_b[MF_CLASSIC_KEY_SIZE]; -} MfClassicSectorTrailer; - -typedef struct { - uint8_t total_blocks; - MfClassicBlock block[MF_CLASSIC_BLOCKS_IN_SECTOR_MAX]; -} MfClassicSector; - -typedef struct { - MfClassicType type; - uint32_t block_read_mask[MF_CLASSIC_TOTAL_BLOCKS_MAX / 32]; - uint64_t key_a_mask; - uint64_t key_b_mask; - MfClassicBlock block[MF_CLASSIC_TOTAL_BLOCKS_MAX]; -} MfClassicData; - -typedef struct { - uint8_t sector; - uint64_t key_a; - uint64_t key_b; -} MfClassicAuthContext; - -typedef struct { - uint8_t sector_num; - uint64_t key_a; - uint64_t key_b; -} MfClassicSectorReader; - -typedef struct { - MfClassicType type; - Crypto1 crypto; - uint8_t sectors_to_read; - MfClassicSectorReader sector_reader[MF_CLASSIC_SECTORS_MAX]; -} MfClassicReader; - -typedef struct { - uint32_t cuid; - Crypto1 crypto; - MfClassicData data; - bool data_changed; -} MfClassicEmulator; - -const char* mf_classic_get_type_str(MfClassicType type); - -bool mf_classic_check_card_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK); - -MfClassicType mf_classic_get_classic_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK); - -uint8_t mf_classic_get_total_sectors_num(MfClassicType type); - -uint16_t mf_classic_get_total_block_num(MfClassicType type); - -uint8_t mf_classic_get_sector_trailer_block_num_by_sector(uint8_t sector); - -bool mf_classic_is_sector_trailer(uint8_t block); - -uint8_t mf_classic_get_sector_by_block(uint8_t block); - -bool mf_classic_is_allowed_access_sector_trailer( - MfClassicData* data, - uint8_t block_num, - MfClassicKey key, - MfClassicAction action); - -bool mf_classic_is_allowed_access_data_block( - MfClassicData* data, - uint8_t block_num, - MfClassicKey key, - MfClassicAction action); - -bool mf_classic_is_value_block(MfClassicData* data, uint8_t block_num); - -bool mf_classic_block_to_value(const uint8_t* block, int32_t* value, uint8_t* addr); - -void mf_classic_value_to_block(int32_t value, uint8_t addr, uint8_t* block); - -bool mf_classic_is_key_found(MfClassicData* data, uint8_t sector_num, MfClassicKey key_type); - -void mf_classic_set_key_found( - MfClassicData* data, - uint8_t sector_num, - MfClassicKey key_type, - uint64_t key); - -void mf_classic_set_key_not_found(MfClassicData* data, uint8_t sector_num, MfClassicKey key_type); - -bool mf_classic_is_block_read(MfClassicData* data, uint8_t block_num); - -void mf_classic_set_block_read(MfClassicData* data, uint8_t block_num, MfClassicBlock* block_data); - -bool mf_classic_is_sector_data_read(MfClassicData* data, uint8_t sector_num); - -void mf_classic_set_sector_data_not_read(MfClassicData* data); - -bool mf_classic_is_sector_read(MfClassicData* data, uint8_t sector_num); - -bool mf_classic_is_card_read(MfClassicData* data); - -void mf_classic_get_read_sectors_and_keys( - MfClassicData* data, - uint8_t* sectors_read, - uint8_t* keys_found); - -MfClassicSectorTrailer* - mf_classic_get_sector_trailer_by_sector(MfClassicData* data, uint8_t sector); - -void mf_classic_auth_init_context(MfClassicAuthContext* auth_ctx, uint8_t sector); - -bool mf_classic_authenticate( - FuriHalNfcTxRxContext* tx_rx, - uint8_t block_num, - uint64_t key, - MfClassicKey key_type); - -bool mf_classic_authenticate_skip_activate( - FuriHalNfcTxRxContext* tx_rx, - uint8_t block_num, - uint64_t key, - MfClassicKey key_type, - bool skip_activate, - uint32_t cuid); - -bool mf_classic_auth_attempt( - FuriHalNfcTxRxContext* tx_rx, - Crypto1* crypto, - MfClassicAuthContext* auth_ctx, - uint64_t key); - -void mf_classic_reader_add_sector( - MfClassicReader* reader, - uint8_t sector, - uint64_t key_a, - uint64_t key_b); - -bool mf_classic_read_block( - FuriHalNfcTxRxContext* tx_rx, - Crypto1* crypto, - uint8_t block_num, - MfClassicBlock* block); - -void mf_classic_read_sector(FuriHalNfcTxRxContext* tx_rx, MfClassicData* data, uint8_t sec_num); - -uint8_t mf_classic_read_card( - FuriHalNfcTxRxContext* tx_rx, - MfClassicReader* reader, - MfClassicData* data); - -uint8_t mf_classic_update_card(FuriHalNfcTxRxContext* tx_rx, MfClassicData* data); - -bool mf_classic_emulator( - MfClassicEmulator* emulator, - FuriHalNfcTxRxContext* tx_rx, - bool is_reader_analyzer); - -void mf_classic_halt(FuriHalNfcTxRxContext* tx_rx, Crypto1* crypto); - -bool mf_classic_write_block( - FuriHalNfcTxRxContext* tx_rx, - Crypto1* crypto, - uint8_t block_num, - MfClassicBlock* src_block); - -bool mf_classic_auth_write_block( - FuriHalNfcTxRxContext* tx_rx, - MfClassicBlock* src_block, - uint8_t block_num, - MfClassicKey key_type, - uint64_t key); - -bool mf_classic_transfer(FuriHalNfcTxRxContext* tx_rx, Crypto1* crypto, uint8_t block_num); - -bool mf_classic_value_cmd( - FuriHalNfcTxRxContext* tx_rx, - Crypto1* crypto, - uint8_t block_num, - uint8_t cmd, - int32_t d_value); - -bool mf_classic_value_cmd_full( - FuriHalNfcTxRxContext* tx_rx, - MfClassicBlock* src_block, - uint8_t block_num, - MfClassicKey key_type, - uint64_t key, - int32_t d_value); - -bool mf_classic_write_sector( - FuriHalNfcTxRxContext* tx_rx, - MfClassicData* dest_data, - MfClassicData* src_data, - uint8_t sec_num); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/lib/nfc/protocols/mifare_common.c b/lib/nfc/protocols/mifare_common.c deleted file mode 100644 index 5277cc8cd..000000000 --- a/lib/nfc/protocols/mifare_common.c +++ /dev/null @@ -1,19 +0,0 @@ -#include "mifare_common.h" - -MifareType mifare_common_get_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK) { - MifareType type = MifareTypeUnknown; - - if((ATQA0 == 0x44) && (ATQA1 == 0x00) && (SAK == 0x00)) { - type = MifareTypeUltralight; - } else if( - ((ATQA0 == 0x44 || ATQA0 == 0x04) && - (SAK == 0x08 || SAK == 0x88 || SAK == 0x09 || SAK == 0x89)) || - ((ATQA0 == 0x42 || ATQA0 == 0x02) && (SAK == 0x18)) || - ((ATQA0 == 0x01) && (ATQA1 == 0x0F) && (SAK == 0x01))) { - type = MifareTypeClassic; - } else if(ATQA0 == 0x44 && ATQA1 == 0x03 && SAK == 0x20) { - type = MifareTypeDesfire; - } - - return type; -} diff --git a/lib/nfc/protocols/mifare_common.h b/lib/nfc/protocols/mifare_common.h deleted file mode 100644 index 2b694d906..000000000 --- a/lib/nfc/protocols/mifare_common.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -typedef enum { - MifareTypeUnknown, - MifareTypeUltralight, - MifareTypeClassic, - MifareTypeDesfire, -} MifareType; - -MifareType mifare_common_get_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK); diff --git a/lib/nfc/protocols/mifare_desfire.c b/lib/nfc/protocols/mifare_desfire.c deleted file mode 100644 index e0ead737f..000000000 --- a/lib/nfc/protocols/mifare_desfire.c +++ /dev/null @@ -1,665 +0,0 @@ -#include "mifare_desfire.h" -#include -#include - -#define TAG "MifareDESFire" - -void mf_df_clear(MifareDesfireData* data) { - free(data->free_memory); - if(data->master_key_settings) { - MifareDesfireKeyVersion* key_version = data->master_key_settings->key_version_head; - while(key_version) { - MifareDesfireKeyVersion* next_key_version = key_version->next; - free(key_version); - key_version = next_key_version; - } - } - free(data->master_key_settings); - MifareDesfireApplication* app = data->app_head; - while(app) { - MifareDesfireApplication* next_app = app->next; - if(app->key_settings) { - MifareDesfireKeyVersion* key_version = app->key_settings->key_version_head; - while(key_version) { - MifareDesfireKeyVersion* next_key_version = key_version->next; - free(key_version); - key_version = next_key_version; - } - } - free(app->key_settings); - MifareDesfireFile* file = app->file_head; - while(file) { - MifareDesfireFile* next_file = file->next; - free(file->contents); - free(file); - file = next_file; - } - free(app); - app = next_app; - } - data->free_memory = NULL; - data->master_key_settings = NULL; - data->app_head = NULL; -} - -MifareDesfireApplication* mf_df_get_application(MifareDesfireData* data, const uint8_t (*aid)[3]) { - if(!data) { - return NULL; - } - for(MifareDesfireApplication* app = data->app_head; app; app = app->next) { - if(memcmp(aid, app->id, 3) == 0) { - return app; - } - } - return NULL; -} - -MifareDesfireFile* mf_df_get_file(MifareDesfireApplication* app, uint8_t id) { - if(!app) { - return NULL; - } - for(MifareDesfireFile* file = app->file_head; file; file = file->next) { - if(file->id == id) { - return file; - } - } - return NULL; -} - -void mf_df_cat_data(MifareDesfireData* data, FuriString* out) { - mf_df_cat_card_info(data, out); - for(MifareDesfireApplication* app = data->app_head; app; app = app->next) { - mf_df_cat_application(app, out); - } -} - -void mf_df_cat_card_info(MifareDesfireData* data, FuriString* out) { - mf_df_cat_version(&data->version, out); - if(data->free_memory) { - mf_df_cat_free_mem(data->free_memory, out); - } - if(data->master_key_settings) { - mf_df_cat_key_settings(data->master_key_settings, out); - } -} - -void mf_df_cat_version(MifareDesfireVersion* version, FuriString* out) { - furi_string_cat_printf( - out, - "%02x:%02x:%02x:%02x:%02x:%02x:%02x\n", - version->uid[0], - version->uid[1], - version->uid[2], - version->uid[3], - version->uid[4], - version->uid[5], - version->uid[6]); - furi_string_cat_printf( - out, - "hw %02x type %02x sub %02x\n" - " maj %02x min %02x\n" - " size %02x proto %02x\n", - version->hw_vendor, - version->hw_type, - version->hw_subtype, - version->hw_major, - version->hw_minor, - version->hw_storage, - version->hw_proto); - furi_string_cat_printf( - out, - "sw %02x type %02x sub %02x\n" - " maj %02x min %02x\n" - " size %02x proto %02x\n", - version->sw_vendor, - version->sw_type, - version->sw_subtype, - version->sw_major, - version->sw_minor, - version->sw_storage, - version->sw_proto); - furi_string_cat_printf( - out, - "batch %02x:%02x:%02x:%02x:%02x\n" - "week %d year %d\n", - version->batch[0], - version->batch[1], - version->batch[2], - version->batch[3], - version->batch[4], - version->prod_week, - version->prod_year); -} - -void mf_df_cat_free_mem(MifareDesfireFreeMemory* free_mem, FuriString* out) { - furi_string_cat_printf(out, "freeMem %lu\n", free_mem->bytes); -} - -void mf_df_cat_key_settings(MifareDesfireKeySettings* ks, FuriString* out) { - furi_string_cat_printf(out, "changeKeyID %d\n", ks->change_key_id); - furi_string_cat_printf(out, "configChangeable %d\n", ks->config_changeable); - furi_string_cat_printf(out, "freeCreateDelete %d\n", ks->free_create_delete); - furi_string_cat_printf(out, "freeDirectoryList %d\n", ks->free_directory_list); - furi_string_cat_printf(out, "masterChangeable %d\n", ks->master_key_changeable); - if(ks->flags) { - furi_string_cat_printf(out, "flags %d\n", ks->flags); - } - furi_string_cat_printf(out, "maxKeys %d\n", ks->max_keys); - for(MifareDesfireKeyVersion* kv = ks->key_version_head; kv; kv = kv->next) { - furi_string_cat_printf(out, "key %d version %d\n", kv->id, kv->version); - } -} - -void mf_df_cat_application_info(MifareDesfireApplication* app, FuriString* out) { - furi_string_cat_printf(out, "Application %02x%02x%02x\n", app->id[0], app->id[1], app->id[2]); - if(app->key_settings) { - mf_df_cat_key_settings(app->key_settings, out); - } -} - -void mf_df_cat_application(MifareDesfireApplication* app, FuriString* out) { - mf_df_cat_application_info(app, out); - for(MifareDesfireFile* file = app->file_head; file; file = file->next) { - mf_df_cat_file(file, out); - } -} - -void mf_df_cat_file(MifareDesfireFile* file, FuriString* out) { - char* type = "unknown"; - switch(file->type) { - case MifareDesfireFileTypeStandard: - type = "standard"; - break; - case MifareDesfireFileTypeBackup: - type = "backup"; - break; - case MifareDesfireFileTypeValue: - type = "value"; - break; - case MifareDesfireFileTypeLinearRecord: - type = "linear"; - break; - case MifareDesfireFileTypeCyclicRecord: - type = "cyclic"; - break; - } - char* comm = "unknown"; - switch(file->comm) { - case MifareDesfireFileCommunicationSettingsPlaintext: - comm = "plain"; - break; - case MifareDesfireFileCommunicationSettingsAuthenticated: - comm = "auth"; - break; - case MifareDesfireFileCommunicationSettingsEnciphered: - comm = "enciphered"; - break; - } - furi_string_cat_printf(out, "File %d\n", file->id); - furi_string_cat_printf(out, "%s %s\n", type, comm); - furi_string_cat_printf( - out, - "r %d w %d rw %d c %d\n", - file->access_rights >> 12 & 0xF, - file->access_rights >> 8 & 0xF, - file->access_rights >> 4 & 0xF, - file->access_rights & 0xF); - uint16_t size = 0; - uint16_t num = 1; - switch(file->type) { - case MifareDesfireFileTypeStandard: - case MifareDesfireFileTypeBackup: - size = file->settings.data.size; - furi_string_cat_printf(out, "size %d\n", size); - break; - case MifareDesfireFileTypeValue: - size = 4; - furi_string_cat_printf( - out, "lo %lu hi %lu\n", file->settings.value.lo_limit, file->settings.value.hi_limit); - furi_string_cat_printf( - out, - "limit %lu enabled %d\n", - file->settings.value.limited_credit_value, - file->settings.value.limited_credit_enabled); - break; - case MifareDesfireFileTypeLinearRecord: - case MifareDesfireFileTypeCyclicRecord: - size = file->settings.record.size; - num = file->settings.record.cur; - furi_string_cat_printf(out, "size %d\n", size); - furi_string_cat_printf(out, "num %d max %lu\n", num, file->settings.record.max); - break; - } - uint8_t* data = file->contents; - if(data) { - for(int rec = 0; rec < num; rec++) { - furi_string_cat_printf(out, "record %d\n", rec); - for(int ch = 0; ch < size; ch += 4) { - furi_string_cat_printf(out, "%03x|", ch); - for(int i = 0; i < 4; i++) { - if(ch + i < size) { - furi_string_cat_printf(out, "%02x ", data[rec * size + ch + i]); - } else { - furi_string_cat_printf(out, " "); - } - } - for(int i = 0; i < 4 && ch + i < size; i++) { - const size_t data_index = rec * size + ch + i; - if(isprint(data[data_index])) { - furi_string_cat_printf(out, "%c", data[data_index]); - } else { - furi_string_cat_printf(out, "."); - } - } - furi_string_cat_printf(out, "\n"); - } - furi_string_cat_printf(out, " \n"); - } - } -} - -bool mf_df_check_card_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK) { - return ATQA0 == 0x44 && ATQA1 == 0x03 && SAK == 0x20; -} - -uint16_t mf_df_prepare_get_version(uint8_t* dest) { - dest[0] = MF_DF_GET_VERSION; - return 1; -} - -bool mf_df_parse_get_version_response(uint8_t* buf, uint16_t len, MifareDesfireVersion* out) { - if(len < 1 || *buf) { - return false; - } - len--; - buf++; - if(len < sizeof(MifareDesfireVersion)) { - return false; - } - memcpy(out, buf, sizeof(MifareDesfireVersion)); - return true; -} - -uint16_t mf_df_prepare_get_free_memory(uint8_t* dest) { - dest[0] = MF_DF_GET_FREE_MEMORY; - return 1; -} - -bool mf_df_parse_get_free_memory_response(uint8_t* buf, uint16_t len, MifareDesfireFreeMemory* out) { - if(len < 1 || *buf) { - return false; - } - len--; - buf++; - if(len != 3) { - return false; - } - out->bytes = buf[0] | (buf[1] << 8) | (buf[2] << 16); - return true; -} - -uint16_t mf_df_prepare_get_key_settings(uint8_t* dest) { - dest[0] = MF_DF_GET_KEY_SETTINGS; - return 1; -} - -bool mf_df_parse_get_key_settings_response( - uint8_t* buf, - uint16_t len, - MifareDesfireKeySettings* out) { - if(len < 1 || *buf) { - return false; - } - len--; - buf++; - if(len < 2) { - return false; - } - out->change_key_id = buf[0] >> 4; - out->config_changeable = (buf[0] & 0x8) != 0; - out->free_create_delete = (buf[0] & 0x4) != 0; - out->free_directory_list = (buf[0] & 0x2) != 0; - out->master_key_changeable = (buf[0] & 0x1) != 0; - out->flags = buf[1] >> 4; - out->max_keys = buf[1] & 0xF; - return true; -} - -uint16_t mf_df_prepare_get_key_version(uint8_t* dest, uint8_t key_id) { - dest[0] = MF_DF_GET_KEY_VERSION; - dest[1] = key_id; - return 2; -} - -bool mf_df_parse_get_key_version_response(uint8_t* buf, uint16_t len, MifareDesfireKeyVersion* out) { - if(len != 2 || *buf) { - return false; - } - out->version = buf[1]; - return true; -} - -uint16_t mf_df_prepare_get_application_ids(uint8_t* dest) { - dest[0] = MF_DF_GET_APPLICATION_IDS; - return 1; -} - -bool mf_df_parse_get_application_ids_response( - uint8_t* buf, - uint16_t len, - MifareDesfireApplication** app_head) { - if(len < 1 || *buf) { - return false; - } - len--; - buf++; - if(len % 3 != 0) { - return false; - } - while(len) { - MifareDesfireApplication* app = malloc(sizeof(MifareDesfireApplication)); - memset(app, 0, sizeof(MifareDesfireApplication)); - memcpy(app->id, buf, 3); - len -= 3; - buf += 3; - *app_head = app; - app_head = &app->next; - } - return true; -} - -uint16_t mf_df_prepare_select_application(uint8_t* dest, uint8_t id[3]) { - dest[0] = MF_DF_SELECT_APPLICATION; - dest[1] = id[0]; - dest[2] = id[1]; - dest[3] = id[2]; - return 4; -} - -bool mf_df_parse_select_application_response(uint8_t* buf, uint16_t len) { - return len == 1 && !*buf; -} - -uint16_t mf_df_prepare_get_file_ids(uint8_t* dest) { - dest[0] = MF_DF_GET_FILE_IDS; - return 1; -} - -bool mf_df_parse_get_file_ids_response(uint8_t* buf, uint16_t len, MifareDesfireFile** file_head) { - if(len < 1 || *buf) { - return false; - } - len--; - buf++; - while(len) { - MifareDesfireFile* file = malloc(sizeof(MifareDesfireFile)); - memset(file, 0, sizeof(MifareDesfireFile)); - file->id = *buf; - len--; - buf++; - *file_head = file; - file_head = &file->next; - } - return true; -} - -uint16_t mf_df_prepare_get_file_settings(uint8_t* dest, uint8_t file_id) { - dest[0] = MF_DF_GET_FILE_SETTINGS; - dest[1] = file_id; - return 2; -} - -bool mf_df_parse_get_file_settings_response(uint8_t* buf, uint16_t len, MifareDesfireFile* out) { - if(len < 5 || *buf) { - return false; - } - len--; - buf++; - out->type = buf[0]; - out->comm = buf[1]; - out->access_rights = buf[2] | (buf[3] << 8); - switch(out->type) { - case MifareDesfireFileTypeStandard: - case MifareDesfireFileTypeBackup: - if(len != 7) { - return false; - } - out->settings.data.size = buf[4] | (buf[5] << 8) | (buf[6] << 16); - break; - case MifareDesfireFileTypeValue: - if(len != 17) { - return false; - } - out->settings.value.lo_limit = buf[4] | (buf[5] << 8) | (buf[6] << 16) | (buf[7] << 24); - out->settings.value.hi_limit = buf[8] | (buf[9] << 8) | (buf[10] << 16) | (buf[11] << 24); - out->settings.value.limited_credit_value = buf[12] | (buf[13] << 8) | (buf[14] << 16) | - (buf[15] << 24); - out->settings.value.limited_credit_enabled = buf[16]; - break; - case MifareDesfireFileTypeLinearRecord: - case MifareDesfireFileTypeCyclicRecord: - if(len != 13) { - return false; - } - out->settings.record.size = buf[4] | (buf[5] << 8) | (buf[6] << 16); - out->settings.record.max = buf[7] | (buf[8] << 8) | (buf[9] << 16); - out->settings.record.cur = buf[10] | (buf[11] << 8) | (buf[12] << 16); - break; - default: - return false; - } - return true; -} - -uint16_t mf_df_prepare_read_data(uint8_t* dest, uint8_t file_id, uint32_t offset, uint32_t len) { - dest[0] = MF_DF_READ_DATA; - dest[1] = file_id; - dest[2] = offset; - dest[3] = offset >> 8; - dest[4] = offset >> 16; - dest[5] = len; - dest[6] = len >> 8; - dest[7] = len >> 16; - return 8; -} - -uint16_t mf_df_prepare_get_value(uint8_t* dest, uint8_t file_id) { - dest[0] = MF_DF_GET_VALUE; - dest[1] = file_id; - return 2; -} - -uint16_t - mf_df_prepare_read_records(uint8_t* dest, uint8_t file_id, uint32_t offset, uint32_t len) { - dest[0] = MF_DF_READ_RECORDS; - dest[1] = file_id; - dest[2] = offset; - dest[3] = offset >> 8; - dest[4] = offset >> 16; - dest[5] = len; - dest[6] = len >> 8; - dest[7] = len >> 16; - return 8; -} - -bool mf_df_parse_read_data_response(uint8_t* buf, uint16_t len, MifareDesfireFile* out) { - if(len < 1 || *buf) { - return false; - } - len--; - buf++; - out->contents = malloc(len); - memcpy(out->contents, buf, len); - return true; -} - -bool mf_df_read_card(FuriHalNfcTxRxContext* tx_rx, MifareDesfireData* data) { - furi_assert(tx_rx); - furi_assert(data); - - bool card_read = false; - do { - // Get version - tx_rx->tx_bits = 8 * mf_df_prepare_get_version(tx_rx->tx_data); - if(!furi_hal_nfc_tx_rx_full(tx_rx)) { - FURI_LOG_W(TAG, "Bad exchange getting version"); - break; - } - if(!mf_df_parse_get_version_response(tx_rx->rx_data, tx_rx->rx_bits / 8, &data->version)) { - FURI_LOG_W(TAG, "Bad DESFire GET_VERSION responce"); - } - - // Get free memory - tx_rx->tx_bits = 8 * mf_df_prepare_get_free_memory(tx_rx->tx_data); - if(furi_hal_nfc_tx_rx_full(tx_rx)) { - data->free_memory = malloc(sizeof(MifareDesfireFreeMemory)); - if(!mf_df_parse_get_free_memory_response( - tx_rx->rx_data, tx_rx->rx_bits / 8, data->free_memory)) { - FURI_LOG_D(TAG, "Bad DESFire GET_FREE_MEMORY response (normal for pre-EV1 cards)"); - free(data->free_memory); - data->free_memory = NULL; - } - } - - // Get key settings - tx_rx->tx_bits = 8 * mf_df_prepare_get_key_settings(tx_rx->tx_data); - if(!furi_hal_nfc_tx_rx_full(tx_rx)) { - FURI_LOG_D(TAG, "Bad exchange getting key settings"); - } else { - data->master_key_settings = malloc(sizeof(MifareDesfireKeySettings)); - if(!mf_df_parse_get_key_settings_response( - tx_rx->rx_data, tx_rx->rx_bits / 8, data->master_key_settings)) { - FURI_LOG_W(TAG, "Bad DESFire GET_KEY_SETTINGS response"); - free(data->master_key_settings); - data->master_key_settings = NULL; - } else { - MifareDesfireKeyVersion** key_version_head = - &data->master_key_settings->key_version_head; - for(uint8_t key_id = 0; key_id < data->master_key_settings->max_keys; key_id++) { - tx_rx->tx_bits = 8 * mf_df_prepare_get_key_version(tx_rx->tx_data, key_id); - if(!furi_hal_nfc_tx_rx_full(tx_rx)) { - FURI_LOG_W(TAG, "Bad exchange getting key version"); - continue; - } - MifareDesfireKeyVersion* key_version = malloc(sizeof(MifareDesfireKeyVersion)); - memset(key_version, 0, sizeof(MifareDesfireKeyVersion)); - key_version->id = key_id; - if(!mf_df_parse_get_key_version_response( - tx_rx->rx_data, tx_rx->rx_bits / 8, key_version)) { - FURI_LOG_W(TAG, "Bad DESFire GET_KEY_VERSION response"); - free(key_version); - continue; - } - *key_version_head = key_version; - key_version_head = &key_version->next; - } - } - } - - // Get application IDs - tx_rx->tx_bits = 8 * mf_df_prepare_get_application_ids(tx_rx->tx_data); - if(!furi_hal_nfc_tx_rx_full(tx_rx)) { - FURI_LOG_W(TAG, "Bad exchange getting application IDs"); - break; - } else { - if(!mf_df_parse_get_application_ids_response( - tx_rx->rx_data, tx_rx->rx_bits / 8, &data->app_head)) { - FURI_LOG_W(TAG, "Bad DESFire GET_APPLICATION_IDS response"); - break; - } - } - - for(MifareDesfireApplication* app = data->app_head; app; app = app->next) { - tx_rx->tx_bits = 8 * mf_df_prepare_select_application(tx_rx->tx_data, app->id); - if(!furi_hal_nfc_tx_rx_full(tx_rx) || - !mf_df_parse_select_application_response( - tx_rx->rx_data, tx_rx->rx_bits / 8)) { //-V1051 - FURI_LOG_W(TAG, "Bad exchange selecting application"); - continue; - } - tx_rx->tx_bits = 8 * mf_df_prepare_get_key_settings(tx_rx->tx_data); - if(!furi_hal_nfc_tx_rx_full(tx_rx)) { - FURI_LOG_W(TAG, "Bad exchange getting key settings"); - } else { - app->key_settings = malloc(sizeof(MifareDesfireKeySettings)); - memset(app->key_settings, 0, sizeof(MifareDesfireKeySettings)); - if(!mf_df_parse_get_key_settings_response( - tx_rx->rx_data, tx_rx->rx_bits / 8, app->key_settings)) { - FURI_LOG_W(TAG, "Bad DESFire GET_KEY_SETTINGS response"); - free(app->key_settings); - app->key_settings = NULL; - continue; - } - - MifareDesfireKeyVersion** key_version_head = &app->key_settings->key_version_head; - for(uint8_t key_id = 0; key_id < app->key_settings->max_keys; key_id++) { - tx_rx->tx_bits = 8 * mf_df_prepare_get_key_version(tx_rx->tx_data, key_id); - if(!furi_hal_nfc_tx_rx_full(tx_rx)) { - FURI_LOG_W(TAG, "Bad exchange getting key version"); - continue; - } - MifareDesfireKeyVersion* key_version = malloc(sizeof(MifareDesfireKeyVersion)); - memset(key_version, 0, sizeof(MifareDesfireKeyVersion)); - key_version->id = key_id; - if(!mf_df_parse_get_key_version_response( - tx_rx->rx_data, tx_rx->rx_bits / 8, key_version)) { - FURI_LOG_W(TAG, "Bad DESFire GET_KEY_VERSION response"); - free(key_version); - continue; - } - *key_version_head = key_version; - key_version_head = &key_version->next; - } - } - - tx_rx->tx_bits = 8 * mf_df_prepare_get_file_ids(tx_rx->tx_data); - if(!furi_hal_nfc_tx_rx_full(tx_rx)) { - FURI_LOG_W(TAG, "Bad exchange getting file IDs"); - } else { - if(!mf_df_parse_get_file_ids_response( - tx_rx->rx_data, tx_rx->rx_bits / 8, &app->file_head)) { - FURI_LOG_W(TAG, "Bad DESFire GET_FILE_IDS response"); - } - } - - for(MifareDesfireFile* file = app->file_head; file; file = file->next) { - tx_rx->tx_bits = 8 * mf_df_prepare_get_file_settings(tx_rx->tx_data, file->id); - if(!furi_hal_nfc_tx_rx_full(tx_rx)) { - FURI_LOG_W(TAG, "Bad exchange getting file settings"); - continue; - } - if(!mf_df_parse_get_file_settings_response( - tx_rx->rx_data, tx_rx->rx_bits / 8, file)) { - FURI_LOG_W(TAG, "Bad DESFire GET_FILE_SETTINGS response"); - continue; - } - switch(file->type) { - case MifareDesfireFileTypeStandard: - case MifareDesfireFileTypeBackup: - tx_rx->tx_bits = 8 * mf_df_prepare_read_data(tx_rx->tx_data, file->id, 0, 0); - break; - case MifareDesfireFileTypeValue: - tx_rx->tx_bits = 8 * mf_df_prepare_get_value(tx_rx->tx_data, file->id); - break; - case MifareDesfireFileTypeLinearRecord: - case MifareDesfireFileTypeCyclicRecord: - tx_rx->tx_bits = - 8 * mf_df_prepare_read_records(tx_rx->tx_data, file->id, 0, 0); - break; - } - if(!furi_hal_nfc_tx_rx_full(tx_rx)) { - FURI_LOG_W(TAG, "Bad exchange reading file %d", file->id); - continue; - } - if(!mf_df_parse_read_data_response(tx_rx->rx_data, tx_rx->rx_bits / 8, file)) { - FURI_LOG_W(TAG, "Bad response reading file %d", file->id); - continue; - } - } - } - - card_read = true; - } while(false); - - return card_read; -} diff --git a/lib/nfc/protocols/mifare_desfire.h b/lib/nfc/protocols/mifare_desfire.h deleted file mode 100644 index 8faa98ec2..000000000 --- a/lib/nfc/protocols/mifare_desfire.h +++ /dev/null @@ -1,179 +0,0 @@ -#pragma once - -#include -#include - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define MF_DF_GET_VERSION (0x60) -#define MF_DF_GET_FREE_MEMORY (0x6E) -#define MF_DF_GET_KEY_SETTINGS (0x45) -#define MF_DF_GET_KEY_VERSION (0x64) -#define MF_DF_GET_APPLICATION_IDS (0x6A) -#define MF_DF_SELECT_APPLICATION (0x5A) -#define MF_DF_GET_FILE_IDS (0x6F) -#define MF_DF_GET_FILE_SETTINGS (0xF5) - -#define MF_DF_READ_DATA (0xBD) -#define MF_DF_GET_VALUE (0x6C) -#define MF_DF_READ_RECORDS (0xBB) - -typedef struct { - uint8_t hw_vendor; - uint8_t hw_type; - uint8_t hw_subtype; - uint8_t hw_major; - uint8_t hw_minor; - uint8_t hw_storage; - uint8_t hw_proto; - - uint8_t sw_vendor; - uint8_t sw_type; - uint8_t sw_subtype; - uint8_t sw_major; - uint8_t sw_minor; - uint8_t sw_storage; - uint8_t sw_proto; - - uint8_t uid[7]; - uint8_t batch[5]; - uint8_t prod_week; - uint8_t prod_year; -} MifareDesfireVersion; - -typedef struct { - uint32_t bytes; -} MifareDesfireFreeMemory; // EV1+ only - -typedef struct MifareDesfireKeyVersion { - uint8_t id; - uint8_t version; - struct MifareDesfireKeyVersion* next; -} MifareDesfireKeyVersion; - -typedef struct { - uint8_t change_key_id; - bool config_changeable; - bool free_create_delete; - bool free_directory_list; - bool master_key_changeable; - uint8_t flags; - uint8_t max_keys; - MifareDesfireKeyVersion* key_version_head; -} MifareDesfireKeySettings; - -typedef enum { - MifareDesfireFileTypeStandard = 0, - MifareDesfireFileTypeBackup = 1, - MifareDesfireFileTypeValue = 2, - MifareDesfireFileTypeLinearRecord = 3, - MifareDesfireFileTypeCyclicRecord = 4, -} MifareDesfireFileType; - -typedef enum { - MifareDesfireFileCommunicationSettingsPlaintext = 0, - MifareDesfireFileCommunicationSettingsAuthenticated = 1, - MifareDesfireFileCommunicationSettingsEnciphered = 3, -} MifareDesfireFileCommunicationSettings; - -typedef struct MifareDesfireFile { - uint8_t id; - MifareDesfireFileType type; - MifareDesfireFileCommunicationSettings comm; - uint16_t access_rights; - union { - struct { - uint32_t size; - } data; - struct { - uint32_t lo_limit; - uint32_t hi_limit; - uint32_t limited_credit_value; - bool limited_credit_enabled; - } value; - struct { - uint32_t size; - uint32_t max; - uint32_t cur; - } record; - } settings; - uint8_t* contents; - - struct MifareDesfireFile* next; -} MifareDesfireFile; - -typedef struct MifareDesfireApplication { - uint8_t id[3]; - MifareDesfireKeySettings* key_settings; - MifareDesfireFile* file_head; - - struct MifareDesfireApplication* next; -} MifareDesfireApplication; - -typedef struct { - MifareDesfireVersion version; - MifareDesfireFreeMemory* free_memory; - MifareDesfireKeySettings* master_key_settings; - MifareDesfireApplication* app_head; -} MifareDesfireData; - -void mf_df_clear(MifareDesfireData* data); - -void mf_df_cat_data(MifareDesfireData* data, FuriString* out); -void mf_df_cat_card_info(MifareDesfireData* data, FuriString* out); -void mf_df_cat_version(MifareDesfireVersion* version, FuriString* out); -void mf_df_cat_free_mem(MifareDesfireFreeMemory* free_mem, FuriString* out); -void mf_df_cat_key_settings(MifareDesfireKeySettings* ks, FuriString* out); -void mf_df_cat_application_info(MifareDesfireApplication* app, FuriString* out); -void mf_df_cat_application(MifareDesfireApplication* app, FuriString* out); -void mf_df_cat_file(MifareDesfireFile* file, FuriString* out); - -bool mf_df_check_card_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK); - -MifareDesfireApplication* mf_df_get_application(MifareDesfireData* data, const uint8_t (*aid)[3]); -MifareDesfireFile* mf_df_get_file(MifareDesfireApplication* app, uint8_t id); - -uint16_t mf_df_prepare_get_version(uint8_t* dest); -bool mf_df_parse_get_version_response(uint8_t* buf, uint16_t len, MifareDesfireVersion* out); - -uint16_t mf_df_prepare_get_free_memory(uint8_t* dest); -bool mf_df_parse_get_free_memory_response(uint8_t* buf, uint16_t len, MifareDesfireFreeMemory* out); - -uint16_t mf_df_prepare_get_key_settings(uint8_t* dest); -bool mf_df_parse_get_key_settings_response( - uint8_t* buf, - uint16_t len, - MifareDesfireKeySettings* out); - -uint16_t mf_df_prepare_get_key_version(uint8_t* dest, uint8_t key_id); -bool mf_df_parse_get_key_version_response(uint8_t* buf, uint16_t len, MifareDesfireKeyVersion* out); - -uint16_t mf_df_prepare_get_application_ids(uint8_t* dest); -bool mf_df_parse_get_application_ids_response( - uint8_t* buf, - uint16_t len, - MifareDesfireApplication** app_head); - -uint16_t mf_df_prepare_select_application(uint8_t* dest, uint8_t id[3]); -bool mf_df_parse_select_application_response(uint8_t* buf, uint16_t len); - -uint16_t mf_df_prepare_get_file_ids(uint8_t* dest); -bool mf_df_parse_get_file_ids_response(uint8_t* buf, uint16_t len, MifareDesfireFile** file_head); - -uint16_t mf_df_prepare_get_file_settings(uint8_t* dest, uint8_t file_id); -bool mf_df_parse_get_file_settings_response(uint8_t* buf, uint16_t len, MifareDesfireFile* out); - -uint16_t mf_df_prepare_read_data(uint8_t* dest, uint8_t file_id, uint32_t offset, uint32_t len); -uint16_t mf_df_prepare_get_value(uint8_t* dest, uint8_t file_id); -uint16_t mf_df_prepare_read_records(uint8_t* dest, uint8_t file_id, uint32_t offset, uint32_t len); -bool mf_df_parse_read_data_response(uint8_t* buf, uint16_t len, MifareDesfireFile* out); - -bool mf_df_read_card(FuriHalNfcTxRxContext* tx_rx, MifareDesfireData* data); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/lib/nfc/protocols/mifare_ultralight.c b/lib/nfc/protocols/mifare_ultralight.c deleted file mode 100644 index 266b6e2e2..000000000 --- a/lib/nfc/protocols/mifare_ultralight.c +++ /dev/null @@ -1,1946 +0,0 @@ -#include -#include -#include "mifare_ultralight.h" -#include "nfc_util.h" -#include -#include - -#define TAG "MfUltralight" - -// Algorithms from: https://github.com/RfidResearchGroup/proxmark3/blob/0f6061c16f072372b7d4d381911f1542afbc3a69/common/generator.c#L110 -uint32_t mf_ul_pwdgen_xiaomi(FuriHalNfcDevData* data) { - uint8_t hash[20]; - mbedtls_sha1(data->uid, data->uid_len, hash); - - uint32_t pwd = 0; - pwd |= (hash[hash[0] % 20]) << 24; - pwd |= (hash[(hash[0] + 5) % 20]) << 16; - pwd |= (hash[(hash[0] + 13) % 20]) << 8; - pwd |= (hash[(hash[0] + 17) % 20]); - - return pwd; -} - -uint32_t mf_ul_pwdgen_amiibo(FuriHalNfcDevData* data) { - uint8_t* uid = data->uid; - - uint32_t pwd = 0; - pwd |= (uid[1] ^ uid[3] ^ 0xAA) << 24; - pwd |= (uid[2] ^ uid[4] ^ 0x55) << 16; - pwd |= (uid[3] ^ uid[5] ^ 0xAA) << 8; - pwd |= uid[4] ^ uid[6] ^ 0x55; - - return pwd; -} - -bool mf_ul_check_card_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK) { - if((ATQA0 == 0x44) && (ATQA1 == 0x00) && (SAK == 0x00)) { - return true; - } - return false; -} - -void mf_ul_reset(MfUltralightData* data) { - furi_assert(data); - data->type = MfUltralightTypeUnknown; - memset(&data->version, 0, sizeof(MfUltralightVersion)); - memset(data->signature, 0, sizeof(data->signature)); - memset(data->counter, 0, sizeof(data->counter)); - memset(data->tearing, 0, sizeof(data->tearing)); - memset(data->data, 0, sizeof(data->data)); - data->data_size = 0; - data->data_read = 0; - data->curr_authlim = 0; - data->auth_success = false; -} - -static MfUltralightFeatures mf_ul_get_features(MfUltralightType type) { - switch(type) { - case MfUltralightTypeUL11: - case MfUltralightTypeUL21: - return MfUltralightSupportFastRead | MfUltralightSupportCompatWrite | - MfUltralightSupportReadCounter | MfUltralightSupportIncrCounter | - MfUltralightSupportAuth | MfUltralightSupportSignature | - MfUltralightSupportTearingFlags | MfUltralightSupportVcsl; - case MfUltralightTypeNTAG213: - case MfUltralightTypeNTAG215: - case MfUltralightTypeNTAG216: - return MfUltralightSupportFastRead | MfUltralightSupportCompatWrite | - MfUltralightSupportReadCounter | MfUltralightSupportAuth | - MfUltralightSupportSignature | MfUltralightSupportSingleCounter | - MfUltralightSupportAsciiMirror; - case MfUltralightTypeNTAGI2C1K: - case MfUltralightTypeNTAGI2C2K: - return MfUltralightSupportFastRead | MfUltralightSupportSectorSelect; - case MfUltralightTypeNTAGI2CPlus1K: - case MfUltralightTypeNTAGI2CPlus2K: - return MfUltralightSupportFastRead | MfUltralightSupportAuth | - MfUltralightSupportFastWrite | MfUltralightSupportSignature | - MfUltralightSupportSectorSelect; - case MfUltralightTypeNTAG203: - return MfUltralightSupportCompatWrite | MfUltralightSupportCounterInMemory; - case MfUltralightTypeULC: - return MfUltralightSupportCompatWrite | MfUltralightSupport3DesAuth; - default: - // Assumed original MFUL 512-bit - return MfUltralightSupportCompatWrite; - } -} - -static void mf_ul_set_default_version(MfUltralightReader* reader, MfUltralightData* data) { - data->type = MfUltralightTypeUnknown; - reader->pages_to_read = 16; -} - -static void mf_ul_set_version_ntag203(MfUltralightReader* reader, MfUltralightData* data) { - data->type = MfUltralightTypeNTAG203; - reader->pages_to_read = 42; -} - -static void mf_ul_set_version_ulc(MfUltralightReader* reader, MfUltralightData* data) { - data->type = MfUltralightTypeULC; - reader->pages_to_read = 48; -} - -bool mf_ultralight_read_version( - FuriHalNfcTxRxContext* tx_rx, - MfUltralightReader* reader, - MfUltralightData* data) { - bool version_read = false; - - do { - FURI_LOG_D(TAG, "Reading version"); - tx_rx->tx_data[0] = MF_UL_GET_VERSION_CMD; - tx_rx->tx_bits = 8; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - if(!furi_hal_nfc_tx_rx(tx_rx, 50) || tx_rx->rx_bits != 64) { - FURI_LOG_D(TAG, "Failed reading version"); - mf_ul_set_default_version(reader, data); - furi_hal_nfc_sleep(); - furi_hal_nfc_activate_nfca(300, NULL); - break; - } - MfUltralightVersion* version = (MfUltralightVersion*)tx_rx->rx_data; - data->version = *version; - if(version->storage_size == 0x0B || version->storage_size == 0x00) { - data->type = MfUltralightTypeUL11; - reader->pages_to_read = 20; - } else if(version->storage_size == 0x0E) { - data->type = MfUltralightTypeUL21; - reader->pages_to_read = 41; - } else if(version->storage_size == 0x0F) { - data->type = MfUltralightTypeNTAG213; - reader->pages_to_read = 45; - } else if(version->storage_size == 0x11) { - data->type = MfUltralightTypeNTAG215; - reader->pages_to_read = 135; - } else if(version->prod_subtype == 5 && version->prod_ver_major == 2) { - // NTAG I2C - bool known = false; - if(version->prod_ver_minor == 1) { - if(version->storage_size == 0x13) { - data->type = MfUltralightTypeNTAGI2C1K; - reader->pages_to_read = 231; - known = true; - } else if(version->storage_size == 0x15) { - data->type = MfUltralightTypeNTAGI2C2K; - reader->pages_to_read = 485; - known = true; - } - } else if(version->prod_ver_minor == 2) { - if(version->storage_size == 0x13) { - data->type = MfUltralightTypeNTAGI2CPlus1K; - reader->pages_to_read = 236; - known = true; - } else if(version->storage_size == 0x15) { - data->type = MfUltralightTypeNTAGI2CPlus2K; - reader->pages_to_read = 492; - known = true; - } - } - - if(!known) { - mf_ul_set_default_version(reader, data); - } - } else if(version->storage_size == 0x13) { - data->type = MfUltralightTypeNTAG216; - reader->pages_to_read = 231; - } else { - mf_ul_set_default_version(reader, data); - break; - } - version_read = true; - } while(false); - - reader->supported_features = mf_ul_get_features(data->type); - return version_read; -} - -bool mf_ultralight_authenticate(FuriHalNfcTxRxContext* tx_rx, uint32_t key, uint16_t* pack) { - furi_assert(pack); - bool authenticated = false; - - do { - FURI_LOG_D(TAG, "Authenticating"); - tx_rx->tx_data[0] = MF_UL_PWD_AUTH; - nfc_util_num2bytes(key, 4, &tx_rx->tx_data[1]); - tx_rx->tx_bits = 40; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - if(!furi_hal_nfc_tx_rx(tx_rx, 50)) { - FURI_LOG_D(TAG, "Tag did not respond to authentication"); - break; - } - - // PACK - if(tx_rx->rx_bits < 2 * 8) { - FURI_LOG_D(TAG, "Authentication failed"); - break; - } - - *pack = (tx_rx->rx_data[1] << 8) | tx_rx->rx_data[0]; - - FURI_LOG_I(TAG, "Auth success. Password: %08lX. PACK: %04X", key, *pack); - authenticated = true; - } while(false); - - return authenticated; -} - -static int16_t mf_ultralight_page_addr_to_tag_addr(uint8_t sector, uint8_t page) { - return sector * 256 + page; -} - -static int16_t mf_ultralight_ntag_i2c_addr_lin_to_tag_1k( - int16_t linear_address, - uint8_t* sector, - int16_t* valid_pages) { - // 0 - 226: sector 0 - // 227 - 228: config registers - // 229 - 230: session registers - - if(linear_address > 230) { - *valid_pages = 0; - return -1; - } else if(linear_address >= 229) { - *sector = 3; - *valid_pages = 2 - (linear_address - 229); - return linear_address - 229 + 248; - } else if(linear_address >= 227) { - *sector = 0; - *valid_pages = 2 - (linear_address - 227); - return linear_address - 227 + 232; - } else { - *sector = 0; - *valid_pages = 227 - linear_address; - return linear_address; - } -} - -static int16_t mf_ultralight_ntag_i2c_addr_lin_to_tag_2k( - int16_t linear_address, - uint8_t* sector, - int16_t* valid_pages) { - // 0 - 255: sector 0 - // 256 - 480: sector 1 - // 481 - 482: config registers - // 483 - 484: session registers - - if(linear_address > 484) { - *valid_pages = 0; - return -1; - } else if(linear_address >= 483) { - *sector = 3; - *valid_pages = 2 - (linear_address - 483); - return linear_address - 483 + 248; - } else if(linear_address >= 481) { - *sector = 1; - *valid_pages = 2 - (linear_address - 481); - return linear_address - 481 + 232; - } else if(linear_address >= 256) { - *sector = 1; - *valid_pages = 225 - (linear_address - 256); - return linear_address - 256; - } else { - *sector = 0; - *valid_pages = 256 - linear_address; - return linear_address; - } -} - -static int16_t mf_ultralight_ntag_i2c_addr_lin_to_tag_plus_1k( - int16_t linear_address, - uint8_t* sector, - int16_t* valid_pages) { - // 0 - 233: sector 0 + registers - // 234 - 235: session registers - - if(linear_address > 235) { - *valid_pages = 0; - return -1; - } else if(linear_address >= 234) { - *sector = 0; - *valid_pages = 2 - (linear_address - 234); - return linear_address - 234 + 236; - } else { - *sector = 0; - *valid_pages = 234 - linear_address; - return linear_address; - } -} - -static int16_t mf_ultralight_ntag_i2c_addr_lin_to_tag_plus_2k( - int16_t linear_address, - uint8_t* sector, - int16_t* valid_pages) { - // 0 - 233: sector 0 + registers - // 234 - 235: session registers - // 236 - 491: sector 1 - - if(linear_address > 491) { - *valid_pages = 0; - return -1; - } else if(linear_address >= 236) { - *sector = 1; - *valid_pages = 256 - (linear_address - 236); - return linear_address - 236; - } else if(linear_address >= 234) { - *sector = 0; - *valid_pages = 2 - (linear_address - 234); - return linear_address - 234 + 236; - } else { - *sector = 0; - *valid_pages = 234 - linear_address; - return linear_address; - } -} - -static int16_t mf_ultralight_ntag_i2c_addr_lin_to_tag( - MfUltralightData* data, - MfUltralightReader* reader, - int16_t linear_address, - uint8_t* sector, - int16_t* valid_pages) { - switch(data->type) { - case MfUltralightTypeNTAGI2C1K: - return mf_ultralight_ntag_i2c_addr_lin_to_tag_1k(linear_address, sector, valid_pages); - - case MfUltralightTypeNTAGI2C2K: - return mf_ultralight_ntag_i2c_addr_lin_to_tag_2k(linear_address, sector, valid_pages); - - case MfUltralightTypeNTAGI2CPlus1K: - return mf_ultralight_ntag_i2c_addr_lin_to_tag_plus_1k(linear_address, sector, valid_pages); - - case MfUltralightTypeNTAGI2CPlus2K: - return mf_ultralight_ntag_i2c_addr_lin_to_tag_plus_2k(linear_address, sector, valid_pages); - - default: - *sector = 0xff; - *valid_pages = reader->pages_to_read - linear_address; - return linear_address; - } -} - -static int16_t - mf_ultralight_ntag_i2c_addr_tag_to_lin_1k(uint8_t page, uint8_t sector, uint16_t* valid_pages) { - bool valid = false; - int16_t translated_page; - if(sector == 0) { - if(page <= 226) { - *valid_pages = 227 - page; - translated_page = page; - valid = true; - } else if(page >= 232 && page <= 233) { - *valid_pages = 2 - (page - 232); - translated_page = page - 232 + 227; - valid = true; - } - } else if(sector == 3) { - if(page >= 248 && page <= 249) { - *valid_pages = 2 - (page - 248); - translated_page = page - 248 + 229; - valid = true; - } - } - - if(!valid) { - *valid_pages = 0; - translated_page = -1; - } - return translated_page; -} - -static int16_t - mf_ultralight_ntag_i2c_addr_tag_to_lin_2k(uint8_t page, uint8_t sector, uint16_t* valid_pages) { - bool valid = false; - int16_t translated_page; - if(sector == 0) { - *valid_pages = 256 - page; - translated_page = page; - valid = true; - } else if(sector == 1) { - if(page <= 224) { - *valid_pages = 225 - page; - translated_page = 256 + page; - valid = true; - } else if(page >= 232 && page <= 233) { - *valid_pages = 2 - (page - 232); - translated_page = page - 232 + 481; - valid = true; - } - } else if(sector == 3) { - if(page >= 248 && page <= 249) { - *valid_pages = 2 - (page - 248); - translated_page = page - 248 + 483; - valid = true; - } - } - - if(!valid) { - *valid_pages = 0; - translated_page = -1; - } - return translated_page; -} - -static int16_t mf_ultralight_ntag_i2c_addr_tag_to_lin_plus_1k( - uint8_t page, - uint8_t sector, - uint16_t* valid_pages) { - bool valid = false; - int16_t translated_page; - if(sector == 0) { - if(page <= 233) { - *valid_pages = 234 - page; - translated_page = page; - valid = true; - } else if(page >= 236 && page <= 237) { - *valid_pages = 2 - (page - 236); - translated_page = page - 236 + 234; - valid = true; - } - } else if(sector == 3) { - if(page >= 248 && page <= 249) { - *valid_pages = 2 - (page - 248); - translated_page = page - 248 + 234; - valid = true; - } - } - - if(!valid) { - *valid_pages = 0; - translated_page = -1; - } - return translated_page; -} - -static int16_t mf_ultralight_ntag_i2c_addr_tag_to_lin_plus_2k( - uint8_t page, - uint8_t sector, - uint16_t* valid_pages) { - bool valid = false; - int16_t translated_page; - if(sector == 0) { - if(page <= 233) { - *valid_pages = 234 - page; - translated_page = page; - valid = true; - } else if(page >= 236 && page <= 237) { - *valid_pages = 2 - (page - 236); - translated_page = page - 236 + 234; - valid = true; - } - } else if(sector == 1) { - *valid_pages = 256 - page; - translated_page = page + 236; - valid = true; - } else if(sector == 3) { - if(page >= 248 && page <= 249) { - *valid_pages = 2 - (page - 248); - translated_page = page - 248 + 234; - valid = true; - } - } - - if(!valid) { - *valid_pages = 0; - translated_page = -1; - } - return translated_page; -} - -static int16_t mf_ultralight_ntag_i2c_addr_tag_to_lin( - MfUltralightData* data, - uint8_t page, - uint8_t sector, - uint16_t* valid_pages) { - switch(data->type) { - case MfUltralightTypeNTAGI2C1K: - return mf_ultralight_ntag_i2c_addr_tag_to_lin_1k(page, sector, valid_pages); - - case MfUltralightTypeNTAGI2C2K: - return mf_ultralight_ntag_i2c_addr_tag_to_lin_2k(page, sector, valid_pages); - - case MfUltralightTypeNTAGI2CPlus1K: - return mf_ultralight_ntag_i2c_addr_tag_to_lin_plus_1k(page, sector, valid_pages); - - case MfUltralightTypeNTAGI2CPlus2K: - return mf_ultralight_ntag_i2c_addr_tag_to_lin_plus_2k(page, sector, valid_pages); - - default: - *valid_pages = data->data_size / 4 - page; - return page; - } -} - -MfUltralightConfigPages* mf_ultralight_get_config_pages(MfUltralightData* data) { - if(data->type >= MfUltralightTypeUL11 && data->type <= MfUltralightTypeNTAG216) { - return (MfUltralightConfigPages*)&data->data[data->data_size - 4 * 4]; - } else if( - data->type >= MfUltralightTypeNTAGI2CPlus1K && - data->type <= MfUltralightTypeNTAGI2CPlus2K) { - return (MfUltralightConfigPages*)&data->data[0xe3 * 4]; //-V641 - } else { - return NULL; - } -} - -static uint16_t mf_ultralight_calc_auth_count(MfUltralightData* data) { - if(mf_ul_get_features(data->type) & MfUltralightSupportAuth) { - MfUltralightConfigPages* config = mf_ultralight_get_config_pages(data); - uint16_t scaled_authlim = config->access.authlim; - // NTAG I2C Plus uses 2^AUTHLIM attempts rather than the direct number - if(scaled_authlim > 0 && data->type >= MfUltralightTypeNTAGI2CPlus1K && - data->type <= MfUltralightTypeNTAGI2CPlus2K) { - scaled_authlim = 1 << scaled_authlim; - } - return scaled_authlim; - } - - return 0; -} - -// NTAG21x will NAK if NFC_CNT_EN unset, so preempt -static bool mf_ultralight_should_read_counters(MfUltralightData* data) { - if(data->type < MfUltralightTypeNTAG213 || data->type > MfUltralightTypeNTAG216) return true; - - MfUltralightConfigPages* config = mf_ultralight_get_config_pages(data); - return config->access.nfc_cnt_en; -} - -static bool mf_ultralight_sector_select(FuriHalNfcTxRxContext* tx_rx, uint8_t sector) { - FURI_LOG_D(TAG, "Selecting sector %u", sector); - tx_rx->tx_data[0] = MF_UL_SECTOR_SELECT; - tx_rx->tx_data[1] = 0xff; - tx_rx->tx_bits = 16; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - if(!furi_hal_nfc_tx_rx(tx_rx, 50)) { - FURI_LOG_D(TAG, "Failed to issue sector select command"); - return false; - } - - tx_rx->tx_data[0] = sector; - tx_rx->tx_data[1] = 0x00; - tx_rx->tx_data[2] = 0x00; - tx_rx->tx_data[3] = 0x00; - tx_rx->tx_bits = 32; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - // This is NOT a typo! The tag ACKs by not sending a response within 1ms. - if(furi_hal_nfc_tx_rx(tx_rx, 20)) { - // TODO: what gets returned when an actual NAK is received? - FURI_LOG_D(TAG, "Sector %u select NAK'd", sector); - return false; - } - - return true; -} - -bool mf_ultralight_read_pages_direct( - FuriHalNfcTxRxContext* tx_rx, - uint8_t start_index, - uint8_t* data) { - FURI_LOG_D(TAG, "Reading pages %d - %d", start_index, start_index + 3); - tx_rx->tx_data[0] = MF_UL_READ_CMD; - tx_rx->tx_data[1] = start_index; - tx_rx->tx_bits = 16; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - if(!furi_hal_nfc_tx_rx(tx_rx, 50) || tx_rx->rx_bits < 16 * 8) { - FURI_LOG_D(TAG, "Failed to read pages %d - %d", start_index, start_index + 3); - return false; - } - memcpy(data, tx_rx->rx_data, 16); //-V1086 - return true; -} - -bool mf_ultralight_read_pages( - FuriHalNfcTxRxContext* tx_rx, - MfUltralightReader* reader, - MfUltralightData* data) { - uint8_t pages_read_cnt = 0; - uint8_t curr_sector_index = 0xff; - reader->pages_read = 0; - for(size_t i = 0; i < reader->pages_to_read; i += pages_read_cnt) { - uint8_t tag_sector; - int16_t valid_pages; - int16_t tag_page = mf_ultralight_ntag_i2c_addr_lin_to_tag( - data, reader, (int16_t)i, &tag_sector, &valid_pages); - - furi_assert(tag_page != -1); - if(curr_sector_index != tag_sector) { - if(!mf_ultralight_sector_select(tx_rx, tag_sector)) return false; - curr_sector_index = tag_sector; - } - - FURI_LOG_D( - TAG, "Reading pages %zu - %zu", i, i + (valid_pages > 4 ? 4 : valid_pages) - 1U); - tx_rx->tx_data[0] = MF_UL_READ_CMD; - tx_rx->tx_data[1] = tag_page; - tx_rx->tx_bits = 16; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - - if(!furi_hal_nfc_tx_rx(tx_rx, 50) || tx_rx->rx_bits < 16 * 8) { - FURI_LOG_D( - TAG, - "Failed to read pages %zu - %zu", - i, - i + (valid_pages > 4 ? 4 : valid_pages) - 1U); - break; - } - - if(valid_pages > 4) { - pages_read_cnt = 4; - } else { - pages_read_cnt = valid_pages; - } - reader->pages_read += pages_read_cnt; - memcpy(&data->data[i * 4], tx_rx->rx_data, pages_read_cnt * 4); - } - data->data_size = reader->pages_to_read * 4; - data->data_read = reader->pages_read * 4; - - return reader->pages_read > 0; -} - -bool mf_ultralight_fast_read_pages( - FuriHalNfcTxRxContext* tx_rx, - MfUltralightReader* reader, - MfUltralightData* data) { - uint8_t curr_sector_index = 0xff; - reader->pages_read = 0; - while(reader->pages_read < reader->pages_to_read) { - uint8_t tag_sector; - int16_t valid_pages; - int16_t tag_page = mf_ultralight_ntag_i2c_addr_lin_to_tag( - data, reader, reader->pages_read, &tag_sector, &valid_pages); - - furi_assert(tag_page != -1); - if(curr_sector_index != tag_sector) { - if(!mf_ultralight_sector_select(tx_rx, tag_sector)) return false; - curr_sector_index = tag_sector; - } - - FURI_LOG_D( - TAG, "Reading pages %d - %d", reader->pages_read, reader->pages_read + valid_pages - 1); - tx_rx->tx_data[0] = MF_UL_FAST_READ_CMD; - tx_rx->tx_data[1] = tag_page; - tx_rx->tx_data[2] = valid_pages - 1; - tx_rx->tx_bits = 24; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - if(furi_hal_nfc_tx_rx(tx_rx, 50)) { - memcpy(&data->data[reader->pages_read * 4], tx_rx->rx_data, valid_pages * 4); - reader->pages_read += valid_pages; - data->data_size = reader->pages_read * 4; - } else { - FURI_LOG_D( - TAG, - "Failed to read pages %d - %d", - reader->pages_read, - reader->pages_read + valid_pages - 1); - break; - } - } - - return reader->pages_read == reader->pages_to_read; -} - -bool mf_ultralight_read_signature(FuriHalNfcTxRxContext* tx_rx, MfUltralightData* data) { - bool signature_read = false; - - FURI_LOG_D(TAG, "Reading signature"); - tx_rx->tx_data[0] = MF_UL_READ_SIG; - tx_rx->tx_data[1] = 0; - tx_rx->tx_bits = 16; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - if(furi_hal_nfc_tx_rx(tx_rx, 50)) { - memcpy(data->signature, tx_rx->rx_data, sizeof(data->signature)); - signature_read = true; - } else { - FURI_LOG_D(TAG, "Failed redaing signature"); - } - - return signature_read; -} - -bool mf_ultralight_read_counters(FuriHalNfcTxRxContext* tx_rx, MfUltralightData* data) { - uint8_t counter_read = 0; - - FURI_LOG_D(TAG, "Reading counters"); - bool is_single_counter = (mf_ul_get_features(data->type) & MfUltralightSupportSingleCounter) != - 0; - for(size_t i = is_single_counter ? 2 : 0; i < 3; i++) { - tx_rx->tx_data[0] = MF_UL_READ_CNT; - tx_rx->tx_data[1] = i; - tx_rx->tx_bits = 16; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - if(!furi_hal_nfc_tx_rx(tx_rx, 50)) { - FURI_LOG_D(TAG, "Failed to read %d counter", i); - break; - } - data->counter[i] = (tx_rx->rx_data[2] << 16) | (tx_rx->rx_data[1] << 8) | - tx_rx->rx_data[0]; - counter_read++; - } - - return counter_read == (is_single_counter ? 1 : 3); -} - -bool mf_ultralight_read_tearing_flags(FuriHalNfcTxRxContext* tx_rx, MfUltralightData* data) { - uint8_t flag_read = 0; - - FURI_LOG_D(TAG, "Reading tearing flags"); - for(size_t i = 0; i < 3; i++) { - tx_rx->tx_data[0] = MF_UL_CHECK_TEARING; - tx_rx->tx_data[1] = i; - tx_rx->tx_bits = 16; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - if(!furi_hal_nfc_tx_rx(tx_rx, 50)) { - FURI_LOG_D(TAG, "Failed to read %d tearing flag", i); - break; - } - data->tearing[i] = tx_rx->rx_data[0]; - flag_read++; - } - - return flag_read == 2; -} - -static bool mf_ul_probe_3des_auth(FuriHalNfcTxRxContext* tx_rx) { - tx_rx->tx_data[0] = MF_UL_AUTHENTICATE_1; - tx_rx->tx_data[1] = 0; - tx_rx->tx_bits = 16; - tx_rx->tx_rx_type = FuriHalNfcTxRxTypeDefault; - bool rc = furi_hal_nfc_tx_rx(tx_rx, 50) && tx_rx->rx_bits == 9 * 8 && - tx_rx->rx_data[0] == 0xAF; - - // Reset just in case, we're not going to finish authenticating and need to if tag doesn't support auth - furi_hal_nfc_sleep(); - furi_hal_nfc_activate_nfca(300, NULL); - - return rc; -} - -bool mf_ul_read_card( - FuriHalNfcTxRxContext* tx_rx, - MfUltralightReader* reader, - MfUltralightData* data) { - furi_assert(tx_rx); - furi_assert(reader); - furi_assert(data); - - bool card_read = false; - - // Read Mifare Ultralight version - if(mf_ultralight_read_version(tx_rx, reader, data)) { - if(reader->supported_features & MfUltralightSupportSignature) { - // Read Signature - mf_ultralight_read_signature(tx_rx, data); - } - } else { - uint8_t dummy[16]; - // No GET_VERSION command, check if AUTHENTICATE command available (detect UL C). - if(mf_ul_probe_3des_auth(tx_rx)) { - mf_ul_set_version_ulc(reader, data); - } else if(mf_ultralight_read_pages_direct(tx_rx, 41, dummy)) { - // No AUTHENTICATE, check for NTAG203 by reading last page (41) - mf_ul_set_version_ntag203(reader, data); - } else { - // We're really an original Mifare Ultralight, reset tag for safety - furi_hal_nfc_sleep(); - furi_hal_nfc_activate_nfca(300, NULL); - } - - reader->supported_features = mf_ul_get_features(data->type); - } - - card_read = mf_ultralight_read_pages(tx_rx, reader, data); - - if(card_read) { - if(reader->supported_features & MfUltralightSupportReadCounter && - mf_ultralight_should_read_counters(data)) { - mf_ultralight_read_counters(tx_rx, data); - } - if(reader->supported_features & MfUltralightSupportTearingFlags) { - mf_ultralight_read_tearing_flags(tx_rx, data); - } - data->curr_authlim = 0; - - if(reader->pages_read == reader->pages_to_read && - reader->supported_features & MfUltralightSupportAuth && !data->auth_success) { - MfUltralightConfigPages* config = mf_ultralight_get_config_pages(data); - if(config->access.authlim == 0) { - // Attempt to auth with default PWD - uint16_t pack; - data->auth_success = mf_ultralight_authenticate(tx_rx, MF_UL_DEFAULT_PWD, &pack); - if(data->auth_success) { - config->auth_data.pwd.value = MF_UL_DEFAULT_PWD; - config->auth_data.pack.value = pack; - } else { - furi_hal_nfc_sleep(); - furi_hal_nfc_activate_nfca(300, NULL); - } - } - } - } - - if(reader->pages_read != reader->pages_to_read) { - if(reader->supported_features & MfUltralightSupportAuth) { - // Probably password protected, fix AUTH0 and PROT so before AUTH0 - // can be written and since AUTH0 won't be readable, like on the - // original card - MfUltralightConfigPages* config = mf_ultralight_get_config_pages(data); - config->auth0 = reader->pages_read; - config->access.prot = true; - } - } - - return card_read; -} - -static void mf_ul_protect_auth_data_on_read_command_i2c( - uint8_t* tx_buff, - uint8_t start_page, - uint8_t end_page, - MfUltralightEmulator* emulator) { - if(emulator->data.type >= MfUltralightTypeNTAGI2CPlus1K) { - // Blank out PWD and PACK - if(start_page <= 229 && end_page >= 229) { - uint16_t offset = (229 - start_page) * 4; - uint8_t count = 4; - if(end_page >= 230) count += 2; - memset(&tx_buff[offset], 0, count); - } - - // Handle AUTH0 for sector 0 - if(!emulator->auth_success) { - if(emulator->config_cache.access.prot) { - uint8_t auth0 = emulator->config_cache.auth0; - if(auth0 < end_page) { - // start_page is always < auth0; otherwise is NAK'd already - uint8_t page_offset = auth0 - start_page; - uint8_t page_count = end_page - auth0; - memset(&tx_buff[page_offset * 4], 0, page_count * 4); - } - } - } - } -} - -static void mf_ul_ntag_i2c_fill_cross_area_read( - uint8_t* tx_buff, - uint8_t start_page, - uint8_t end_page, - MfUltralightEmulator* emulator) { - // For copying config or session registers in fast read - int16_t tx_page_offset; - int16_t data_page_offset; - uint8_t page_length; - bool apply = false; - MfUltralightType type = emulator->data.type; - if(emulator->curr_sector == 0) { - if(type == MfUltralightTypeNTAGI2C1K) { - if(start_page <= 233 && end_page >= 232) { - tx_page_offset = start_page - 232; - data_page_offset = 227; - page_length = 2; - apply = true; - } - } else if(type == MfUltralightTypeNTAGI2CPlus1K || type == MfUltralightTypeNTAGI2CPlus2K) { - if(start_page <= 237 && end_page >= 236) { - tx_page_offset = start_page - 236; - data_page_offset = 234; - page_length = 2; - apply = true; - } - } - } else if(emulator->curr_sector == 1) { - if(type == MfUltralightTypeNTAGI2C2K) { - if(start_page <= 233 && end_page >= 232) { - tx_page_offset = start_page - 232; - data_page_offset = 483; - page_length = 2; - apply = true; - } - } - } - - if(apply) { - while(tx_page_offset < 0 && page_length > 0) { //-V614 - ++tx_page_offset; - ++data_page_offset; - --page_length; - } - memcpy( - &tx_buff[tx_page_offset * 4], - &emulator->data.data[data_page_offset * 4], - page_length * 4); - } -} - -static bool mf_ul_check_auth(MfUltralightEmulator* emulator, uint8_t start_page, bool is_write) { - if(!emulator->auth_success) { - if(start_page >= emulator->config_cache.auth0 && - (emulator->config_cache.access.prot || is_write)) - return false; - } - - if(is_write && emulator->config_cache.access.cfglck) { - uint16_t config_start_page = emulator->page_num - 4; - if(start_page == config_start_page || start_page == config_start_page + 1) return false; - } - - return true; -} - -static bool mf_ul_ntag_i2c_plus_check_auth( - MfUltralightEmulator* emulator, - uint8_t start_page, - bool is_write) { - if(!emulator->auth_success) { - // Check NFC_PROT - if(emulator->curr_sector == 0 && (emulator->config_cache.access.prot || is_write)) { - if(start_page >= emulator->config_cache.auth0) return false; - } else if(emulator->curr_sector == 1) { - // We don't have to specifically check for type because this is done - // by address translator - uint8_t pt_i2c = emulator->data.data[231 * 4]; - // Check 2K_PROT - if(pt_i2c & 0x08) return false; - } - } - - if(emulator->curr_sector == 1) { - // Check NFC_DIS_SEC1 - if(emulator->config_cache.access.nfc_dis_sec1) return false; - } - - return true; -} - -static int16_t mf_ul_get_dynamic_lock_page_addr(MfUltralightData* data) { - switch(data->type) { - case MfUltralightTypeNTAG203: - return 0x28; - case MfUltralightTypeUL21: - case MfUltralightTypeNTAG213: - case MfUltralightTypeNTAG215: - case MfUltralightTypeNTAG216: - return data->data_size / 4 - 5; - case MfUltralightTypeNTAGI2C1K: - case MfUltralightTypeNTAGI2CPlus1K: - case MfUltralightTypeNTAGI2CPlus2K: - return 0xe2; - case MfUltralightTypeNTAGI2C2K: - return 0x1e0; - default: - return -1; // No dynamic lock bytes - } -} - -// Returns true if page not locked -// write_page is tag address -static bool mf_ul_check_lock(MfUltralightEmulator* emulator, int16_t write_page) { - if(write_page < 2) return false; // Page 0-1 is always locked - if(write_page == 2) return true; // Page 2 does not have a lock flag - - // Check static lock bytes - if(write_page <= 15) { - uint16_t static_lock_bytes = emulator->data.data[10] | (emulator->data.data[11] << 8); - return (static_lock_bytes & (1 << write_page)) == 0; - } - - // Check dynamic lock bytes - - // Check max page - switch(emulator->data.type) { - case MfUltralightTypeNTAG203: - // Counter page can be locked and is after dynamic locks - if(write_page == 40) return true; - break; - case MfUltralightTypeUL21: - case MfUltralightTypeNTAG213: - case MfUltralightTypeNTAG215: - case MfUltralightTypeNTAG216: - if(write_page >= emulator->page_num - 5) return true; - break; - case MfUltralightTypeNTAGI2C1K: - case MfUltralightTypeNTAGI2CPlus1K: - if(write_page > 225) return true; - break; - case MfUltralightTypeNTAGI2C2K: - if(write_page > 479) return true; - break; - case MfUltralightTypeNTAGI2CPlus2K: - if(write_page >= 226 && write_page <= 255) return true; - if(write_page >= 512) return true; - break; - default: - furi_crash("Unknown MFUL"); - return true; - } - - int16_t dynamic_lock_index = mf_ul_get_dynamic_lock_page_addr(&emulator->data); - if(dynamic_lock_index == -1) return true; - // Run address through converter because NTAG I2C 2K is special - uint16_t valid_pages; // unused - dynamic_lock_index = - mf_ultralight_ntag_i2c_addr_tag_to_lin( - &emulator->data, dynamic_lock_index & 0xff, dynamic_lock_index >> 8, &valid_pages) * - 4; - - uint16_t dynamic_lock_bytes = emulator->data.data[dynamic_lock_index] | - (emulator->data.data[dynamic_lock_index + 1] << 8); - uint8_t shift; - - switch(emulator->data.type) { - // low byte LSB range, MSB range - case MfUltralightTypeNTAG203: - if(write_page >= 16 && write_page <= 27) //-V560 - shift = (write_page - 16) / 4 + 1; - else if(write_page >= 28 && write_page <= 39) //-V560 - shift = (write_page - 28) / 4 + 5; - else if(write_page == 41) - shift = 12; - else { - furi_crash("Unknown MFUL"); - } - - break; - case MfUltralightTypeUL21: - case MfUltralightTypeNTAG213: - // 16-17, 30-31 - shift = (write_page - 16) / 2; - break; - case MfUltralightTypeNTAG215: - case MfUltralightTypeNTAG216: - case MfUltralightTypeNTAGI2C1K: - case MfUltralightTypeNTAGI2CPlus1K: - // 16-31, 128-129 - // 16-31, 128-143 - shift = (write_page - 16) / 16; - break; - case MfUltralightTypeNTAGI2C2K: - // 16-47, 240-271 - shift = (write_page - 16) / 32; - break; - case MfUltralightTypeNTAGI2CPlus2K: - // 16-47, 256-271 - if(write_page >= 208 && write_page <= 225) - shift = 6; - else if(write_page >= 256 && write_page <= 271) - shift = 7; - else - shift = (write_page - 16) / 32; - break; - default: - furi_crash("Unknown MFUL"); - break; - } - - return (dynamic_lock_bytes & (1 << shift)) == 0; -} - -static void mf_ul_make_ascii_mirror(MfUltralightEmulator* emulator, FuriString* str) { - // Locals to improve readability - uint8_t mirror_page = emulator->config->mirror_page; - uint8_t mirror_byte = emulator->config->mirror.mirror_byte; - MfUltralightMirrorConf mirror_conf = emulator->config_cache.mirror.mirror_conf; - uint16_t last_user_page_index = emulator->page_num - 6; - bool uid_printed = false; - - if(mirror_conf == MfUltralightMirrorUid || mirror_conf == MfUltralightMirrorUidCounter) { - // UID range check - if(mirror_page < 4 || mirror_page > last_user_page_index - 3 || - (mirror_page == last_user_page_index - 3 && mirror_byte > 2)) { - if(mirror_conf == MfUltralightMirrorUid) return; - // NTAG21x has the peculiar behavior when UID+counter selected, if UID does not fit but - // counter will fit, it will actually mirror the counter - furi_string_cat(str, " "); - } else { - for(int i = 0; i < 3; ++i) { - furi_string_cat_printf(str, "%02X", emulator->data.data[i]); - } - // Skip BCC0 - for(int i = 4; i < 8; ++i) { - furi_string_cat_printf(str, "%02X", emulator->data.data[i]); - } - uid_printed = true; - } - - uint16_t next_byte_offset = mirror_page * 4 + mirror_byte + 14; - if(mirror_conf == MfUltralightMirrorUidCounter) ++next_byte_offset; - mirror_page = next_byte_offset / 4; - mirror_byte = next_byte_offset % 4; - } - - if(mirror_conf == MfUltralightMirrorCounter || mirror_conf == MfUltralightMirrorUidCounter) { - // Counter is only printed if counter enabled - if(emulator->config_cache.access.nfc_cnt_en) { - // Counter protection check - if(emulator->config_cache.access.nfc_cnt_pwd_prot && !emulator->auth_success) return; - // Counter range check - if(mirror_page < 4) return; - if(mirror_page > last_user_page_index - 1) return; - if(mirror_page == last_user_page_index - 1 && mirror_byte > 2) return; - - if(mirror_conf == MfUltralightMirrorUidCounter) - furi_string_cat(str, uid_printed ? "x" : " "); - - furi_string_cat_printf(str, "%06lX", emulator->data.counter[2]); - } - } -} - -static void mf_ul_increment_single_counter(MfUltralightEmulator* emulator) { - if(!emulator->read_counter_incremented && emulator->config_cache.access.nfc_cnt_en) { - if(emulator->data.counter[2] < 0xFFFFFF) { - ++emulator->data.counter[2]; - emulator->data_changed = true; - } - emulator->read_counter_incremented = true; - } -} - -static bool - mf_ul_emulate_ntag203_counter_write(MfUltralightEmulator* emulator, uint8_t* page_buff) { - // We'll reuse the existing counters for other NTAGs as staging - // Counter 0 stores original value, data is new value - uint32_t counter_value; - if(emulator->data.tearing[0] == MF_UL_TEARING_FLAG_DEFAULT) { - counter_value = emulator->data.data[MF_UL_NTAG203_COUNTER_PAGE * 4] | - (emulator->data.data[MF_UL_NTAG203_COUNTER_PAGE * 4 + 1] << 8); - } else { - // We've had a reset here, so load from original value - counter_value = emulator->data.counter[0]; - } - // Although the datasheet says increment by 0 is always possible, this is not the case on - // an actual tag. If the counter is at 0xFFFF, any writes are locked out. - if(counter_value == 0xFFFF) return false; - uint32_t increment = page_buff[0] | (page_buff[1] << 8); - if(counter_value == 0) { - counter_value = increment; - } else { - // Per datasheet specifying > 0x000F is supposed to NAK, but actual tag doesn't - increment &= 0x000F; - if(counter_value + increment > 0xFFFF) return false; - counter_value += increment; - } - // Commit to new value counter - emulator->data.data[MF_UL_NTAG203_COUNTER_PAGE * 4] = (uint8_t)counter_value; - emulator->data.data[MF_UL_NTAG203_COUNTER_PAGE * 4 + 1] = (uint8_t)(counter_value >> 8); - emulator->data.tearing[0] = MF_UL_TEARING_FLAG_DEFAULT; - if(counter_value == 0xFFFF) { - // Tag will lock out counter if final number is 0xFFFF, even if you try to roll it back - emulator->data.counter[1] = 0xFFFF; - } - emulator->data_changed = true; - return true; -} - -static void mf_ul_emulate_write( - MfUltralightEmulator* emulator, - int16_t tag_addr, - int16_t write_page, - uint8_t* page_buff) { - // Assumption: all access checks have been completed - - if(tag_addr == 2) { - // Handle static locks - uint16_t orig_static_locks = emulator->data.data[write_page * 4 + 2] | - (emulator->data.data[write_page * 4 + 3] << 8); - uint16_t new_static_locks = page_buff[2] | (page_buff[3] << 8); - if(orig_static_locks & 1) new_static_locks &= ~0x08; - if(orig_static_locks & 2) new_static_locks &= ~0xF0; - if(orig_static_locks & 4) new_static_locks &= 0xFF; - new_static_locks |= orig_static_locks; - page_buff[0] = emulator->data.data[write_page * 4]; - page_buff[1] = emulator->data.data[write_page * 4 + 1]; - page_buff[2] = new_static_locks & 0xff; - page_buff[3] = new_static_locks >> 8; - } else if(tag_addr == 3) { - // Handle OTP/capability container - *(uint32_t*)page_buff |= *(uint32_t*)&emulator->data.data[write_page * 4]; - } else if(tag_addr == mf_ul_get_dynamic_lock_page_addr(&emulator->data)) { - // Handle dynamic locks - if(emulator->data.type == MfUltralightTypeNTAG203) { - // NTAG203 lock bytes are a bit different from the others - uint8_t orig_page_lock_byte = emulator->data.data[write_page * 4]; - uint8_t orig_cnt_lock_byte = emulator->data.data[write_page * 4 + 1]; - uint8_t new_page_lock_byte = page_buff[0]; - uint8_t new_cnt_lock_byte = page_buff[1]; - - if(orig_page_lock_byte & 0x01) // Block lock bits 1-3 - new_page_lock_byte &= ~0x0E; - if(orig_page_lock_byte & 0x10) // Block lock bits 5-7 - new_page_lock_byte &= ~0xE0; - for(uint8_t i = 0; i < 4; ++i) { - if(orig_cnt_lock_byte & (1 << i)) // Block lock counter bit - new_cnt_lock_byte &= ~(1 << (4 + i)); - } - - new_page_lock_byte |= orig_page_lock_byte; - new_cnt_lock_byte |= orig_cnt_lock_byte; - page_buff[0] = new_page_lock_byte; - page_buff[1] = new_cnt_lock_byte; - } else { - uint16_t orig_locks = emulator->data.data[write_page * 4] | - (emulator->data.data[write_page * 4 + 1] << 8); - uint8_t orig_block_locks = emulator->data.data[write_page * 4 + 2]; - uint16_t new_locks = page_buff[0] | (page_buff[1] << 8); - uint8_t new_block_locks = page_buff[2]; - - int block_lock_count; - switch(emulator->data.type) { - case MfUltralightTypeUL21: - block_lock_count = 5; - break; - case MfUltralightTypeNTAG213: - block_lock_count = 6; - break; - case MfUltralightTypeNTAG215: - block_lock_count = 4; - break; - case MfUltralightTypeNTAG216: - case MfUltralightTypeNTAGI2C1K: - case MfUltralightTypeNTAGI2CPlus1K: - block_lock_count = 7; - break; - case MfUltralightTypeNTAGI2C2K: - case MfUltralightTypeNTAGI2CPlus2K: - block_lock_count = 8; - break; - default: - furi_crash("Unknown MFUL"); - break; - } - - for(int i = 0; i < block_lock_count; ++i) { - if(orig_block_locks & (1 << i)) new_locks &= ~(3 << (2 * i)); - } - - new_locks |= orig_locks; - new_block_locks |= orig_block_locks; - - page_buff[0] = new_locks & 0xff; - page_buff[1] = new_locks >> 8; - page_buff[2] = new_block_locks; - if(emulator->data.type >= MfUltralightTypeUL21 && //-V1016 - emulator->data.type <= MfUltralightTypeNTAG216) - page_buff[3] = MF_UL_TEARING_FLAG_DEFAULT; - else - page_buff[3] = 0; - } - } - - memcpy(&emulator->data.data[write_page * 4], page_buff, 4); - emulator->data_changed = true; -} - -bool mf_ul_emulation_supported(MfUltralightData* data) { - return data->type != MfUltralightTypeULC; -} - -void mf_ul_reset_emulation(MfUltralightEmulator* emulator, bool is_power_cycle) { - emulator->comp_write_cmd_started = false; - emulator->sector_select_cmd_started = false; - emulator->curr_sector = 0; - emulator->ntag_i2c_plus_sector3_lockout = false; - emulator->auth_success = false; - if(is_power_cycle) { - if(emulator->config != NULL) emulator->config_cache = *emulator->config; - - if(emulator->supported_features & MfUltralightSupportSingleCounter) { - emulator->read_counter_incremented = false; - } - - if(emulator->data.type == MfUltralightTypeNTAG203) { - // Apply lockout if counter ever reached 0xFFFF - if(emulator->data.counter[1] == 0xFFFF) { - emulator->data.data[MF_UL_NTAG203_COUNTER_PAGE * 4] = 0xFF; - emulator->data.data[MF_UL_NTAG203_COUNTER_PAGE * 4 + 1] = 0xFF; - } - // Copy original counter value from data - emulator->data.counter[0] = - emulator->data.data[MF_UL_NTAG203_COUNTER_PAGE * 4] | - (emulator->data.data[MF_UL_NTAG203_COUNTER_PAGE * 4 + 1] << 8); - } - } else { - if(emulator->config != NULL) { - // ACCESS (less CFGLCK) and AUTH0 are updated when reactivated - // MIRROR_CONF is not; don't know about STRG_MOD_EN, but we're not using that anyway - emulator->config_cache.access.value = (emulator->config->access.value & 0xBF) | - (emulator->config_cache.access.value & 0x40); - emulator->config_cache.auth0 = emulator->config->auth0; - } - } - if(emulator->data.type == MfUltralightTypeNTAG203) { - // Mark counter as dirty - emulator->data.tearing[0] = 0; - } -} - -void mf_ul_prepare_emulation(MfUltralightEmulator* emulator, MfUltralightData* data) { - FURI_LOG_D(TAG, "Prepare emulation"); - emulator->data = *data; - emulator->supported_features = mf_ul_get_features(data->type); - emulator->config = mf_ultralight_get_config_pages(&emulator->data); - emulator->page_num = emulator->data.data_size / 4; - emulator->data_changed = false; - memset(&emulator->auth_attempt, 0, sizeof(MfUltralightAuth)); - mf_ul_reset_emulation(emulator, true); -} - -bool mf_ul_prepare_emulation_response( - uint8_t* buff_rx, - uint16_t buff_rx_len, - uint8_t* buff_tx, - uint16_t* buff_tx_len, - uint32_t* data_type, - void* context) { - furi_assert(context); - MfUltralightEmulator* emulator = context; - uint16_t tx_bytes = 0; - uint16_t tx_bits = 0; - bool command_parsed = false; - bool send_ack = false; - bool respond_nothing = false; - bool reset_idle = false; - -#ifdef FURI_DEBUG - FuriString* debug_buf; - debug_buf = furi_string_alloc(); - for(int i = 0; i < (buff_rx_len + 7) / 8; ++i) { - furi_string_cat_printf(debug_buf, "%02x ", buff_rx[i]); - } - furi_string_trim(debug_buf); - FURI_LOG_T(TAG, "Emu RX (%d): %s", buff_rx_len, furi_string_get_cstr(debug_buf)); - furi_string_reset(debug_buf); -#endif - - // Check composite commands - if(emulator->comp_write_cmd_started) { - if(buff_rx_len == 16 * 8) { - if(emulator->data.type == MfUltralightTypeNTAG203 && - emulator->comp_write_page_addr == MF_UL_NTAG203_COUNTER_PAGE) { - send_ack = mf_ul_emulate_ntag203_counter_write(emulator, buff_rx); - command_parsed = send_ack; - } else { - mf_ul_emulate_write( - emulator, - emulator->comp_write_page_addr, - emulator->comp_write_page_addr, - buff_rx); - send_ack = true; - command_parsed = true; - } - } - emulator->comp_write_cmd_started = false; - } else if(emulator->sector_select_cmd_started) { - if(buff_rx_len == 4 * 8) { - if(buff_rx[0] <= 0xFE) { - emulator->curr_sector = buff_rx[0] > 3 ? 0 : buff_rx[0]; - emulator->ntag_i2c_plus_sector3_lockout = false; - command_parsed = true; - respond_nothing = true; - FURI_LOG_D(TAG, "Changing sector to %d", emulator->curr_sector); - } - } - emulator->sector_select_cmd_started = false; - } else if(buff_rx_len >= 8) { - uint8_t cmd = buff_rx[0]; - if(cmd == MF_UL_GET_VERSION_CMD) { - if(emulator->data.type >= MfUltralightTypeUL11) { - if(buff_rx_len == 1 * 8) { - tx_bytes = sizeof(emulator->data.version); - memcpy(buff_tx, &emulator->data.version, tx_bytes); - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - } - } - } else if(cmd == MF_UL_READ_CMD) { - if(buff_rx_len == (1 + 1) * 8) { - int16_t start_page = buff_rx[1]; - tx_bytes = 16; - if(emulator->data.type < MfUltralightTypeNTAGI2C1K) { - if(start_page < emulator->page_num) { - do { - uint8_t copied_pages = 0; - uint8_t src_page = start_page; - uint8_t last_page_plus_one = start_page + 4; - uint8_t pwd_page = emulator->page_num - 2; - FuriString* ascii_mirror = NULL; - size_t ascii_mirror_len = 0; - const char* ascii_mirror_cptr = NULL; - uint8_t ascii_mirror_curr_page = 0; - uint8_t ascii_mirror_curr_byte = 0; - if(last_page_plus_one > emulator->page_num) - last_page_plus_one = emulator->page_num; - if(emulator->supported_features & MfUltralightSupportAuth) { - if(!mf_ul_check_auth(emulator, start_page, false)) break; - if(!emulator->auth_success && emulator->config_cache.access.prot && - emulator->config_cache.auth0 < last_page_plus_one) - last_page_plus_one = emulator->config_cache.auth0; - } - if(emulator->supported_features & MfUltralightSupportSingleCounter) - mf_ul_increment_single_counter(emulator); - if(emulator->supported_features & MfUltralightSupportAsciiMirror && - emulator->config_cache.mirror.mirror_conf != - MfUltralightMirrorNone) { - ascii_mirror_curr_byte = emulator->config->mirror.mirror_byte; - ascii_mirror_curr_page = emulator->config->mirror_page; - // Try to avoid wasting time making mirror if we won't copy it - // Conservatively check with UID+counter mirror size - if(last_page_plus_one > ascii_mirror_curr_page && - start_page + 3 >= ascii_mirror_curr_page && - start_page <= ascii_mirror_curr_page + 6) { - ascii_mirror = furi_string_alloc(); - mf_ul_make_ascii_mirror(emulator, ascii_mirror); - ascii_mirror_len = furi_string_utf8_length(ascii_mirror); - ascii_mirror_cptr = furi_string_get_cstr(ascii_mirror); - // Move pointer to where it should be to start copying - if(ascii_mirror_len > 0 && - ascii_mirror_curr_page < start_page && - ascii_mirror_curr_byte != 0) { - uint8_t diff = 4 - ascii_mirror_curr_byte; - ascii_mirror_len -= diff; - ascii_mirror_cptr += diff; - ascii_mirror_curr_byte = 0; - ++ascii_mirror_curr_page; - } - while(ascii_mirror_len > 0 && - ascii_mirror_curr_page < start_page) { - uint8_t diff = ascii_mirror_len > 4 ? 4 : ascii_mirror_len; - ascii_mirror_len -= diff; - ascii_mirror_cptr += diff; - ++ascii_mirror_curr_page; - } - } - } - - uint8_t* dest_ptr = buff_tx; - while(copied_pages < 4) { - // Copy page - memcpy(dest_ptr, &emulator->data.data[src_page * 4], 4); - - // Note: don't have to worry about roll-over with ASCII mirror because - // lowest valid page for it is 4, while roll-over will at best read - // pages 0-2 - if(ascii_mirror_len > 0 && src_page == ascii_mirror_curr_page) { - // Copy ASCII mirror - size_t copy_len = 4 - ascii_mirror_curr_byte; - if(copy_len > ascii_mirror_len) copy_len = ascii_mirror_len; - for(size_t i = 0; i < copy_len; ++i) { - if(*ascii_mirror_cptr != ' ') - dest_ptr[ascii_mirror_curr_byte] = - (uint8_t)*ascii_mirror_cptr; - ++ascii_mirror_curr_byte; - ++ascii_mirror_cptr; - } - ascii_mirror_len -= copy_len; - // Don't care if this is inaccurate after ascii_mirror_len = 0 - ascii_mirror_curr_byte = 0; - ++ascii_mirror_curr_page; - } - - if(emulator->supported_features & MfUltralightSupportAuth) { - if(src_page == pwd_page || src_page == pwd_page + 1) { - // Blank out PWD and PACK pages - memset(dest_ptr, 0, 4); - } - } - - dest_ptr += 4; - ++copied_pages; - ++src_page; - if(src_page >= last_page_plus_one) src_page = 0; - } - if(ascii_mirror != NULL) { - furi_string_free(ascii_mirror); - } - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - } while(false); - } - } else { - uint16_t valid_pages; - start_page = mf_ultralight_ntag_i2c_addr_tag_to_lin( - &emulator->data, start_page, emulator->curr_sector, &valid_pages); - if(start_page != -1) { - if(emulator->data.type < MfUltralightTypeNTAGI2CPlus1K || - mf_ul_ntag_i2c_plus_check_auth(emulator, buff_rx[1], false)) { - if(emulator->data.type >= MfUltralightTypeNTAGI2CPlus1K && - emulator->curr_sector == 3 && valid_pages == 1) { - // Rewind back a sector to match behavior on a real tag - --start_page; - ++valid_pages; - } - - uint16_t copy_count = (valid_pages > 4 ? 4 : valid_pages) * 4; - FURI_LOG_D( - TAG, - "NTAG I2C Emu: page valid, %02x:%02x -> %d, %d", - emulator->curr_sector, - buff_rx[1], - start_page, - valid_pages); - memcpy(buff_tx, &emulator->data.data[start_page * 4], copy_count); - // For NTAG I2C, there's no roll-over; remainder is filled by null bytes - if(copy_count < tx_bytes) - memset(&buff_tx[copy_count], 0, tx_bytes - copy_count); - // Special case: NTAG I2C Plus sector 0 page 233 read crosses into page 236 - if(start_page == 233) - memcpy( - &buff_tx[12], &emulator->data.data[(start_page + 1) * 4], 4); - mf_ul_protect_auth_data_on_read_command_i2c( - buff_tx, start_page, start_page + copy_count / 4 - 1, emulator); - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - } - } else { - FURI_LOG_D( - TAG, - "NTAG I2C Emu: page invalid, %02x:%02x", - emulator->curr_sector, - buff_rx[1]); - if(emulator->data.type >= MfUltralightTypeNTAGI2CPlus1K && - emulator->curr_sector == 3 && - !emulator->ntag_i2c_plus_sector3_lockout) { - // NTAG I2C Plus has a weird behavior where if you read sector 3 - // at an invalid address, it responds with zeroes then locks - // the read out, while if you read the mirrored session registers, - // it returns both session registers on either pages - memset(buff_tx, 0, tx_bytes); - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - emulator->ntag_i2c_plus_sector3_lockout = true; - } - } - } - if(!command_parsed) tx_bytes = 0; - } - } else if(cmd == MF_UL_FAST_READ_CMD) { - if(emulator->supported_features & MfUltralightSupportFastRead) { - if(buff_rx_len == (1 + 2) * 8) { - int16_t start_page = buff_rx[1]; - uint8_t end_page = buff_rx[2]; - if(start_page <= end_page) { - tx_bytes = ((end_page + 1) - start_page) * 4; - if(emulator->data.type < MfUltralightTypeNTAGI2C1K) { - if((start_page < emulator->page_num) && - (end_page < emulator->page_num)) { - do { - if(emulator->supported_features & MfUltralightSupportAuth) { - // NAK if not authenticated and requested pages cross over AUTH0 - if(!emulator->auth_success && - emulator->config_cache.access.prot && - (start_page >= emulator->config_cache.auth0 || - end_page >= emulator->config_cache.auth0)) - break; - } - if(emulator->supported_features & - MfUltralightSupportSingleCounter) - mf_ul_increment_single_counter(emulator); - - // Copy requested pages - memcpy( - buff_tx, &emulator->data.data[start_page * 4], tx_bytes); - - if(emulator->supported_features & - MfUltralightSupportAsciiMirror && - emulator->config_cache.mirror.mirror_conf != - MfUltralightMirrorNone) { - // Copy ASCII mirror - // Less stringent check here, because expecting FAST_READ to - // only be issued once rather than repeatedly - FuriString* ascii_mirror; - ascii_mirror = furi_string_alloc(); - mf_ul_make_ascii_mirror(emulator, ascii_mirror); - size_t ascii_mirror_len = - furi_string_utf8_length(ascii_mirror); - const char* ascii_mirror_cptr = - furi_string_get_cstr(ascii_mirror); - int16_t mirror_start_offset = - (emulator->config->mirror_page - start_page) * 4 + - emulator->config->mirror.mirror_byte; - if(mirror_start_offset < 0) { - if(mirror_start_offset < -(int16_t)ascii_mirror_len) { - // Past ASCII mirror, don't copy - ascii_mirror_len = 0; - } else { - ascii_mirror_cptr += -mirror_start_offset; - ascii_mirror_len -= -mirror_start_offset; - mirror_start_offset = 0; - } - } - if(ascii_mirror_len > 0) { - int16_t mirror_end_offset = - mirror_start_offset + ascii_mirror_len; - if(mirror_end_offset > (end_page + 1) * 4) { - mirror_end_offset = (end_page + 1) * 4; - ascii_mirror_len = - mirror_end_offset - mirror_start_offset; - } - for(size_t i = 0; i < ascii_mirror_len; ++i) { - if(*ascii_mirror_cptr != ' ') - buff_tx[mirror_start_offset] = - (uint8_t)*ascii_mirror_cptr; - ++mirror_start_offset; - ++ascii_mirror_cptr; - } - } - furi_string_free(ascii_mirror); - } - - if(emulator->supported_features & MfUltralightSupportAuth) { - // Clear PWD and PACK pages - uint8_t pwd_page = emulator->page_num - 2; - int16_t pwd_page_offset = pwd_page - start_page; - // PWD page - if(pwd_page_offset >= 0 && pwd_page <= end_page) { - memset(&buff_tx[pwd_page_offset * 4], 0, 4); - // PACK page - if(pwd_page + 1 <= end_page) - memset(&buff_tx[(pwd_page_offset + 1) * 4], 0, 4); - } - } - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - } while(false); - } - } else { - uint16_t valid_pages; - start_page = mf_ultralight_ntag_i2c_addr_tag_to_lin( - &emulator->data, start_page, emulator->curr_sector, &valid_pages); - if(start_page != -1) { - if(emulator->data.type < MfUltralightTypeNTAGI2CPlus1K || - mf_ul_ntag_i2c_plus_check_auth(emulator, buff_rx[1], false)) { - uint16_t copy_count = tx_bytes; - if(copy_count > valid_pages * 4) copy_count = valid_pages * 4; - memcpy( - buff_tx, &emulator->data.data[start_page * 4], copy_count); - if(copy_count < tx_bytes) - memset(&buff_tx[copy_count], 0, tx_bytes - copy_count); - mf_ul_ntag_i2c_fill_cross_area_read( - buff_tx, buff_rx[1], buff_rx[2], emulator); - mf_ul_protect_auth_data_on_read_command_i2c( - buff_tx, - start_page, - start_page + copy_count / 4 - 1, - emulator); - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - } - } - } - if(!command_parsed) tx_bytes = 0; - } - } - } - } else if(cmd == MF_UL_WRITE) { - if(buff_rx_len == (1 + 5) * 8) { - do { - uint8_t orig_write_page = buff_rx[1]; - int16_t write_page = orig_write_page; - uint16_t valid_pages; // unused - write_page = mf_ultralight_ntag_i2c_addr_tag_to_lin( - &emulator->data, write_page, emulator->curr_sector, &valid_pages); - if(write_page == -1) // NTAG I2C range check - break; - else if(write_page < 2 || write_page >= emulator->page_num) // Other MFUL/NTAG range check - break; - - if(emulator->supported_features & MfUltralightSupportAuth) { - if(emulator->data.type >= MfUltralightTypeNTAGI2CPlus1K) { - if(!mf_ul_ntag_i2c_plus_check_auth(emulator, orig_write_page, true)) - break; - } else { - if(!mf_ul_check_auth(emulator, orig_write_page, true)) break; - } - } - int16_t tag_addr = mf_ultralight_page_addr_to_tag_addr( - emulator->curr_sector, orig_write_page); - if(!mf_ul_check_lock(emulator, tag_addr)) break; - if(emulator->data.type == MfUltralightTypeNTAG203 && - orig_write_page == MF_UL_NTAG203_COUNTER_PAGE) { - send_ack = mf_ul_emulate_ntag203_counter_write(emulator, &buff_rx[2]); - command_parsed = send_ack; - } else { - mf_ul_emulate_write(emulator, tag_addr, write_page, &buff_rx[2]); - send_ack = true; - command_parsed = true; - } - } while(false); - } - } else if(cmd == MF_UL_FAST_WRITE) { - if(emulator->supported_features & MfUltralightSupportFastWrite) { - if(buff_rx_len == (1 + 66) * 8) { - if(buff_rx[1] == 0xF0 && buff_rx[2] == 0xFF) { - // TODO: update when SRAM emulation implemented - send_ack = true; - command_parsed = true; - } - } - } - } else if(cmd == MF_UL_COMP_WRITE) { - if(emulator->supported_features & MfUltralightSupportCompatWrite) { - if(buff_rx_len == (1 + 1) * 8) { - uint8_t write_page = buff_rx[1]; - do { - if(write_page < 2 || write_page >= emulator->page_num) break; - if(emulator->supported_features & MfUltralightSupportAuth && - !mf_ul_check_auth(emulator, write_page, true)) - break; - // Note we don't convert to tag addr here because there's only one sector - if(!mf_ul_check_lock(emulator, write_page)) break; - - emulator->comp_write_cmd_started = true; - emulator->comp_write_page_addr = write_page; - send_ack = true; - command_parsed = true; - } while(false); - } - } - } else if(cmd == MF_UL_READ_CNT) { - if(emulator->supported_features & MfUltralightSupportReadCounter) { - if(buff_rx_len == (1 + 1) * 8) { - do { - uint8_t cnt_num = buff_rx[1]; - - // NTAG21x checks - if(emulator->supported_features & MfUltralightSupportSingleCounter) { - if(cnt_num != 2) break; // Only counter 2 is available - if(!emulator->config_cache.access.nfc_cnt_en) - break; // NAK if counter not enabled - if(emulator->config_cache.access.nfc_cnt_pwd_prot && - !emulator->auth_success) - break; - } - - if(cnt_num < 3) { - buff_tx[0] = emulator->data.counter[cnt_num] & 0xFF; - buff_tx[1] = (emulator->data.counter[cnt_num] >> 8) & 0xFF; - buff_tx[2] = (emulator->data.counter[cnt_num] >> 16) & 0xFF; - tx_bytes = 3; - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - } - } while(false); - } - } - } else if(cmd == MF_UL_INC_CNT) { - if(emulator->supported_features & MfUltralightSupportIncrCounter) { - if(buff_rx_len == (1 + 5) * 8) { - uint8_t cnt_num = buff_rx[1]; - uint32_t inc = (buff_rx[2] | (buff_rx[3] << 8) | (buff_rx[4] << 16)); - // TODO: can you increment by 0 when counter is at 0xffffff? - if((cnt_num < 3) && (emulator->data.counter[cnt_num] != 0x00FFFFFF) && - (emulator->data.counter[cnt_num] + inc <= 0x00FFFFFF)) { - emulator->data.counter[cnt_num] += inc; - // We're RAM-backed, so tearing never happens - emulator->data.tearing[cnt_num] = MF_UL_TEARING_FLAG_DEFAULT; - emulator->data_changed = true; - send_ack = true; - command_parsed = true; - } - } - } - } else if(cmd == MF_UL_PWD_AUTH) { - if(emulator->supported_features & MfUltralightSupportAuth) { - if(buff_rx_len == (1 + 4) * 8) { - // Record password sent by PCD - memcpy( - emulator->auth_attempt.pwd.raw, - &buff_rx[1], - sizeof(emulator->auth_attempt.pwd.raw)); - emulator->auth_attempted = true; - if(emulator->auth_received_callback) { - emulator->auth_received_callback( - emulator->auth_attempt, emulator->context); - } - - uint16_t scaled_authlim = mf_ultralight_calc_auth_count(&emulator->data); - if(scaled_authlim != 0 && emulator->data.curr_authlim >= scaled_authlim) { - if(emulator->data.curr_authlim != UINT16_MAX) { - // Handle case where AUTHLIM has been lowered or changed from 0 - emulator->data.curr_authlim = UINT16_MAX; - emulator->data_changed = true; - } - // AUTHLIM reached, always fail - buff_tx[0] = MF_UL_NAK_AUTHLIM_REACHED; - tx_bits = 4; - *data_type = FURI_HAL_NFC_TX_RAW_RX_DEFAULT; - mf_ul_reset_emulation(emulator, false); - command_parsed = true; - } else { - if(memcmp(&buff_rx[1], emulator->config->auth_data.pwd.raw, 4) == 0) { - // Correct password - buff_tx[0] = emulator->config->auth_data.pack.raw[0]; - buff_tx[1] = emulator->config->auth_data.pack.raw[1]; - tx_bytes = 2; - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - emulator->auth_success = true; - command_parsed = true; - if(emulator->data.curr_authlim != 0) { - // Reset current AUTHLIM - emulator->data.curr_authlim = 0; - emulator->data_changed = true; - } - } else if(!emulator->config->auth_data.pwd.value) { - // Unknown password, pretend to be an Amiibo - buff_tx[0] = 0x80; - buff_tx[1] = 0x80; - tx_bytes = 2; - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - emulator->auth_success = true; - command_parsed = true; - } else { - // Wrong password, increase negative verification count - if(emulator->data.curr_authlim < UINT16_MAX) { - ++emulator->data.curr_authlim; - emulator->data_changed = true; - } - if(scaled_authlim != 0 && - emulator->data.curr_authlim >= scaled_authlim) { - emulator->data.curr_authlim = UINT16_MAX; - buff_tx[0] = MF_UL_NAK_AUTHLIM_REACHED; - tx_bits = 4; - *data_type = FURI_HAL_NFC_TX_RAW_RX_DEFAULT; - mf_ul_reset_emulation(emulator, false); - command_parsed = true; - } else { - // Should delay here to slow brute forcing - } - } - } - } - } - } else if(cmd == MF_UL_READ_SIG) { - if(emulator->supported_features & MfUltralightSupportSignature) { - // Check 2nd byte = 0x00 - RFU - if(buff_rx_len == (1 + 1) * 8 && buff_rx[1] == 0x00) { - tx_bytes = sizeof(emulator->data.signature); - memcpy(buff_tx, emulator->data.signature, tx_bytes); - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - } - } - } else if(cmd == MF_UL_CHECK_TEARING) { - if(emulator->supported_features & MfUltralightSupportTearingFlags) { - if(buff_rx_len == (1 + 1) * 8) { - uint8_t cnt_num = buff_rx[1]; - if(cnt_num < 3) { - buff_tx[0] = emulator->data.tearing[cnt_num]; - tx_bytes = 1; - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - } - } - } - } else if(cmd == MF_UL_HALT_START) { - reset_idle = true; - FURI_LOG_D(TAG, "Received HLTA"); - } else if(cmd == MF_UL_SECTOR_SELECT) { - if(emulator->supported_features & MfUltralightSupportSectorSelect) { - if(buff_rx_len == (1 + 1) * 8 && buff_rx[1] == 0xFF) { - // Send ACK - emulator->sector_select_cmd_started = true; - send_ack = true; - command_parsed = true; - } - } - } else if(cmd == MF_UL_READ_VCSL) { - if(emulator->supported_features & MfUltralightSupportVcsl) { - if(buff_rx_len == (1 + 20) * 8) { - buff_tx[0] = emulator->config_cache.vctid; - tx_bytes = 1; - *data_type = FURI_HAL_NFC_TXRX_DEFAULT; - command_parsed = true; - } - } - } else { - // NTAG203 appears to NAK instead of just falling off on invalid commands - if(emulator->data.type != MfUltralightTypeNTAG203) reset_idle = true; - FURI_LOG_D(TAG, "Received invalid command"); - } - } else { - reset_idle = true; - FURI_LOG_D(TAG, "Received invalid buffer less than 8 bits in length"); - } - - if(reset_idle) { - mf_ul_reset_emulation(emulator, false); - tx_bits = 0; - command_parsed = true; - } - - if(!command_parsed) { - // Send NACK - buff_tx[0] = MF_UL_NAK_INVALID_ARGUMENT; - tx_bits = 4; - *data_type = FURI_HAL_NFC_TX_RAW_RX_DEFAULT; - // Every NAK should cause reset to IDLE - mf_ul_reset_emulation(emulator, false); - } else if(send_ack) { - buff_tx[0] = MF_UL_ACK; - tx_bits = 4; - *data_type = FURI_HAL_NFC_TX_RAW_RX_DEFAULT; - } - - if(respond_nothing) { - *buff_tx_len = UINT16_MAX; - *data_type = FURI_HAL_NFC_TX_RAW_RX_DEFAULT; - } else { - // Return tx buffer size in bits - if(tx_bytes) { - tx_bits = tx_bytes * 8; - } - *buff_tx_len = tx_bits; - } - -#ifdef FURI_DEBUG - if(*buff_tx_len == UINT16_MAX) { - FURI_LOG_T(TAG, "Emu TX: no reply"); - } else if(*buff_tx_len > 0) { - int count = (*buff_tx_len + 7) / 8; - for(int i = 0; i < count; ++i) { - furi_string_cat_printf(debug_buf, "%02x ", buff_tx[i]); - } - furi_string_trim(debug_buf); - FURI_LOG_T(TAG, "Emu TX (%d): %s", *buff_tx_len, furi_string_get_cstr(debug_buf)); - furi_string_free(debug_buf); - } else { - FURI_LOG_T(TAG, "Emu TX: HALT"); - } -#endif - - return tx_bits > 0; -} - -bool mf_ul_is_full_capture(MfUltralightData* data) { - if(data->data_read != data->data_size) return false; - - // Having read all the pages doesn't mean that we've got everything. - // By default PWD is 0xFFFFFFFF, but if read back it is always 0x00000000, - // so a default read on an auth-supported NTAG is never complete. - if(!(mf_ul_get_features(data->type) & MfUltralightSupportAuth)) return true; - MfUltralightConfigPages* config = mf_ultralight_get_config_pages(data); - return config->auth_data.pwd.value != 0 || config->auth_data.pack.value != 0; -} diff --git a/lib/nfc/protocols/mifare_ultralight.h b/lib/nfc/protocols/mifare_ultralight.h deleted file mode 100644 index 9cb7ca535..000000000 --- a/lib/nfc/protocols/mifare_ultralight.h +++ /dev/null @@ -1,269 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// Largest tag is NTAG I2C Plus 2K, both data sectors plus SRAM -#define MF_UL_MAX_DUMP_SIZE ((238 + 256 + 16) * 4) - -#define MF_UL_TEARING_FLAG_DEFAULT (0xBD) - -#define MF_UL_HALT_START (0x50) -#define MF_UL_GET_VERSION_CMD (0x60) -#define MF_UL_READ_CMD (0x30) -#define MF_UL_FAST_READ_CMD (0x3A) -#define MF_UL_WRITE (0xA2) -#define MF_UL_FAST_WRITE (0xA6) -#define MF_UL_COMP_WRITE (0xA0) -#define MF_UL_READ_CNT (0x39) -#define MF_UL_INC_CNT (0xA5) -#define MF_UL_AUTHENTICATE_1 (0x1A) -#define MF_UL_PWD_AUTH (0x1B) -#define MF_UL_READ_SIG (0x3C) -#define MF_UL_CHECK_TEARING (0x3E) -#define MF_UL_READ_VCSL (0x4B) -#define MF_UL_SECTOR_SELECT (0xC2) - -#define MF_UL_ACK (0xa) -#define MF_UL_NAK_INVALID_ARGUMENT (0x0) -#define MF_UL_NAK_AUTHLIM_REACHED (0x4) - -#define MF_UL_NTAG203_COUNTER_PAGE (41) - -#define MF_UL_DEFAULT_PWD (0xFFFFFFFF) - -typedef enum { - MfUltralightAuthMethodManual, - MfUltralightAuthMethodAmeebo, - MfUltralightAuthMethodXiaomi, - MfUltralightAuthMethodAuto, -} MfUltralightAuthMethod; - -// Important: order matters; some features are based on positioning in this enum -typedef enum { - MfUltralightTypeUnknown, - MfUltralightTypeNTAG203, - MfUltralightTypeULC, - // Below have config pages and GET_VERSION support - MfUltralightTypeUL11, - MfUltralightTypeUL21, - MfUltralightTypeNTAG213, - MfUltralightTypeNTAG215, - MfUltralightTypeNTAG216, - // Below also have sector select - // NTAG I2C's *does not* have regular config pages, so it's a bit of an odd duck - MfUltralightTypeNTAGI2C1K, - MfUltralightTypeNTAGI2C2K, - // NTAG I2C Plus has stucture expected from NTAG21x - MfUltralightTypeNTAGI2CPlus1K, - MfUltralightTypeNTAGI2CPlus2K, - - // Keep last for number of types calculation - MfUltralightTypeNum, -} MfUltralightType; - -typedef enum { - MfUltralightSupportNone = 0, - MfUltralightSupportFastRead = 1 << 0, - MfUltralightSupportTearingFlags = 1 << 1, - MfUltralightSupportReadCounter = 1 << 2, - MfUltralightSupportIncrCounter = 1 << 3, - MfUltralightSupportSignature = 1 << 4, - MfUltralightSupportFastWrite = 1 << 5, - MfUltralightSupportCompatWrite = 1 << 6, - MfUltralightSupportAuth = 1 << 7, - MfUltralightSupportVcsl = 1 << 8, - MfUltralightSupportSectorSelect = 1 << 9, - // NTAG21x only has counter 2 - MfUltralightSupportSingleCounter = 1 << 10, - // ASCII mirror is not a command, but handy to have as a flag - MfUltralightSupportAsciiMirror = 1 << 11, - // NTAG203 counter that's in memory rather than through a command - MfUltralightSupportCounterInMemory = 1 << 12, - MfUltralightSupport3DesAuth = 1 << 13, -} MfUltralightFeatures; - -typedef enum { - MfUltralightMirrorNone, - MfUltralightMirrorUid, - MfUltralightMirrorCounter, - MfUltralightMirrorUidCounter, -} MfUltralightMirrorConf; - -typedef struct { - uint8_t header; - uint8_t vendor_id; - uint8_t prod_type; - uint8_t prod_subtype; - uint8_t prod_ver_major; - uint8_t prod_ver_minor; - uint8_t storage_size; - uint8_t protocol_type; -} MfUltralightVersion; - -typedef struct { - uint8_t sn0[3]; - uint8_t btBCC0; - uint8_t sn1[4]; - uint8_t btBCC1; - uint8_t internal; - uint8_t lock[2]; - uint8_t otp[4]; -} MfUltralightManufacturerBlock; - -typedef struct { - MfUltralightType type; - MfUltralightVersion version; - uint8_t signature[32]; - uint32_t counter[3]; - uint8_t tearing[3]; - MfUltralightAuthMethod auth_method; - uint8_t auth_key[4]; - bool auth_success; - uint16_t curr_authlim; - uint16_t data_size; - uint8_t data[MF_UL_MAX_DUMP_SIZE]; - uint16_t data_read; -} MfUltralightData; - -typedef struct __attribute__((packed)) { - union { - uint8_t raw[4]; - uint32_t value; - } pwd; - union { - uint8_t raw[2]; - uint16_t value; - } pack; -} MfUltralightAuth; - -// Common configuration pages for MFUL EV1, NTAG21x, and NTAG I2C Plus -typedef struct __attribute__((packed)) { - union { - uint8_t value; - struct { - uint8_t rfui1 : 2; - bool strg_mod_en : 1; - bool rfui2 : 1; - uint8_t mirror_byte : 2; - MfUltralightMirrorConf mirror_conf : 2; - }; - } mirror; - uint8_t rfui1; - uint8_t mirror_page; - uint8_t auth0; - union { - uint8_t value; - struct { - uint8_t authlim : 3; - bool nfc_cnt_pwd_prot : 1; - bool nfc_cnt_en : 1; - bool nfc_dis_sec1 : 1; // NTAG I2C Plus only - bool cfglck : 1; - bool prot : 1; - }; - } access; - uint8_t vctid; - uint8_t rfui2[2]; - MfUltralightAuth auth_data; - uint8_t rfui3[2]; -} MfUltralightConfigPages; - -typedef struct { - uint16_t pages_to_read; - int16_t pages_read; - MfUltralightFeatures supported_features; -} MfUltralightReader; - -// TODO rework with reader analyzer -typedef void (*MfUltralightAuthReceivedCallback)(MfUltralightAuth auth, void* context); - -typedef struct { - MfUltralightData data; - MfUltralightConfigPages* config; - // Most config values don't apply until power cycle, so cache config pages - // for correct behavior - MfUltralightConfigPages config_cache; - MfUltralightFeatures supported_features; - uint16_t page_num; - bool data_changed; - bool comp_write_cmd_started; - uint8_t comp_write_page_addr; - bool auth_success; - uint8_t curr_sector; - bool sector_select_cmd_started; - bool ntag_i2c_plus_sector3_lockout; - bool read_counter_incremented; - bool auth_attempted; - MfUltralightAuth auth_attempt; - - // TODO rework with reader analyzer - MfUltralightAuthReceivedCallback auth_received_callback; - void* context; -} MfUltralightEmulator; - -void mf_ul_reset(MfUltralightData* data); - -bool mf_ul_check_card_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK); - -bool mf_ultralight_read_version( - FuriHalNfcTxRxContext* tx_rx, - MfUltralightReader* reader, - MfUltralightData* data); - -bool mf_ultralight_read_pages_direct( - FuriHalNfcTxRxContext* tx_rx, - uint8_t start_index, - uint8_t* data); - -bool mf_ultralight_read_pages( - FuriHalNfcTxRxContext* tx_rx, - MfUltralightReader* reader, - MfUltralightData* data); - -bool mf_ultralight_fast_read_pages( - FuriHalNfcTxRxContext* tx_rx, - MfUltralightReader* reader, - MfUltralightData* data); - -bool mf_ultralight_read_signature(FuriHalNfcTxRxContext* tx_rx, MfUltralightData* data); - -bool mf_ultralight_read_counters(FuriHalNfcTxRxContext* tx_rx, MfUltralightData* data); - -bool mf_ultralight_read_tearing_flags(FuriHalNfcTxRxContext* tx_rx, MfUltralightData* data); - -bool mf_ultralight_authenticate(FuriHalNfcTxRxContext* tx_rx, uint32_t key, uint16_t* pack); - -MfUltralightConfigPages* mf_ultralight_get_config_pages(MfUltralightData* data); - -bool mf_ul_read_card( - FuriHalNfcTxRxContext* tx_rx, - MfUltralightReader* reader, - MfUltralightData* data); - -bool mf_ul_emulation_supported(MfUltralightData* data); - -void mf_ul_reset_emulation(MfUltralightEmulator* emulator, bool is_power_cycle); - -void mf_ul_prepare_emulation(MfUltralightEmulator* emulator, MfUltralightData* data); - -bool mf_ul_prepare_emulation_response( - uint8_t* buff_rx, - uint16_t buff_rx_len, - uint8_t* buff_tx, - uint16_t* buff_tx_len, - uint32_t* data_type, - void* context); - -uint32_t mf_ul_pwdgen_amiibo(FuriHalNfcDevData* data); - -uint32_t mf_ul_pwdgen_xiaomi(FuriHalNfcDevData* data); - -bool mf_ul_is_full_capture(MfUltralightData* data); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/lib/nfc/protocols/nfc_device_base.h b/lib/nfc/protocols/nfc_device_base.h new file mode 100644 index 000000000..4f3480d45 --- /dev/null +++ b/lib/nfc/protocols/nfc_device_base.h @@ -0,0 +1,26 @@ +/** + * @file nfc_device_base.h + * @brief Common top-level types for the NFC protocol stack. + */ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Verbosity level of the displayed NFC device name. + */ +typedef enum { + NfcDeviceNameTypeFull, /**< Display full(verbose) name. */ + NfcDeviceNameTypeShort, /**< Display shortened name. */ +} NfcDeviceNameType; + +/** + * @brief Generic opaque type for protocol-specific NFC device data. + */ +typedef void NfcDeviceData; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/nfc_device_base_i.h b/lib/nfc/protocols/nfc_device_base_i.h new file mode 100644 index 000000000..946ae76dc --- /dev/null +++ b/lib/nfc/protocols/nfc_device_base_i.h @@ -0,0 +1,161 @@ +/** + * @file nfc_device_base_i.h + * @brief Abstract interface definitions for the NFC device system. + * + * This file is an implementation detail. It must not be included in + * any public API-related headers. + */ +#pragma once + +#include "nfc_device_base.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Allocate the protocol-specific NFC device data instance. + * + * @returns pointer to the allocated instance. + */ +typedef NfcDeviceData* (*NfcDeviceAlloc)(); + +/** + * @brief Delete the protocol-specific NFC device data instance. + * + * @param[in,out] data pointer to the instance to be deleted. + */ +typedef void (*NfcDeviceFree)(NfcDeviceData* data); + +/** + * @brief Reset the NFC device data instance. + * + * The behaviour is protocol-specific. Usually, required fields are zeroed or + * set to their initial values. + * + * @param[in,out] data pointer to the instance to be reset. + */ +typedef void (*NfcDeviceReset)(NfcDeviceData* data); + +/** + * @brief Copy source instance's data into the destination so that they become equal. + * + * @param[in,out] data pointer to the destination instance. + * @param[in] other pointer to the source instance. + */ +typedef void (*NfcDeviceCopy)(NfcDeviceData* data, const NfcDeviceData* other); + +/** + * @brief Deprecated. Do not use in new protocols. + * @deprecated do not use in new protocols. + * + * @param[in,out] data pointer to the instance to be tested. + * @param[in] device_type pointer to a FuriString containing a device type identifier. + * @returns true if data was verified, false otherwise. + */ +typedef bool (*NfcDeviceVerify)(NfcDeviceData* data, const FuriString* device_type); + +/** + * @brief Load NFC device data from a FlipperFormat file. + * + * The FlipperFormat file structure must be initialised and open by the calling code. + * + * @param[in,out] data pointer to the instance to be loaded into. + * @param[in] ff pointer to the FlipperFormat file instance. + * @param[in] version file format version to use when loading. + * @returns true if loaded successfully, false otherwise. + */ +typedef bool (*NfcDeviceLoad)(NfcDeviceData* data, FlipperFormat* ff, uint32_t version); + +/** + * @brief Save NFC device data to a FlipperFormat file. + * + * The FlipperFormat file structure must be initialised and open by the calling code. + * + * @param[in] data pointer to the instance to be saved. + * @param[in] ff pointer to the FlipperFormat file instance. + * @returns true if saved successfully, false otherwise. + */ +typedef bool (*NfcDeviceSave)(const NfcDeviceData* data, FlipperFormat* ff); + +/** + * @brief Compare two NFC device data instances. + * + * @param[in] data pointer to the first instance to be compared. + * @param[in] other pointer to the second instance to be compared. + * @returns true if instances are equal, false otherwise. + */ +typedef bool (*NfcDeviceEqual)(const NfcDeviceData* data, const NfcDeviceData* other); + +/** + * @brief Get a protocol-specific stateful NFC device name. + * + * The return value may change depending on the instance's internal state and the name_type parameter. + * + * @param[in] data pointer to the instance to be queried. + * @param[in] name_type type of the name to be displayed. + * @returns pointer to a statically allocated character string containing the appropriate name. + */ +typedef const char* (*NfcDeviceGetName)(const NfcDeviceData* data, NfcDeviceNameType name_type); + +/** + * @brief Get the NFC device's unique identifier (UID). + * + * The UID length is protocol-dependent. Additionally, a particular protocol might support + * several UID lengths. + * + * @param[in] data pointer to the instance to be queried. + * @param[out] uid_len pointer to the variable to contain the UID length. + * @returns pointer to the byte array containing the device's UID. + */ +typedef const uint8_t* (*NfcDeviceGetUid)(const NfcDeviceData* data, size_t* uid_len); + +/** + * @brief Set the NFC device's unique identifier (UID). + * + * The UID length must be supported by the protocol in question. + * + * @param[in,out] data pointer to the instance to be modified. + * @param[in] uid pointer to the byte array containing the new UID. + * @param[in] uid_len length of the UID. + * @return true if the UID was valid and set, false otherwise. + */ +typedef bool (*NfcDeviceSetUid)(NfcDeviceData* data, const uint8_t* uid, size_t uid_len); + +/** + * @brief Get the NFC device data associated with the parent protocol. + * + * The protocol the instance's data is associated with must have a parent. + * + * @param[in] data pointer to the instance to be queried. + * @returns pointer to the data instance associated with the parent protocol. + */ +typedef NfcDeviceData* (*NfcDeviceGetBaseData)(const NfcDeviceData* data); + +/** + * @brief Generic NFC device interface. + * + * Each protocol must fill this structure with its own function implementations. + */ +typedef struct { + const char* + protocol_name; /**< Pointer to a statically-allocated string with the protocol name. */ + NfcDeviceAlloc alloc; /**< Pointer to the alloc() function. */ + NfcDeviceFree free; /**< Pointer to the free() function. */ + NfcDeviceReset reset; /**< Pointer to the reset() function. */ + NfcDeviceCopy copy; /**< Pointer to the copy() function. */ + NfcDeviceVerify verify; /**< Deprecated. Set to NULL in new protocols. */ + NfcDeviceLoad load; /**< Pointer to the load() function. */ + NfcDeviceSave save; /**< Pointer to the save() function. */ + NfcDeviceEqual is_equal; /**< Pointer to the is_equal() function. */ + NfcDeviceGetName get_name; /**< Pointer to the get_name() function. */ + NfcDeviceGetUid get_uid; /**< Pointer to the get_uid() function. */ + NfcDeviceSetUid set_uid; /**< Pointer to the set_uid() function. */ + NfcDeviceGetBaseData get_base_data; /**< Pointer to the get_base_data() function. */ +} NfcDeviceBase; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/nfc_device_defs.c b/lib/nfc/protocols/nfc_device_defs.c new file mode 100644 index 000000000..870bcafd9 --- /dev/null +++ b/lib/nfc/protocols/nfc_device_defs.c @@ -0,0 +1,46 @@ +/** + * @file nfc_device_defs.c + * @brief Main NFC device implementation definitions. + * + * All NFC device implementations must be registered here in order to be used + * by the NfcDevice library. + * + * @see nfc_device.h + * + * This file is to be modified upon adding a new protocol (see below). + */ +#include "nfc_device_base_i.h" +#include "nfc_protocol.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * @brief List of registered NFC device implementations. + * + * When implementing a new protocol, add its implementation + * here under its own index defined in nfc_protocol.h. + */ +const NfcDeviceBase* nfc_devices[NfcProtocolNum] = { + [NfcProtocolIso14443_3a] = &nfc_device_iso14443_3a, + [NfcProtocolIso14443_3b] = &nfc_device_iso14443_3b, + [NfcProtocolIso14443_4a] = &nfc_device_iso14443_4a, + [NfcProtocolIso14443_4b] = &nfc_device_iso14443_4b, + [NfcProtocolIso15693_3] = &nfc_device_iso15693_3, + [NfcProtocolFelica] = &nfc_device_felica, + [NfcProtocolMfUltralight] = &nfc_device_mf_ultralight, + [NfcProtocolMfClassic] = &nfc_device_mf_classic, + [NfcProtocolMfDesfire] = &nfc_device_mf_desfire, + [NfcProtocolSlix] = &nfc_device_slix, + [NfcProtocolSt25tb] = &nfc_device_st25tb, + /* Add new protocols here */ +}; diff --git a/lib/nfc/protocols/nfc_device_defs.h b/lib/nfc/protocols/nfc_device_defs.h new file mode 100644 index 000000000..f5ba2563f --- /dev/null +++ b/lib/nfc/protocols/nfc_device_defs.h @@ -0,0 +1,13 @@ +#pragma once + +#include "nfc_device_base_i.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NfcDeviceBase* nfc_devices[]; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/nfc_generic_event.h b/lib/nfc/protocols/nfc_generic_event.h new file mode 100644 index 000000000..ec3bd68dc --- /dev/null +++ b/lib/nfc/protocols/nfc_generic_event.h @@ -0,0 +1,79 @@ +/** + * @file nfc_generic_event.h + * @brief Generic Nfc stack event definitions. + * + * Events are the main way of passing information about, well, various events + * that occur across the Nfc protocol stack. + * + * In order to subscribe to events from a certain instance, the user code must call + * its corresponding start() function while providing the appropriate callback. + * During this call, an additional context pointer can be provided, which will be passed + * to the context parameter at the time of the callback execution. + * + * For additional information on how events are passed around and processed, see protocol-specific + * poller and listener implementations found in the respectively named subfolders. + * + */ +#pragma once + +#include "nfc_protocol.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Generic Nfc instance type. + * + * Must be cast to a concrete type before use. + * Depending on the context, a pointer of this type + * may point to an object of the following types: + * - Nfc type, + * - Concrete poller type, + * - Concrete listener type. + */ +typedef void NfcGenericInstance; + +/** + * @brief Generic Nfc event data type. + * + * Must be cast to a concrete type before use. + * Usually, it will be the protocol-specific event type. + */ +typedef void NfcGenericEventData; + +/** + * @brief Generic Nfc event type. + * + * A generic Nfc event contains a protocol identifier, can be used to determine + * the remaing fields' type. + * + * If the value of the protocol field is NfcProtocolInvalid, then it means that + * the event was emitted from an Nfc instance, otherwise it originated from + * a concrete poller or listener instance. + * + * The event_data field is protocol-specific and should be cast to the appropriate type before use. + */ +typedef struct { + NfcProtocol protocol; /**< Protocol identifier of the instance that produced the event. */ + NfcGenericInstance* + instance; /**< Pointer to the protocol-specific instance that produced the event. */ + NfcGenericEventData* event_data; /**< Pointer to the protocol-specific event. */ +} NfcGenericEvent; + +/** + * @brief Generic Nfc event callback type. + * + * A function of this type must be passed as the callback parameter upon start + * of a poller, listener or Nfc instance. + * + * @param [in] event Nfc generic event, passed by value, complete with protocol type and data. + * @param [in,out] context pointer to the user-specific context (set when starting a poller/listener instance). + * @returns the command which the event producer must execute. + */ +typedef NfcCommand (*NfcGenericCallback)(NfcGenericEvent event, void* context); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/nfc_listener_base.h b/lib/nfc/protocols/nfc_listener_base.h new file mode 100644 index 000000000..6d0cdcd09 --- /dev/null +++ b/lib/nfc/protocols/nfc_listener_base.h @@ -0,0 +1,98 @@ +/** + * @file nfc_listener_base.h + * @brief Abstract interface definitions for the NFC listener system. + * + * This file is an implementation detail. It must not be included in + * any public API-related headers. + * + * @see nfc_listener.h + * + */ +#pragma once + +#include "nfc_generic_event.h" +#include "nfc_device_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Allocate a protocol-specific listener instance. + * + * For base listeners pass a pointer to an instance of type Nfc + * as the base_listener parameter, otherwise it must be a pointer to another listener instance + * (compare iso14443_3a/iso14443_3a_listener.c and iso14443_4a/iso14443_4a_listener.c). + * + * @see nfc_protocol.c + * + * The NFC device data passed as the data parameter is copied to the instance and may + * change during the emulation in response to reader commands. + * + * To retrieve the modified data, NfcListenerGetData gets called by the NfcListener + * implementation when the user code calls nfc_listener_get_data(). + * + * @param[in] base_listener pointer to the parent listener instance. + * @param[in] data pointer to the protocol-specific data to use during emulation. + * @returns pointer to the allocated listener instance. + */ +typedef NfcGenericInstance* ( + *NfcListenerAlloc)(NfcGenericInstance* base_listener, NfcDeviceData* data); + +/** + * @brief Delete a protocol-specific listener instance. + * + * @param[in,out] instance pointer to the instance to be deleted. + */ +typedef void (*NfcListenerFree)(NfcGenericInstance* instance); + +/** + * @brief Set the callback function to handle events emitted by the listener instance. + * + * @see nfc_generic_event.h + * + * @param[in,out] listener + * @param[in] callback pointer to the user-defined callback function which will receive events. + * @param[in] context pointer to the user-specific context (will be passed to the callback). + */ +typedef void (*NfcListenerSetCallback)( + NfcGenericInstance* listener, + NfcGenericCallback callback, + void* context); + +/** + * @brief Emulate a supported NFC card with given device data. + * + * @param[in] event protocol-specific event passed by the parent listener instance. + * @param[in,out] context pointer to the protocol-specific listener instance. + * @returns command to be executed by the parent listener instance. + */ +typedef NfcCommand (*NfcListenerRun)(NfcGenericEvent event, void* context); + +/** + * @brief Get the protocol-specific data that was that was provided for emulation. + * + * @param[in] instance pointer to the protocol-specific listener instance. + * @returns pointer to the NFC device data. + */ +typedef const NfcDeviceData* (*NfcListenerGetData)(const NfcGenericInstance* instance); + +/** + * @brief Generic NFC listener interface. + * + * Each protocol must fill this structure with its own function implementations. + * See above for the function signatures and descriptions. + * + * Additionally, see ${PROTOCOL_NAME}/${PROTOCOL_NAME}_listener.c for usage examples. + */ +typedef struct { + NfcListenerAlloc alloc; /**< Pointer to the alloc() function. */ + NfcListenerFree free; /**< Pointer to the free() function. */ + NfcListenerSetCallback set_callback; /**< Pointer to the set_callback() function. */ + NfcListenerRun run; /**< Pointer to the run() function. */ + NfcListenerGetData get_data; /**< Pointer to the get_data() function. */ +} NfcListenerBase; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/nfc_listener_defs.c b/lib/nfc/protocols/nfc_listener_defs.c new file mode 100644 index 000000000..31f9bc16c --- /dev/null +++ b/lib/nfc/protocols/nfc_listener_defs.c @@ -0,0 +1,21 @@ +#include "nfc_listener_defs.h" + +#include +#include +#include +#include +#include +#include + +const NfcListenerBase* nfc_listeners_api[NfcProtocolNum] = { + [NfcProtocolIso14443_3a] = &nfc_listener_iso14443_3a, + [NfcProtocolIso14443_3b] = NULL, + [NfcProtocolIso14443_4a] = &nfc_listener_iso14443_4a, + [NfcProtocolIso14443_4b] = NULL, + [NfcProtocolIso15693_3] = &nfc_listener_iso15693_3, + [NfcProtocolMfUltralight] = &mf_ultralight_listener, + [NfcProtocolMfClassic] = &mf_classic_listener, + [NfcProtocolMfDesfire] = NULL, + [NfcProtocolSlix] = &nfc_listener_slix, + [NfcProtocolSt25tb] = NULL, +}; diff --git a/lib/nfc/protocols/nfc_listener_defs.h b/lib/nfc/protocols/nfc_listener_defs.h new file mode 100644 index 000000000..4d88cc098 --- /dev/null +++ b/lib/nfc/protocols/nfc_listener_defs.h @@ -0,0 +1,14 @@ +#pragma once + +#include "nfc_listener_base.h" +#include "nfc_protocol.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NfcListenerBase* nfc_listeners_api[NfcProtocolNum]; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/nfc_poller_base.h b/lib/nfc/protocols/nfc_poller_base.h new file mode 100644 index 000000000..9c4a2b652 --- /dev/null +++ b/lib/nfc/protocols/nfc_poller_base.h @@ -0,0 +1,132 @@ +/** + * @file nfc_poller_base.h + * @brief Abstract interface definitions for the NFC poller system. + * + * This file is an implementation detail. It must not be included in + * any public API-related headers. + * + * @see nfc_poller.h + * + */ +#pragma once + +#include "nfc_generic_event.h" +#include "nfc_device_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Allocate a protocol-specific poller instance. + * + * For base pollers pass a pointer to an instance of type Nfc + * as the base_poller parameter, otherwise it must be a pointer to another poller instance + * (compare iso14443_3a/iso14443_3a_poller.c and iso14443_4a/iso14443_4a_poller.c). + * + * @see nfc_protocol.c + * + * @param[in] base_poller pointer to the parent poller instance. + * @returns pointer to the allocated poller instance. + */ +typedef NfcGenericInstance* (*NfcPollerAlloc)(NfcGenericInstance* base_poller); + +/** + * @brief Delete a protocol-specific poller instance. + * + * @param[in,out] instance pointer to the instance to be deleted. + */ +typedef void (*NfcPollerFree)(NfcGenericInstance* instance); + +/** + * @brief Set the callback function to handle events emitted by the poller instance. + * + * @see nfc_generic_event.h + * + * @param[in,out] poller pointer to the protocol-specific poller instance. + * @param[in] callback pointer to the user-defined callback function which will receive events. + * @param[in] context pointer to the user-specific context (will be passed to the callback). + */ +typedef void ( + *NfcPollerSetCallback)(NfcGenericInstance* poller, NfcGenericCallback callback, void* context); + +/** + * @brief Activate and read a supported NFC card. + * + * Ths function is passed to the parent poller's ${POLLER_NAME}_set_callback function as + * the callback parameter. This is done automatically by the NfcPoller implementation based + * on the protocol hierarchy defined in nfc_protocol.c, so there is no need to call it explicitly. + * + * Thus, it will be called each time the parent poller emits an event. Usually it happens + * only after the parent poller has successfully completed its job. + * + * Example for an application reading a card with a compound (non-base) protocol (simplified): + * + * ``` + * start() <-- set_callback() <-- set_callback() <-- nfc_poller_start() + * | | | + * Nfc | Base Poller | Child Poller | Application + * | | | + * worker() --> run() --> run() ---> handle_event() + * ``` + * + * The base poller receives events directly from an Nfc instance, from which they are + * propagated as needed to however many other pollers there are in the current hierarchy. + * + * This function can be thought of as the poller's "main loop" function. Depending + * on the particular poller implementation, it may perform actions such as reading + * and writing to an NFC card, state changes and control of the parent poller. + * + * @see nfc_generic_event.h + * + * @param[in] event protocol-specific event passed by the parent poller instance. + * @param[in,out] context pointer to the protocol-specific poller instance. + * @returns command to be executed by the parent poller instance. + */ +typedef NfcCommand (*NfcPollerRun)(NfcGenericEvent event, void* context); + +/** + * @brief Determine whether there is a supported card in the vicinity. + * + * The behaviour is mostly the same as of NfcPollerRun, with the difference in the + * procedure and return value. + * The procedure implemented in this function must do whatever it needs to unambigiously + * determine whether a supported and valid NFC card is in the vicinity. + * + * Like the previously described NfcPollerRun, it is called automatically by the NfcPoller + * implementation, so there is no need to call it explicitly. + * + * @param[in] event protocol-specific event passed by the parent poller instance. + * @param[in,out] context pointer to the protocol-specific poller instance. + * @returns true if a supported card was detected, false otherwise. + */ +typedef bool (*NfcPollerDetect)(NfcGenericEvent event, void* context); + +/** + * @brief Get the data that was that was gathered during the reading process. + * + * @param[in] instance pointer to the protocol-specific poller instance. + * @returns pointer to the NFC device data. + */ +typedef const NfcDeviceData* (*NfcPollerGetData)(const NfcGenericInstance* instance); + +/** + * @brief Generic NFC poller interface. + * + * Each protocol must fill this structure with its own function implementations. + * See above for the function signatures and descriptions. + * + * Additionally, see ${PROTOCOL_NAME}/${PROTOCOL_NAME}_poller.c for usage examples. + */ +typedef struct { + NfcPollerAlloc alloc; /**< Pointer to the alloc() function. */ + NfcPollerFree free; /**< Pointer to the free() function. */ + NfcPollerSetCallback set_callback; /**< Pointer to the set_callback() function. */ + NfcPollerRun run; /**< Pointer to the run() function. */ + NfcPollerDetect detect; /**< Pointer to the detect() function. */ + NfcPollerGetData get_data; /**< Pointer to the get_data() function. */ +} NfcPollerBase; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/nfc_poller_defs.c b/lib/nfc/protocols/nfc_poller_defs.c new file mode 100644 index 000000000..7553c74de --- /dev/null +++ b/lib/nfc/protocols/nfc_poller_defs.c @@ -0,0 +1,28 @@ +#include "nfc_poller_defs.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +const NfcPollerBase* nfc_pollers_api[NfcProtocolNum] = { + [NfcProtocolIso14443_3a] = &nfc_poller_iso14443_3a, + [NfcProtocolIso14443_3b] = &nfc_poller_iso14443_3b, + [NfcProtocolIso14443_4a] = &nfc_poller_iso14443_4a, + [NfcProtocolIso14443_4b] = &nfc_poller_iso14443_4b, + [NfcProtocolIso15693_3] = &nfc_poller_iso15693_3, + [NfcProtocolFelica] = &nfc_poller_felica, + [NfcProtocolMfUltralight] = &mf_ultralight_poller, + [NfcProtocolMfClassic] = &mf_classic_poller, + [NfcProtocolMfDesfire] = &mf_desfire_poller, + [NfcProtocolSlix] = &nfc_poller_slix, + /* Add new pollers here */ + [NfcProtocolSt25tb] = &nfc_poller_st25tb, +}; diff --git a/lib/nfc/protocols/nfc_poller_defs.h b/lib/nfc/protocols/nfc_poller_defs.h new file mode 100644 index 000000000..a406a5f08 --- /dev/null +++ b/lib/nfc/protocols/nfc_poller_defs.h @@ -0,0 +1,14 @@ +#pragma once + +#include "nfc_poller_base.h" +#include "nfc_protocol.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NfcPollerBase* nfc_pollers_api[NfcProtocolNum]; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/nfc_protocol.c b/lib/nfc/protocols/nfc_protocol.c new file mode 100644 index 000000000..2ea9b3982 --- /dev/null +++ b/lib/nfc/protocols/nfc_protocol.c @@ -0,0 +1,174 @@ +/** + * @file nfc_protocol.c + * @brief Main protocol hierarchy definitions. + * + * To reduce code duplication, all NFC protocols are described as a tree, whose + * structure is shown in the diagram below. The (Start) node is actually + * nonexistent and is there only for clarity. + * + * All its child protocols are considered base protocols, which in turn serve + * as parents to other, usually vendor-specific ones. + * + * ``` + * **************************** Protocol tree structure *************************** + * + * (Start) + * | + * +------------------------+-----------+---------+------------+ + * | | | | | + * ISO14443-3A ISO14443-3B Felica ISO15693-3 ST25TB + * | | | + * +---------------+-------------+ ISO14443-4B SLIX + * | | | + * ISO14443-4A Mf Ultralight Mf Classic + * | + * Mf Desfire + * ``` + * + * When implementing a new protocol, its place in the tree must be determined first. + * If no appropriate base protocols exists, then it must be a base protocol itself. + * + * This file is to be modified upon adding a new protocol (see below). + * + */ +#include "nfc_protocol.h" + +#include + +/** + * @brief Tree node describing a protocol. + * + * All base protocols (see above) have NfcProtocolInvalid + * in the parent_protocol field. + */ +typedef struct { + NfcProtocol parent_protocol; /**< Parent protocol identifier. */ + size_t children_num; /** < Number of the child protocols. */ + const NfcProtocol* children_protocol; /**< Pointer to an array of child protocol identifiers. */ +} NfcProtocolTreeNode; + +/** List of ISO14443-3A child protocols. */ +static const NfcProtocol nfc_protocol_iso14443_3a_children_protocol[] = { + NfcProtocolIso14443_4a, + NfcProtocolMfUltralight, +}; + +/** List of ISO14443-3B child protocols. */ +static const NfcProtocol nfc_protocol_iso14443_3b_children_protocol[] = { + NfcProtocolIso14443_4b, +}; + +/** List of ISO14443-4A child protocols. */ +static const NfcProtocol nfc_protocol_iso14443_4a_children_protocol[] = { + NfcProtocolMfDesfire, +}; + +/** List of ISO115693-3 child protocols. */ +static const NfcProtocol nfc_protocol_iso15693_3_children_protocol[] = { + NfcProtocolSlix, +}; + +/* Add new child protocol lists here (if necessary) */ + +/** + * @brief Flattened description of the NFC protocol tree. + * + * When implementing a new protocol, add the node here under its + * own index defined in nfc_protocol.h. + * + * Additionally, if it has an already implemented protocol as a parent, + * add its identifier to its respective list of child protocols (see above). + */ +static const NfcProtocolTreeNode nfc_protocol_nodes[NfcProtocolNum] = { + [NfcProtocolIso14443_3a] = + { + .parent_protocol = NfcProtocolInvalid, + .children_num = COUNT_OF(nfc_protocol_iso14443_3a_children_protocol), + .children_protocol = nfc_protocol_iso14443_3a_children_protocol, + }, + [NfcProtocolIso14443_3b] = + { + .parent_protocol = NfcProtocolInvalid, + .children_num = COUNT_OF(nfc_protocol_iso14443_3b_children_protocol), + .children_protocol = nfc_protocol_iso14443_3b_children_protocol, + }, + [NfcProtocolIso14443_4a] = + { + .parent_protocol = NfcProtocolIso14443_3a, + .children_num = COUNT_OF(nfc_protocol_iso14443_4a_children_protocol), + .children_protocol = nfc_protocol_iso14443_4a_children_protocol, + }, + [NfcProtocolIso14443_4b] = + { + .parent_protocol = NfcProtocolIso14443_3b, + .children_num = 0, + .children_protocol = NULL, + }, + [NfcProtocolIso15693_3] = + { + .parent_protocol = NfcProtocolInvalid, + .children_num = COUNT_OF(nfc_protocol_iso15693_3_children_protocol), + .children_protocol = nfc_protocol_iso15693_3_children_protocol, + }, + [NfcProtocolFelica] = + { + .parent_protocol = NfcProtocolInvalid, + .children_num = 0, + .children_protocol = NULL, + }, + [NfcProtocolMfUltralight] = + { + .parent_protocol = NfcProtocolIso14443_3a, + .children_num = 0, + .children_protocol = NULL, + }, + [NfcProtocolMfClassic] = + { + .parent_protocol = NfcProtocolIso14443_3a, + .children_num = 0, + .children_protocol = NULL, + }, + [NfcProtocolMfDesfire] = + { + .parent_protocol = NfcProtocolIso14443_4a, + .children_num = 0, + .children_protocol = NULL, + }, + [NfcProtocolSlix] = + { + .parent_protocol = NfcProtocolIso15693_3, + .children_num = 0, + .children_protocol = NULL, + }, + [NfcProtocolSt25tb] = + { + .parent_protocol = NfcProtocolInvalid, + .children_num = 0, + .children_protocol = NULL, + }, + /* Add new protocols here */ +}; + +NfcProtocol nfc_protocol_get_parent(NfcProtocol protocol) { + furi_assert(protocol < NfcProtocolNum); + + return nfc_protocol_nodes[protocol].parent_protocol; +} + +bool nfc_protocol_has_parent(NfcProtocol protocol, NfcProtocol parent_protocol) { + furi_assert(protocol < NfcProtocolNum); + furi_assert(parent_protocol < NfcProtocolNum); + + bool parent_found = false; + const NfcProtocolTreeNode* iter = &nfc_protocol_nodes[protocol]; + + while(iter->parent_protocol != NfcProtocolInvalid) { + if(iter->parent_protocol == parent_protocol) { + parent_found = true; + break; + } + iter = &nfc_protocol_nodes[iter->parent_protocol]; + } + + return parent_found; +} diff --git a/lib/nfc/protocols/nfc_protocol.h b/lib/nfc/protocols/nfc_protocol.h new file mode 100644 index 000000000..55aa8a589 --- /dev/null +++ b/lib/nfc/protocols/nfc_protocol.h @@ -0,0 +1,219 @@ +/** + * @file nfc_protocol.h + * @brief Top-level NFC protocol definitions. + * + * This file is to be modified upon adding a new protocol (see below). + * + * # How to add a new NFC protocol + * + * ## 1. Gather information + * + * Having proper protocol documentation would be ideal, although they are often available only for a fee, or given under an NDA. + * As an alternative, reading code from relevant open-source projects or notes gathered by means of reverse engineering will do. + * + * ### 1.1 Technology + * + * Check whether the NFC technology required for the protocol is supported. If no support exists, adding the protocol may + * be problematic, since it is highly hardware-dependent. + * + * @see NfcTech for the enumeration of supported NFC technologies. + * + * ### 1.2 Base protocols + * + * Check whether the protocol to be implemented is built on top of some already supported protocol. + * + * @see NfcProtocol for the enumeration of supported NFC protocols. + * + * If the answer is "yes", then the protocol to be implemented is a child protocol. If no, then it will become a base protocol. + * Sometimes it will be necessary to implement both, e.g. when the target protocol is built on top of a base one, + * but the latter is currently not supported. + * + * ## 2. Create the files + * + * ### 2.1 Recommended file structure + * + * The recommended file structure for a protocol is as follows: + * + * ```text + * protocols + * | + * +- protocol_name + * | + * +- protocol_name.h + * | + * +- protocol_name.c + * | + * +- protocol_name_device_defs.h + * | + * +- protocol_name_poller.h + * | + * +- protocol_name_poller.c + * | + * +- protocol_name_poller_defs.h + * | + * . + * . (files below are optional) + * . + * | + * +- protocol_name_listener.h | + * | | + * +- protocol_name_listener.c |- add for emulation support + * | | + * +- protocol_name_listener_defs.h | + * | + * +- protocol_name_sync_api.h | + * | |- add for synchronous API support + * +- protocol_name_sync_api.c | + * | + * ``` + * + * Additionally, an arbitrary amount of private `protocol_name_*_i.h` header files may be created. Do not put implementation + * details in the regular header files, as they will be exposed in the public firmware API later on. + * + * ### 2.2 File structure explanation + * + * | Filename | Explanation | + * |:------------------------------|:------------| + * | protocol_name.h | Main protocol data structure and associated functions declarations. It is recommended to keep the former as opaque pointer. | + * | protocol_name.c | Implementations of functions declared in `protocol_name.h`. | + * | protocol_name_device_defs.h | Declarations for use by the NfcDevice library. See nfc_device_base_i.h for more info. | + * | protocol_name_poller.h | Protocol-specific poller and associated functions declarations. | + * | protocol_name_poller.c | Implementation of functions declared in `protocol_name_poller.h`. | + * | protocol_name_poller_defs.h | Declarations for use by the NfcPoller library. See nfc_poller_base.h for more info. | + * | protocol_name_listener.h | Protocol-specific listener and associated functions declarations. Optional, needed for emulation support. | + * | protocol_name_listener.c | Implementation of functions declared in `protocol_name_listener.h`. Optional, needed for emulation support. | + * | protocol_name_listener_defs.h | Declarations for use by the NfcListener library. See nfc_listener_base.h for more info. Optional, needed for emulation support. | + * | protocol_name_sync_api.h | Synchronous API declarations. (See below for sync API explanation). Optional.| + * | protocol_name_sync_api.c | Synchronous API implementation. Optional. | + * + * ## 3 Implement the code + * + * ### 3.1 Protocol data structure + * + * A protocol data structure is what holds all data that can be possibly read from a card of a certain type. It may include a unique identifier (UID), + * configuration bytes and flags, built-in memory, and so on. + * Additionally, it must implement the NfcDevice interface so that it could be used by the firmware. + * + * @see nfc_device_base_i.h for the device interface description. + * + * @note It is strongly recommended to implement such a structure as an opaque type and access it via specialised methods only. + * + * If the protocol being implemented is a child protocol, then its data must include a pointer to the parent protocol data structure. + * It is the protocol's responsibility to correctly create and delete the instance the pointer is pointing to. + * + * ### 3.2 Poller (reading functionality) + * + * A poller contains the functions necessary to successfully read a card of supported type. It must also implement a specific interface, + * namely described by the NfcPollerBase type. + * + * Upon creation, a poller instance will receive either a pointer to the Nfc instance (if it's a base protocol), or a pointer to another poller + * instance (if it is a child protocol) as the `alloc()` parameter. + * + * @see nfc_poller_base.h for the poller interface description. + * + * ### 3.3 Listener (emulation functionality) + * + * A listener implementation is optional, needed only when emulation is required/possible. + * + * Same considerations apply to the listener as for the poller. Additionally, upon creation it will receive an additional parameter + * in the form of a pointer to the matching protocol data structure, which will be used during emulation. The listener instance + * does not own this data and does not need to worry about its deletion. + * + * @see nfc_listener_base.h for the listener interface description. + * + * ### 3.4 Synchronous API + * + * Synchronous API does exaclty what it says -- it provides a set of blocking functions for easier use of pollers. + * Instead of creating all necessary instances and setting up callbacks manually, it does it automatically, at the + * expense of some flexibility. + * + * The most notable use of sync API is in the supported card plugins, so it's a good idea to implement it if such a plugin + * is to be implemented afterwards. + * + * ### 3.5 Registering the protocol + * + * After completing the protocol, it must be registered within the NfcProtocol system in order for it to be usable. + * + * 1. In nfc_protocol.h, add a new entry in the NfcProtocol enum in the form of NfcProtocolProtocolName. + * 2. In nfc_protocol.c, add a new entry in the `nfc_protocol_nodes[]` array under the appropriate index. + * 1. If it is a child protocol, register it as a child in the respective `nfc_base_protocol_name_children_protocol[]` array. + * 2. If the protocol has children on its own, create a `nfc_protocol_name_children_protocol[]` array + * with respective identifiers and register it in the protocol entry added in step 2. + * 3. In nfc_device_defs.c, include `protocol_name_device_defs.h` and add a pointer to the + * `protocol_name_device_defs` structure under the appropriate index. + * 4. In nfc_poller_defs.c, include `protocol_name_poller_defs.h` and add a pointer to the + * `protocol_name_poller_defs` structure under the appropriate index. + * 5. (Optional) If emulation support was implemented, do the step 4, but for the listener. + * 6. Add `protocol_name.h`, `protocol_name_poller.h`, and optionally, `protocol_name_listener.h` + * and `protocol_name_sync_api.h` into the `SDK_HEADERS` list in the SConscript file. + * This will export the protocol's types and functions for use by the applications. + * 7. Done! + * + * ## What's next? + * + * It's about time to integrate the newly implemented protocol into the main NFC application. Without that, reading a card + * of this type would crash it. + * + * @see nfc_protocol_support.h for more information on protocol integration. + * + * After having done that, a supported card plugin may be implemented to take further advantage of the new protocol. + * + * @see nfc_supported_card_plugin.h for more information on supported card plugins. + * + */ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Enumeration of all available NFC protocols. + * + * When implementing a new protocol, add its identifier before the + * NfcProtocolNum entry. + */ +typedef enum { + NfcProtocolIso14443_3a, + NfcProtocolIso14443_3b, + NfcProtocolIso14443_4a, + NfcProtocolIso14443_4b, + NfcProtocolIso15693_3, + NfcProtocolFelica, + NfcProtocolMfUltralight, + NfcProtocolMfClassic, + NfcProtocolMfDesfire, + NfcProtocolSlix, + NfcProtocolSt25tb, + /* Add new protocols here */ + + NfcProtocolNum, /**< Special value representing the number of available protocols. */ + + NfcProtocolInvalid, /**< Special value representing an invalid state. */ +} NfcProtocol; + +/** + * @brief Get the immediate parent of a specific protocol. + * + * @param[in] protocol identifier of the protocol in question. + * @returns parent protocol identifier if it has one, or NfcProtocolInvalid otherwise. + */ +NfcProtocol nfc_protocol_get_parent(NfcProtocol protocol); + +/** + * @brief Determine if a specific protocol has a parent on an arbitrary level. + * + * Unlike nfc_protocol_get_parent(), this function will traverse the full protocol hierarchy + * and check each parent node for the matching protocol type. + * + * @param[in] protocol identifier of the protocol in question. + * @param[in] parent_protocol identifier of the parent protocol in question. + * @returns true if the parent of given type exists, false otherwise. + */ +bool nfc_protocol_has_parent(NfcProtocol protocol, NfcProtocol parent_protocol); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/nfca.c b/lib/nfc/protocols/nfca.c deleted file mode 100644 index ab4f3f23c..000000000 --- a/lib/nfc/protocols/nfca.c +++ /dev/null @@ -1,140 +0,0 @@ -#include "nfca.h" -#include -#include -#include - -#define NFCA_CRC_INIT (0x6363) - -#define NFCA_F_SIG (13560000.0) -#define T_SIG 7374 //73.746ns*100 -#define T_SIG_x8 58992 //T_SIG*8 -#define T_SIG_x8_x8 471936 //T_SIG*8*8 -#define T_SIG_x8_x9 530928 //T_SIG*8*9 - -#define NFCA_SIGNAL_MAX_EDGES (1350) - -typedef struct { - uint8_t cmd; - uint8_t param; -} nfca_cmd_rats; - -static uint8_t nfca_default_ats[] = {0x05, 0x78, 0x80, 0x80, 0x00}; - -static uint8_t nfca_halt_req[] = {NFCA_CMD_HALT, 0x00}; - -uint16_t nfca_get_crc16(uint8_t* buff, uint16_t len) { - uint16_t crc = NFCA_CRC_INIT; - uint8_t byte = 0; - - for(uint8_t i = 0; i < len; i++) { - byte = buff[i]; - byte ^= (uint8_t)(crc & 0xff); - byte ^= byte << 4; - crc = (crc >> 8) ^ (((uint16_t)byte) << 8) ^ (((uint16_t)byte) << 3) ^ - (((uint16_t)byte) >> 4); - } - - return crc; -} - -void nfca_append_crc16(uint8_t* buff, uint16_t len) { - uint16_t crc = nfca_get_crc16(buff, len); - buff[len] = (uint8_t)crc; - buff[len + 1] = (uint8_t)(crc >> 8); -} - -bool nfca_emulation_handler( - uint8_t* buff_rx, - uint16_t buff_rx_len, - uint8_t* buff_tx, - uint16_t* buff_tx_len) { - bool halt = false; - uint8_t rx_bytes = buff_rx_len / 8; - - if(rx_bytes == sizeof(nfca_halt_req) && !memcmp(buff_rx, nfca_halt_req, rx_bytes)) { - halt = true; - } else if(rx_bytes == sizeof(nfca_cmd_rats) && buff_rx[0] == NFCA_CMD_RATS) { - memcpy(buff_tx, nfca_default_ats, sizeof(nfca_default_ats)); - *buff_tx_len = sizeof(nfca_default_ats) * 8; - } - - return halt; -} - -static void nfca_add_bit(DigitalSignal* signal, bool bit) { - if(bit) { - signal->start_level = true; - for(size_t i = 0; i < 7; i++) { - signal->edge_timings[i] = T_SIG_x8; - } - signal->edge_timings[7] = T_SIG_x8_x9; - signal->edge_cnt = 8; - } else { - signal->start_level = false; - signal->edge_timings[0] = T_SIG_x8_x8; - for(size_t i = 1; i < 9; i++) { - signal->edge_timings[i] = T_SIG_x8; - } - signal->edge_cnt = 9; - } -} - -static void nfca_add_byte(NfcaSignal* nfca_signal, uint8_t byte, bool parity) { - for(uint8_t i = 0; i < 8; i++) { - if(byte & (1 << i)) { - digital_signal_append(nfca_signal->tx_signal, nfca_signal->one); - } else { - digital_signal_append(nfca_signal->tx_signal, nfca_signal->zero); - } - } - if(parity) { - digital_signal_append(nfca_signal->tx_signal, nfca_signal->one); - } else { - digital_signal_append(nfca_signal->tx_signal, nfca_signal->zero); - } -} - -NfcaSignal* nfca_signal_alloc() { - NfcaSignal* nfca_signal = malloc(sizeof(NfcaSignal)); - nfca_signal->one = digital_signal_alloc(10); - nfca_signal->zero = digital_signal_alloc(10); - nfca_add_bit(nfca_signal->one, true); - nfca_add_bit(nfca_signal->zero, false); - nfca_signal->tx_signal = digital_signal_alloc(NFCA_SIGNAL_MAX_EDGES); - - return nfca_signal; -} - -void nfca_signal_free(NfcaSignal* nfca_signal) { - furi_assert(nfca_signal); - - digital_signal_free(nfca_signal->one); - digital_signal_free(nfca_signal->zero); - digital_signal_free(nfca_signal->tx_signal); - free(nfca_signal); -} - -void nfca_signal_encode(NfcaSignal* nfca_signal, uint8_t* data, uint16_t bits, uint8_t* parity) { - furi_assert(nfca_signal); - furi_assert(data); - furi_assert(parity); - - nfca_signal->tx_signal->edge_cnt = 0; - nfca_signal->tx_signal->start_level = true; - // Start of frame - digital_signal_append(nfca_signal->tx_signal, nfca_signal->one); - - if(bits < 8) { - for(size_t i = 0; i < bits; i++) { - if(FURI_BIT(data[0], i)) { - digital_signal_append(nfca_signal->tx_signal, nfca_signal->one); - } else { - digital_signal_append(nfca_signal->tx_signal, nfca_signal->zero); - } - } - } else { - for(size_t i = 0; i < bits / 8; i++) { - nfca_add_byte(nfca_signal, data[i], parity[i / 8] & (1 << (7 - (i & 0x07)))); - } - } -} diff --git a/lib/nfc/protocols/nfca.h b/lib/nfc/protocols/nfca.h deleted file mode 100644 index e4978a3e0..000000000 --- a/lib/nfc/protocols/nfca.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include - -#include - -#define NFCA_CMD_RATS (0xE0U) -#define NFCA_CMD_HALT (0x50U) - -typedef struct { - DigitalSignal* one; - DigitalSignal* zero; - DigitalSignal* tx_signal; -} NfcaSignal; - -uint16_t nfca_get_crc16(uint8_t* buff, uint16_t len); - -void nfca_append_crc16(uint8_t* buff, uint16_t len); - -bool nfca_emulation_handler( - uint8_t* buff_rx, - uint16_t buff_rx_len, - uint8_t* buff_tx, - uint16_t* buff_tx_len); - -NfcaSignal* nfca_signal_alloc(); - -void nfca_signal_free(NfcaSignal* nfca_signal); - -void nfca_signal_encode(NfcaSignal* nfca_signal, uint8_t* data, uint16_t bits, uint8_t* parity); diff --git a/lib/nfc/protocols/nfcv.c b/lib/nfc/protocols/nfcv.c deleted file mode 100644 index 281463281..000000000 --- a/lib/nfc/protocols/nfcv.c +++ /dev/null @@ -1,1438 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "nfcv.h" -#include "nfc_util.h" -#include "slix.h" - -#define TAG "NfcV" - -/* macros to map "modulate field" flag to GPIO level */ -#define GPIO_LEVEL_MODULATED NFCV_LOAD_MODULATION_POLARITY -#define GPIO_LEVEL_UNMODULATED (!GPIO_LEVEL_MODULATED) - -/* timing macros */ -#define DIGITAL_SIGNAL_UNIT_S (100000000000.0f) -#define DIGITAL_SIGNAL_UNIT_US (100000.0f) - -ReturnCode nfcv_inventory(uint8_t* uid) { - uint16_t received = 0; - rfalNfcvInventoryRes res; - ReturnCode ret = ERR_NONE; - - for(int tries = 0; tries < NFCV_COMMAND_RETRIES; tries++) { - /* TODO: needs proper abstraction via furi_hal(_ll)_* */ - ret = rfalNfcvPollerInventory(RFAL_NFCV_NUM_SLOTS_1, 0, NULL, &res, &received); - - if(ret == ERR_NONE) { - break; - } - } - - if(ret == ERR_NONE) { - if(uid != NULL) { - memcpy(uid, res.UID, NFCV_UID_LENGTH); - } - } - - return ret; -} - -ReturnCode nfcv_read_blocks(NfcVReader* reader, NfcVData* nfcv_data) { - UNUSED(reader); - - uint16_t received = 0; - for(size_t block = 0; block < nfcv_data->block_num; block++) { - uint8_t rxBuf[32]; - FURI_LOG_D(TAG, "Reading block %d/%d", block, (nfcv_data->block_num - 1)); - - ReturnCode ret = ERR_NONE; - for(int tries = 0; tries < NFCV_COMMAND_RETRIES; tries++) { - ret = rfalNfcvPollerReadSingleBlock( - RFAL_NFCV_REQ_FLAG_DEFAULT, NULL, block, rxBuf, sizeof(rxBuf), &received); - - if(ret == ERR_NONE) { - break; - } - } - if(ret != ERR_NONE) { - FURI_LOG_D(TAG, "failed to read: %d", ret); - return ret; - } - memcpy( - &(nfcv_data->data[block * nfcv_data->block_size]), &rxBuf[1], nfcv_data->block_size); - FURI_LOG_D( - TAG, - " %02X %02X %02X %02X", - nfcv_data->data[block * nfcv_data->block_size + 0], - nfcv_data->data[block * nfcv_data->block_size + 1], - nfcv_data->data[block * nfcv_data->block_size + 2], - nfcv_data->data[block * nfcv_data->block_size + 3]); - } - - return ERR_NONE; -} - -ReturnCode nfcv_read_sysinfo(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data) { - uint8_t rxBuf[32]; - uint16_t received = 0; - ReturnCode ret = ERR_NONE; - - FURI_LOG_D(TAG, "Read SYSTEM INFORMATION..."); - - for(int tries = 0; tries < NFCV_COMMAND_RETRIES; tries++) { - /* TODO: needs proper abstraction via furi_hal(_ll)_* */ - ret = rfalNfcvPollerGetSystemInformation( - RFAL_NFCV_REQ_FLAG_DEFAULT, NULL, rxBuf, sizeof(rxBuf), &received); - - if(ret == ERR_NONE) { - break; - } - } - - if(ret == ERR_NONE) { - nfc_data->type = FuriHalNfcTypeV; - nfc_data->uid_len = NFCV_UID_LENGTH; - /* UID is stored reversed in this response */ - for(int pos = 0; pos < nfc_data->uid_len; pos++) { - nfc_data->uid[pos] = rxBuf[2 + (NFCV_UID_LENGTH - 1 - pos)]; - } - nfcv_data->dsfid = rxBuf[NFCV_UID_LENGTH + 2]; - nfcv_data->afi = rxBuf[NFCV_UID_LENGTH + 3]; - nfcv_data->block_num = rxBuf[NFCV_UID_LENGTH + 4] + 1; - nfcv_data->block_size = rxBuf[NFCV_UID_LENGTH + 5] + 1; - nfcv_data->ic_ref = rxBuf[NFCV_UID_LENGTH + 6]; - FURI_LOG_D( - TAG, - " UID: %02X %02X %02X %02X %02X %02X %02X %02X", - nfc_data->uid[0], - nfc_data->uid[1], - nfc_data->uid[2], - nfc_data->uid[3], - nfc_data->uid[4], - nfc_data->uid[5], - nfc_data->uid[6], - nfc_data->uid[7]); - FURI_LOG_D( - TAG, - " DSFID %d, AFI %d, Blocks %d, Size %d, IC Ref %d", - nfcv_data->dsfid, - nfcv_data->afi, - nfcv_data->block_num, - nfcv_data->block_size, - nfcv_data->ic_ref); - return ret; - } - FURI_LOG_D(TAG, "Failed: %d", ret); - - return ret; -} - -bool nfcv_read_card(NfcVReader* reader, FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data) { - furi_assert(reader); - furi_assert(nfc_data); - furi_assert(nfcv_data); - - if(nfcv_read_sysinfo(nfc_data, nfcv_data) != ERR_NONE) { - return false; - } - - if(nfcv_read_blocks(reader, nfcv_data) != ERR_NONE) { - return false; - } - - /* clear all know sub type data before reading them */ - memset(&nfcv_data->sub_data, 0x00, sizeof(nfcv_data->sub_data)); - - if(slix_check_card_type(nfc_data)) { - FURI_LOG_I(TAG, "NXP SLIX detected"); - nfcv_data->sub_type = NfcVTypeSlix; - } else if(slix2_check_card_type(nfc_data)) { - FURI_LOG_I(TAG, "NXP SLIX2 detected"); - nfcv_data->sub_type = NfcVTypeSlix2; - if(slix2_read_custom(nfc_data, nfcv_data) != ERR_NONE) { - return false; - } - } else if(slix_s_check_card_type(nfc_data)) { - FURI_LOG_I(TAG, "NXP SLIX-S detected"); - nfcv_data->sub_type = NfcVTypeSlixS; - } else if(slix_l_check_card_type(nfc_data)) { - FURI_LOG_I(TAG, "NXP SLIX-L detected"); - nfcv_data->sub_type = NfcVTypeSlixL; - } else { - nfcv_data->sub_type = NfcVTypePlain; - } - - return true; -} - -void nfcv_crc(uint8_t* data, uint32_t length) { - uint32_t reg = 0xFFFF; - - for(size_t i = 0; i < length; i++) { - reg = reg ^ ((uint32_t)data[i]); - for(size_t j = 0; j < 8; j++) { - if(reg & 0x0001) { - reg = (reg >> 1) ^ 0x8408; - } else { - reg = (reg >> 1); - } - } - } - - uint16_t crc = ~(uint16_t)(reg & 0xffff); - - data[length + 0] = crc & 0xFF; - data[length + 1] = crc >> 8; -} - -void nfcv_emu_free_signals(NfcVEmuAirSignals* signals) { - furi_assert(signals); - - if(signals->nfcv_resp_one) { - digital_signal_free(signals->nfcv_resp_one); - } - if(signals->nfcv_resp_zero) { - digital_signal_free(signals->nfcv_resp_zero); - } - if(signals->nfcv_resp_sof) { - digital_signal_free(signals->nfcv_resp_sof); - } - if(signals->nfcv_resp_eof) { - digital_signal_free(signals->nfcv_resp_eof); - } - signals->nfcv_resp_one = NULL; - signals->nfcv_resp_zero = NULL; - signals->nfcv_resp_sof = NULL; - signals->nfcv_resp_eof = NULL; -} - -bool nfcv_emu_alloc_signals(NfcVEmuAir* air, NfcVEmuAirSignals* signals, uint32_t slowdown) { - furi_assert(air); - furi_assert(signals); - - bool success = true; - - if(!signals->nfcv_resp_one) { - /* logical one: unmodulated then 8 pulses */ - signals->nfcv_resp_one = digital_signal_alloc( - slowdown * (air->nfcv_resp_unmod->edge_cnt + 8 * air->nfcv_resp_pulse->edge_cnt)); - if(!signals->nfcv_resp_one) { - return false; - } - for(size_t i = 0; i < slowdown; i++) { - success &= digital_signal_append(signals->nfcv_resp_one, air->nfcv_resp_unmod); - } - for(size_t i = 0; i < slowdown * 8; i++) { - success &= digital_signal_append(signals->nfcv_resp_one, air->nfcv_resp_pulse); - } - if(!success) { - return false; - } - } - if(!signals->nfcv_resp_zero) { - /* logical zero: 8 pulses then unmodulated */ - signals->nfcv_resp_zero = digital_signal_alloc( - slowdown * (8 * air->nfcv_resp_pulse->edge_cnt + air->nfcv_resp_unmod->edge_cnt)); - if(!signals->nfcv_resp_zero) { - return false; - } - for(size_t i = 0; i < slowdown * 8; i++) { - success &= digital_signal_append(signals->nfcv_resp_zero, air->nfcv_resp_pulse); - } - for(size_t i = 0; i < slowdown; i++) { - success &= digital_signal_append(signals->nfcv_resp_zero, air->nfcv_resp_unmod); - } - if(!success) { - return false; - } - } - if(!signals->nfcv_resp_sof) { - /* SOF: unmodulated, 24 pulses, logic 1 */ - signals->nfcv_resp_sof = digital_signal_alloc( - slowdown * (3 * air->nfcv_resp_unmod->edge_cnt + 24 * air->nfcv_resp_pulse->edge_cnt) + - signals->nfcv_resp_one->edge_cnt); - if(!signals->nfcv_resp_sof) { - return false; - } - for(size_t i = 0; i < slowdown * 3; i++) { - success &= digital_signal_append(signals->nfcv_resp_sof, air->nfcv_resp_unmod); - } - for(size_t i = 0; i < slowdown * 24; i++) { - success &= digital_signal_append(signals->nfcv_resp_sof, air->nfcv_resp_pulse); - } - success &= digital_signal_append(signals->nfcv_resp_sof, signals->nfcv_resp_one); - if(!success) { - return false; - } - } - if(!signals->nfcv_resp_eof) { - /* EOF: logic 0, 24 pulses, unmodulated */ - signals->nfcv_resp_eof = digital_signal_alloc( - signals->nfcv_resp_zero->edge_cnt + - slowdown * (24 * air->nfcv_resp_pulse->edge_cnt + 3 * air->nfcv_resp_unmod->edge_cnt) + - air->nfcv_resp_unmod->edge_cnt); - if(!signals->nfcv_resp_eof) { - return false; - } - success &= digital_signal_append(signals->nfcv_resp_eof, signals->nfcv_resp_zero); - for(size_t i = 0; i < slowdown * 23; i++) { - success &= digital_signal_append(signals->nfcv_resp_eof, air->nfcv_resp_pulse); - } - /* we don't want to add the last level as we just want a transition to "unmodulated" again */ - for(size_t i = 0; i < slowdown; i++) { - success &= digital_signal_append(signals->nfcv_resp_eof, air->nfcv_resp_half_pulse); - } - } - return success; -} - -bool nfcv_emu_alloc(NfcVData* nfcv_data) { - furi_assert(nfcv_data); - - if(!nfcv_data->frame) { - nfcv_data->frame = malloc(NFCV_FRAMESIZE_MAX); - if(!nfcv_data->frame) { - return false; - } - } - - if(!nfcv_data->emu_air.nfcv_signal) { - /* assuming max frame length is 255 bytes */ - nfcv_data->emu_air.nfcv_signal = digital_sequence_alloc(8 * 255 + 2, &gpio_spi_r_mosi); - if(!nfcv_data->emu_air.nfcv_signal) { - return false; - } - } - if(!nfcv_data->emu_air.nfcv_resp_unmod) { - /* unmodulated 256/fc or 1024/fc signal as building block */ - nfcv_data->emu_air.nfcv_resp_unmod = digital_signal_alloc(4); - if(!nfcv_data->emu_air.nfcv_resp_unmod) { - return false; - } - nfcv_data->emu_air.nfcv_resp_unmod->start_level = GPIO_LEVEL_UNMODULATED; - nfcv_data->emu_air.nfcv_resp_unmod->edge_timings[0] = - (uint32_t)(NFCV_RESP_SUBC1_UNMOD_256 * DIGITAL_SIGNAL_UNIT_S); - nfcv_data->emu_air.nfcv_resp_unmod->edge_cnt = 1; - } - if(!nfcv_data->emu_air.nfcv_resp_pulse) { - /* modulated fc/32 or fc/8 pulse as building block */ - nfcv_data->emu_air.nfcv_resp_pulse = digital_signal_alloc(4); - if(!nfcv_data->emu_air.nfcv_resp_pulse) { - return false; - } - nfcv_data->emu_air.nfcv_resp_pulse->start_level = GPIO_LEVEL_MODULATED; - nfcv_data->emu_air.nfcv_resp_pulse->edge_timings[0] = - (uint32_t)(NFCV_RESP_SUBC1_PULSE_32 * DIGITAL_SIGNAL_UNIT_S); - nfcv_data->emu_air.nfcv_resp_pulse->edge_timings[1] = - (uint32_t)(NFCV_RESP_SUBC1_PULSE_32 * DIGITAL_SIGNAL_UNIT_S); - nfcv_data->emu_air.nfcv_resp_pulse->edge_cnt = 2; - } - - if(!nfcv_data->emu_air.nfcv_resp_half_pulse) { - /* modulated fc/32 or fc/8 pulse as building block */ - nfcv_data->emu_air.nfcv_resp_half_pulse = digital_signal_alloc(4); - if(!nfcv_data->emu_air.nfcv_resp_half_pulse) { - return false; - } - nfcv_data->emu_air.nfcv_resp_half_pulse->start_level = GPIO_LEVEL_MODULATED; - nfcv_data->emu_air.nfcv_resp_half_pulse->edge_timings[0] = - (uint32_t)(NFCV_RESP_SUBC1_PULSE_32 * DIGITAL_SIGNAL_UNIT_S); - nfcv_data->emu_air.nfcv_resp_half_pulse->edge_cnt = 1; - } - - bool success = true; - success &= nfcv_emu_alloc_signals(&nfcv_data->emu_air, &nfcv_data->emu_air.signals_high, 1); - success &= nfcv_emu_alloc_signals(&nfcv_data->emu_air, &nfcv_data->emu_air.signals_low, 4); - - if(!success) { - FURI_LOG_E(TAG, "Failed to allocate signals"); - return false; - } - - digital_sequence_set_signal( - nfcv_data->emu_air.nfcv_signal, - NFCV_SIG_SOF, - nfcv_data->emu_air.signals_high.nfcv_resp_sof); - digital_sequence_set_signal( - nfcv_data->emu_air.nfcv_signal, - NFCV_SIG_BIT0, - nfcv_data->emu_air.signals_high.nfcv_resp_zero); - digital_sequence_set_signal( - nfcv_data->emu_air.nfcv_signal, - NFCV_SIG_BIT1, - nfcv_data->emu_air.signals_high.nfcv_resp_one); - digital_sequence_set_signal( - nfcv_data->emu_air.nfcv_signal, - NFCV_SIG_EOF, - nfcv_data->emu_air.signals_high.nfcv_resp_eof); - digital_sequence_set_signal( - nfcv_data->emu_air.nfcv_signal, - NFCV_SIG_LOW_SOF, - nfcv_data->emu_air.signals_low.nfcv_resp_sof); - digital_sequence_set_signal( - nfcv_data->emu_air.nfcv_signal, - NFCV_SIG_LOW_BIT0, - nfcv_data->emu_air.signals_low.nfcv_resp_zero); - digital_sequence_set_signal( - nfcv_data->emu_air.nfcv_signal, - NFCV_SIG_LOW_BIT1, - nfcv_data->emu_air.signals_low.nfcv_resp_one); - digital_sequence_set_signal( - nfcv_data->emu_air.nfcv_signal, - NFCV_SIG_LOW_EOF, - nfcv_data->emu_air.signals_low.nfcv_resp_eof); - - return true; -} - -void nfcv_emu_free(NfcVData* nfcv_data) { - furi_assert(nfcv_data); - - if(nfcv_data->frame) { - free(nfcv_data->frame); - } - if(nfcv_data->emu_protocol_ctx) { - free(nfcv_data->emu_protocol_ctx); - } - if(nfcv_data->emu_air.nfcv_resp_unmod) { - digital_signal_free(nfcv_data->emu_air.nfcv_resp_unmod); - } - if(nfcv_data->emu_air.nfcv_resp_pulse) { - digital_signal_free(nfcv_data->emu_air.nfcv_resp_pulse); - } - if(nfcv_data->emu_air.nfcv_resp_half_pulse) { - digital_signal_free(nfcv_data->emu_air.nfcv_resp_half_pulse); - } - if(nfcv_data->emu_air.nfcv_signal) { - digital_sequence_free(nfcv_data->emu_air.nfcv_signal); - } - if(nfcv_data->emu_air.reader_signal) { - // Stop pulse reader and disable bus before free - pulse_reader_stop(nfcv_data->emu_air.reader_signal); - // Free pulse reader - pulse_reader_free(nfcv_data->emu_air.reader_signal); - } - - nfcv_data->frame = NULL; - nfcv_data->emu_air.nfcv_resp_unmod = NULL; - nfcv_data->emu_air.nfcv_resp_pulse = NULL; - nfcv_data->emu_air.nfcv_resp_half_pulse = NULL; - nfcv_data->emu_air.nfcv_signal = NULL; - nfcv_data->emu_air.reader_signal = NULL; - - nfcv_emu_free_signals(&nfcv_data->emu_air.signals_high); - nfcv_emu_free_signals(&nfcv_data->emu_air.signals_low); -} - -void nfcv_emu_send( - FuriHalNfcTxRxContext* tx_rx, - NfcVData* nfcv, - uint8_t* data, - uint8_t length, - NfcVSendFlags flags, - uint32_t send_time) { - furi_assert(tx_rx); - furi_assert(nfcv); - - /* picked default value (0) to match the most common format */ - if(flags == NfcVSendFlagsNormal) { - flags = NfcVSendFlagsSof | NfcVSendFlagsCrc | NfcVSendFlagsEof | - NfcVSendFlagsOneSubcarrier | NfcVSendFlagsHighRate; - } - - if(flags & NfcVSendFlagsCrc) { - nfcv_crc(data, length); - length += 2; - } - - /* depending on the request flags, send with high or low rate */ - uint32_t bit0 = (flags & NfcVSendFlagsHighRate) ? NFCV_SIG_BIT0 : NFCV_SIG_LOW_BIT0; - uint32_t bit1 = (flags & NfcVSendFlagsHighRate) ? NFCV_SIG_BIT1 : NFCV_SIG_LOW_BIT1; - uint32_t sof = (flags & NfcVSendFlagsHighRate) ? NFCV_SIG_SOF : NFCV_SIG_LOW_SOF; - uint32_t eof = (flags & NfcVSendFlagsHighRate) ? NFCV_SIG_EOF : NFCV_SIG_LOW_EOF; - - digital_sequence_clear(nfcv->emu_air.nfcv_signal); - - if(flags & NfcVSendFlagsSof) { - digital_sequence_add(nfcv->emu_air.nfcv_signal, sof); - } - - for(int bit_total = 0; bit_total < length * 8; bit_total++) { - uint32_t byte_pos = bit_total / 8; - uint32_t bit_pos = bit_total % 8; - uint8_t bit_val = 0x01 << bit_pos; - - digital_sequence_add(nfcv->emu_air.nfcv_signal, (data[byte_pos] & bit_val) ? bit1 : bit0); - } - - if(flags & NfcVSendFlagsEof) { - digital_sequence_add(nfcv->emu_air.nfcv_signal, eof); - } - - furi_hal_gpio_write(&gpio_spi_r_mosi, GPIO_LEVEL_UNMODULATED); - digital_sequence_set_sendtime(nfcv->emu_air.nfcv_signal, send_time); - digital_sequence_send(nfcv->emu_air.nfcv_signal); - furi_hal_gpio_write(&gpio_spi_r_mosi, GPIO_LEVEL_UNMODULATED); - - if(tx_rx->sniff_tx) { - tx_rx->sniff_tx(data, length * 8, false, tx_rx->sniff_context); - } -} - -static void nfcv_revuidcpy(uint8_t* dst, uint8_t* src) { - for(int pos = 0; pos < NFCV_UID_LENGTH; pos++) { - dst[pos] = src[NFCV_UID_LENGTH - 1 - pos]; - } -} - -static int nfcv_revuidcmp(uint8_t* dst, uint8_t* src) { - for(int pos = 0; pos < NFCV_UID_LENGTH; pos++) { - if(dst[pos] != src[NFCV_UID_LENGTH - 1 - pos]) { - return 1; - } - } - return 0; -} - -void nfcv_emu_handle_packet( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data_in) { - furi_assert(tx_rx); - furi_assert(nfc_data); - furi_assert(nfcv_data_in); - - NfcVData* nfcv_data = (NfcVData*)nfcv_data_in; - NfcVEmuProtocolCtx* ctx = nfcv_data->emu_protocol_ctx; - - if(nfcv_data->frame_length < 2) { - return; - } - - if(nfcv_data->echo_mode) { - nfcv_emu_send( - tx_rx, - nfcv_data, - nfcv_data->frame, - nfcv_data->frame_length, - NfcVSendFlagsSof | NfcVSendFlagsHighRate | NfcVSendFlagsEof, - ctx->send_time); - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "ECHO data"); - return; - } - - /* parse the frame data for the upcoming part 3 handling */ - ctx->flags = nfcv_data->frame[0]; - ctx->command = nfcv_data->frame[1]; - ctx->selected = !(ctx->flags & NFCV_REQ_FLAG_INVENTORY) && (ctx->flags & NFCV_REQ_FLAG_SELECT); - ctx->addressed = !(ctx->flags & NFCV_REQ_FLAG_INVENTORY) && - (ctx->flags & NFCV_REQ_FLAG_ADDRESS); - ctx->advanced = (ctx->command >= NFCV_CMD_ADVANCED); - ctx->address_offset = 2 + (ctx->advanced ? 1 : 0); - ctx->payload_offset = ctx->address_offset + (ctx->addressed ? NFCV_UID_LENGTH : 0); - ctx->response_flags = NfcVSendFlagsSof | NfcVSendFlagsCrc | NfcVSendFlagsEof; - ctx->send_time = nfcv_data->eof_timestamp + NFCV_FDT_FC(4380); - - if(ctx->flags & NFCV_REQ_FLAG_DATA_RATE) { - ctx->response_flags |= NfcVSendFlagsHighRate; - } - if(ctx->flags & NFCV_REQ_FLAG_SUB_CARRIER) { - ctx->response_flags |= NfcVSendFlagsTwoSubcarrier; - } - - if(ctx->payload_offset + 2 > nfcv_data->frame_length) { -#ifdef NFCV_VERBOSE - FURI_LOG_D(TAG, "command 0x%02X, but packet is too short", ctx->command); -#endif - return; - } - - /* standard behavior is implemented */ - if(ctx->addressed) { - uint8_t* address = &nfcv_data->frame[ctx->address_offset]; - if(nfcv_revuidcmp(address, nfc_data->uid)) { -#ifdef NFCV_VERBOSE - FURI_LOG_D(TAG, "addressed command 0x%02X, but not for us:", ctx->command); - FURI_LOG_D( - TAG, - " dest: %02X%02X%02X%02X%02X%02X%02X%02X", - address[7], - address[6], - address[5], - address[4], - address[3], - address[2], - address[1], - address[0]); - FURI_LOG_D( - TAG, - " our UID: %02X%02X%02X%02X%02X%02X%02X%02X", - nfc_data->uid[0], - nfc_data->uid[1], - nfc_data->uid[2], - nfc_data->uid[3], - nfc_data->uid[4], - nfc_data->uid[5], - nfc_data->uid[6], - nfc_data->uid[7]); -#endif - return; - } - } - - if(ctx->selected && !nfcv_data->selected) { -#ifdef NFCV_VERBOSE - FURI_LOG_D( - TAG, - "selected card shall execute command 0x%02X, but we were not selected", - ctx->command); -#endif - return; - } - - /* then give control to the card subtype specific protocol filter */ - if(ctx->emu_protocol_filter != NULL) { - if(ctx->emu_protocol_filter(tx_rx, nfc_data, nfcv_data)) { - if(strlen(nfcv_data->last_command) > 0) { -#ifdef NFCV_VERBOSE - FURI_LOG_D( - TAG, "Received command %s (handled by filter)", nfcv_data->last_command); -#endif - } - return; - } - } - - switch(ctx->command) { - case NFCV_CMD_INVENTORY: { - bool respond = false; - - if(ctx->flags & NFCV_REQ_FLAG_AFI) { - uint8_t afi = nfcv_data->frame[ctx->payload_offset]; - - uint8_t family = (afi & 0xF0); - uint8_t subfamily = (afi & 0x0F); - - if(family) { - if(subfamily) { - /* selected family and subfamily only */ - if(afi == nfcv_data->afi) { - respond = true; - } - } else { - /* selected family, any subfamily */ - if(family == (nfcv_data->afi & 0xf0)) { - respond = true; - } - } - } else { - if(subfamily) { - /* proprietary subfamily only */ - if(afi == nfcv_data->afi) { - respond = true; - } - } else { - /* all families and subfamilies */ - respond = true; - } - } - - } else { - respond = true; - } - - if(!nfcv_data->quiet && respond) { - int buffer_pos = 0; - ctx->response_buffer[buffer_pos++] = NFCV_NOERROR; - ctx->response_buffer[buffer_pos++] = nfcv_data->dsfid; - nfcv_revuidcpy(&ctx->response_buffer[buffer_pos], nfc_data->uid); - buffer_pos += NFCV_UID_LENGTH; - - nfcv_emu_send( - tx_rx, - nfcv_data, - ctx->response_buffer, - buffer_pos, - ctx->response_flags, - ctx->send_time); - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "INVENTORY"); - } else { - snprintf( - nfcv_data->last_command, sizeof(nfcv_data->last_command), "INVENTORY (quiet)"); - } - break; - } - - case NFCV_CMD_STAY_QUIET: { - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "STAYQUIET"); - nfcv_data->quiet = true; - break; - } - - case NFCV_CMD_LOCK_BLOCK: { - uint8_t block = nfcv_data->frame[ctx->payload_offset]; - nfcv_data->security_status[block] |= 0x01; - nfcv_data->modified = true; - - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "LOCK BLOCK %d", block); - break; - } - - case NFCV_CMD_WRITE_DSFID: { - uint8_t id = nfcv_data->frame[ctx->payload_offset]; - - if(!(nfcv_data->security_status[0] & NfcVLockBitDsfid)) { - nfcv_data->dsfid = id; - nfcv_data->modified = true; - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - } - - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "WRITE DSFID %02X", id); - break; - } - - case NFCV_CMD_WRITE_AFI: { - uint8_t id = nfcv_data->frame[ctx->payload_offset]; - - if(!(nfcv_data->security_status[0] & NfcVLockBitAfi)) { - nfcv_data->afi = id; - nfcv_data->modified = true; - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - } - - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "WRITE AFI %02X", id); - break; - } - - case NFCV_CMD_LOCK_DSFID: { - if(!(nfcv_data->security_status[0] & NfcVLockBitDsfid)) { - nfcv_data->security_status[0] |= NfcVLockBitDsfid; - nfcv_data->modified = true; - - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - } - - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "LOCK DSFID"); - break; - } - - case NFCV_CMD_LOCK_AFI: { - if(!(nfcv_data->security_status[0] & NfcVLockBitAfi)) { - nfcv_data->security_status[0] |= NfcVLockBitAfi; - nfcv_data->modified = true; - - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - } - - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "LOCK AFI"); - break; - } - - case NFCV_CMD_SELECT: { - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_data->selected = true; - nfcv_data->quiet = false; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "SELECT"); - break; - } - - case NFCV_CMD_RESET_TO_READY: { - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_data->quiet = false; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "RESET_TO_READY"); - break; - } - - case NFCV_CMD_READ_MULTI_BLOCK: - case NFCV_CMD_READ_BLOCK: { - uint8_t block = nfcv_data->frame[ctx->payload_offset]; - int blocks = 1; - - if(ctx->command == NFCV_CMD_READ_MULTI_BLOCK) { - blocks = nfcv_data->frame[ctx->payload_offset + 1] + 1; - } - - /* limit the maximum block count, underflow accepted */ - if(block + blocks > nfcv_data->block_num) { - blocks = nfcv_data->block_num - block; - } - - /* only respond with the valid blocks, if there are any */ - if(blocks > 0) { - uint8_t buffer_pos = 0; - - ctx->response_buffer[buffer_pos++] = NFCV_NOERROR; - - for(int block_index = 0; block_index < blocks; block_index++) { - int block_current = block + block_index; - /* prepend security status */ - if(ctx->flags & NFCV_REQ_FLAG_OPTION) { - ctx->response_buffer[buffer_pos++] = - nfcv_data->security_status[1 + block_current]; - } - /* then the data block */ - memcpy( - &ctx->response_buffer[buffer_pos], - &nfcv_data->data[nfcv_data->block_size * block_current], - nfcv_data->block_size); - buffer_pos += nfcv_data->block_size; - } - nfcv_emu_send( - tx_rx, - nfcv_data, - ctx->response_buffer, - buffer_pos, - ctx->response_flags, - ctx->send_time); - } else { - /* reply with an error only in addressed or selected mode */ - if(ctx->addressed || ctx->selected) { - ctx->response_buffer[0] = NFCV_RES_FLAG_ERROR; - ctx->response_buffer[1] = NFCV_ERROR_GENERIC; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 2, ctx->response_flags, ctx->send_time); - } - } - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "READ BLOCK %d", block); - - break; - } - - case NFCV_CMD_WRITE_MULTI_BLOCK: - case NFCV_CMD_WRITE_BLOCK: { - uint8_t blocks = 1; - uint8_t block = nfcv_data->frame[ctx->payload_offset]; - uint8_t data_pos = ctx->payload_offset + 1; - - if(ctx->command == NFCV_CMD_WRITE_MULTI_BLOCK) { - blocks = nfcv_data->frame[data_pos] + 1; - data_pos++; - } - - uint8_t* data = &nfcv_data->frame[data_pos]; - uint32_t data_len = nfcv_data->block_size * blocks; - - if((block + blocks) <= nfcv_data->block_num && - (data_pos + data_len + 2) == nfcv_data->frame_length) { - ctx->response_buffer[0] = NFCV_NOERROR; - memcpy( - &nfcv_data->data[nfcv_data->block_size * block], - &nfcv_data->frame[data_pos], - data_len); - nfcv_data->modified = true; - - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - } else { - ctx->response_buffer[0] = NFCV_RES_FLAG_ERROR; - ctx->response_buffer[1] = NFCV_ERROR_GENERIC; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 2, ctx->response_flags, ctx->send_time); - } - - if(ctx->command == NFCV_CMD_WRITE_MULTI_BLOCK) { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "WRITE MULTI BLOCK %d, %d blocks", - block, - blocks); - } else { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "WRITE BLOCK %d <- %02X %02X %02X %02X", - block, - data[0], - data[1], - data[2], - data[3]); - } - break; - } - - case NFCV_CMD_GET_SYSTEM_INFO: { - int buffer_pos = 0; - ctx->response_buffer[buffer_pos++] = NFCV_NOERROR; - ctx->response_buffer[buffer_pos++] = NFCV_SYSINFO_FLAG_DSFID | NFCV_SYSINFO_FLAG_AFI | - NFCV_SYSINFO_FLAG_MEMSIZE | NFCV_SYSINFO_FLAG_ICREF; - nfcv_revuidcpy(&ctx->response_buffer[buffer_pos], nfc_data->uid); - buffer_pos += NFCV_UID_LENGTH; - ctx->response_buffer[buffer_pos++] = nfcv_data->dsfid; /* DSFID */ - ctx->response_buffer[buffer_pos++] = nfcv_data->afi; /* AFI */ - ctx->response_buffer[buffer_pos++] = nfcv_data->block_num - 1; /* number of blocks */ - ctx->response_buffer[buffer_pos++] = nfcv_data->block_size - 1; /* block size */ - ctx->response_buffer[buffer_pos++] = nfcv_data->ic_ref; /* IC reference */ - - nfcv_emu_send( - tx_rx, - nfcv_data, - ctx->response_buffer, - buffer_pos, - ctx->response_flags, - ctx->send_time); - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "SYSTEMINFO"); - break; - } - - case NFCV_CMD_CUST_ECHO_MODE: { - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_data->echo_mode = true; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "ECHO mode"); - break; - } - - case NFCV_CMD_CUST_ECHO_DATA: { - nfcv_emu_send( - tx_rx, - nfcv_data, - &nfcv_data->frame[ctx->payload_offset], - nfcv_data->frame_length - ctx->payload_offset - 2, - NfcVSendFlagsSof | NfcVSendFlagsHighRate | NfcVSendFlagsEof, - ctx->send_time); - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "ECHO data"); - break; - } - - default: - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "unsupported: %02X", - ctx->command); - break; - } - - if(strlen(nfcv_data->last_command) > 0) { -#ifdef NFCV_VERBOSE - FURI_LOG_D(TAG, "Received command %s", nfcv_data->last_command); -#endif - } -} - -void nfcv_emu_sniff_packet( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data_in) { - furi_assert(tx_rx); - furi_assert(nfc_data); - furi_assert(nfcv_data_in); - - NfcVData* nfcv_data = (NfcVData*)nfcv_data_in; - NfcVEmuProtocolCtx* ctx = nfcv_data->emu_protocol_ctx; - - if(nfcv_data->frame_length < 2) { - return; - } - - /* parse the frame data for the upcoming part 3 handling */ - ctx->flags = nfcv_data->frame[0]; - ctx->command = nfcv_data->frame[1]; - ctx->selected = (ctx->flags & NFCV_REQ_FLAG_SELECT); - ctx->addressed = !(ctx->flags & NFCV_REQ_FLAG_INVENTORY) && - (ctx->flags & NFCV_REQ_FLAG_ADDRESS); - ctx->advanced = (ctx->command >= NFCV_CMD_ADVANCED); - ctx->address_offset = 2 + (ctx->advanced ? 1 : 0); - ctx->payload_offset = ctx->address_offset + (ctx->addressed ? NFCV_UID_LENGTH : 0); - - char flags_string[5]; - - snprintf( - flags_string, - 5, - "%c%c%c%d", - (ctx->flags & NFCV_REQ_FLAG_INVENTORY) ? - 'I' : - (ctx->addressed ? 'A' : (ctx->selected ? 'S' : '*')), - ctx->advanced ? 'X' : ' ', - (ctx->flags & NFCV_REQ_FLAG_DATA_RATE) ? 'h' : 'l', - (ctx->flags & NFCV_REQ_FLAG_SUB_CARRIER) ? 2 : 1); - - switch(ctx->command) { - case NFCV_CMD_INVENTORY: { - snprintf( - nfcv_data->last_command, sizeof(nfcv_data->last_command), "%s INVENTORY", flags_string); - break; - } - - case NFCV_CMD_STAY_QUIET: { - snprintf( - nfcv_data->last_command, sizeof(nfcv_data->last_command), "%s STAYQUIET", flags_string); - nfcv_data->quiet = true; - break; - } - - case NFCV_CMD_LOCK_BLOCK: { - uint8_t block = nfcv_data->frame[ctx->payload_offset]; - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "%s LOCK %d", - flags_string, - block); - break; - } - - case NFCV_CMD_WRITE_DSFID: { - uint8_t id = nfcv_data->frame[ctx->payload_offset]; - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "%s WR DSFID %d", - flags_string, - id); - break; - } - - case NFCV_CMD_WRITE_AFI: { - uint8_t id = nfcv_data->frame[ctx->payload_offset]; - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "%s WR AFI %d", - flags_string, - id); - break; - } - - case NFCV_CMD_LOCK_DSFID: { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "%s LOCK DSFID", - flags_string); - break; - } - - case NFCV_CMD_LOCK_AFI: { - snprintf( - nfcv_data->last_command, sizeof(nfcv_data->last_command), "%s LOCK AFI", flags_string); - break; - } - - case NFCV_CMD_SELECT: { - snprintf( - nfcv_data->last_command, sizeof(nfcv_data->last_command), "%s SELECT", flags_string); - break; - } - - case NFCV_CMD_RESET_TO_READY: { - snprintf( - nfcv_data->last_command, sizeof(nfcv_data->last_command), "%s RESET", flags_string); - break; - } - - case NFCV_CMD_READ_MULTI_BLOCK: - case NFCV_CMD_READ_BLOCK: { - uint8_t block = nfcv_data->frame[ctx->payload_offset]; - uint8_t blocks = 1; - - if(ctx->command == NFCV_CMD_READ_MULTI_BLOCK) { - blocks = nfcv_data->frame[ctx->payload_offset + 1] + 1; - } - - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "%s READ %d cnt: %d", - flags_string, - block, - blocks); - - break; - } - - case NFCV_CMD_WRITE_MULTI_BLOCK: - case NFCV_CMD_WRITE_BLOCK: { - uint8_t block = nfcv_data->frame[ctx->payload_offset]; - uint8_t blocks = 1; - uint8_t data_pos = 1; - - if(ctx->command == NFCV_CMD_WRITE_MULTI_BLOCK) { - blocks = nfcv_data->frame[ctx->payload_offset + 1] + 1; - data_pos++; - } - - uint8_t* data = &nfcv_data->frame[ctx->payload_offset + data_pos]; - - if(ctx->command == NFCV_CMD_WRITE_MULTI_BLOCK) { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "%s WRITE %d, cnd %d", - flags_string, - block, - blocks); - } else { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "%s WRITE %d %02X %02X %02X %02X", - flags_string, - block, - data[0], - data[1], - data[2], - data[3]); - } - break; - } - - case NFCV_CMD_GET_SYSTEM_INFO: { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "%s SYSTEMINFO", - flags_string); - break; - } - - default: - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "%s unsupported: %02X", - flags_string, - ctx->command); - break; - } - - if(strlen(nfcv_data->last_command) > 0) { - FURI_LOG_D(TAG, "Received command %s", nfcv_data->last_command); - } -} - -void nfcv_emu_init(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data) { - furi_assert(nfc_data); - furi_assert(nfcv_data); - - if(!nfcv_emu_alloc(nfcv_data)) { - FURI_LOG_E(TAG, "Failed to allocate structures"); - nfcv_data->ready = false; - return; - } - - strcpy(nfcv_data->last_command, ""); - nfcv_data->quiet = false; - nfcv_data->selected = false; - nfcv_data->modified = false; - - /* everything is initialized */ - nfcv_data->ready = true; - - /* ensure the GPIO is already in unmodulated state */ - furi_hal_gpio_init(&gpio_spi_r_mosi, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); - furi_hal_gpio_write(&gpio_spi_r_mosi, GPIO_LEVEL_UNMODULATED); - - rfal_platform_spi_acquire(); - /* stop operation to configure for transparent and passive mode */ - st25r3916ExecuteCommand(ST25R3916_CMD_STOP); - /* set enable, rx_enable and field detector enable */ - st25r3916WriteRegister( - ST25R3916_REG_OP_CONTROL, - ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_rx_en | - ST25R3916_REG_OP_CONTROL_en_fd_auto_efd); - /* explicitely set the modulation resistor in case system config changes for some reason */ - st25r3916WriteRegister( - ST25R3916_REG_PT_MOD, - (0 << ST25R3916_REG_PT_MOD_ptm_res_shift) | (15 << ST25R3916_REG_PT_MOD_pt_res_shift)); - /* target mode: target, other fields do not have any effect as we use transparent mode */ - st25r3916WriteRegister(ST25R3916_REG_MODE, ST25R3916_REG_MODE_targ); - /* let us modulate the field using MOSI, read ASK modulation using IRQ */ - st25r3916ExecuteCommand(ST25R3916_CMD_TRANSPARENT_MODE); - - furi_hal_spi_bus_handle_deinit(&furi_hal_spi_bus_handle_nfc); - - /* if not set already, initialize the default protocol handler */ - if(!nfcv_data->emu_protocol_ctx) { - nfcv_data->emu_protocol_ctx = malloc(sizeof(NfcVEmuProtocolCtx)); - if(nfcv_data->sub_type == NfcVTypeSniff) { - nfcv_data->emu_protocol_handler = &nfcv_emu_sniff_packet; - } else { - nfcv_data->emu_protocol_handler = &nfcv_emu_handle_packet; - } - } - - FURI_LOG_D(TAG, "Starting NfcV emulation"); - FURI_LOG_D( - TAG, - " UID: %02X %02X %02X %02X %02X %02X %02X %02X", - nfc_data->uid[0], - nfc_data->uid[1], - nfc_data->uid[2], - nfc_data->uid[3], - nfc_data->uid[4], - nfc_data->uid[5], - nfc_data->uid[6], - nfc_data->uid[7]); - - switch(nfcv_data->sub_type) { - case NfcVTypeSlixL: - FURI_LOG_D(TAG, " Card type: SLIX-L"); - slix_l_prepare(nfcv_data); - break; - case NfcVTypeSlixS: - FURI_LOG_D(TAG, " Card type: SLIX-S"); - slix_s_prepare(nfcv_data); - break; - case NfcVTypeSlix2: - FURI_LOG_D(TAG, " Card type: SLIX2"); - slix2_prepare(nfcv_data); - break; - case NfcVTypeSlix: - FURI_LOG_D(TAG, " Card type: SLIX"); - slix_prepare(nfcv_data); - break; - case NfcVTypePlain: - FURI_LOG_D(TAG, " Card type: Plain"); - break; - case NfcVTypeSniff: - FURI_LOG_D(TAG, " Card type: Sniffing"); - break; - } - - /* allocate a 512 edge buffer, more than enough */ - nfcv_data->emu_air.reader_signal = - pulse_reader_alloc(&gpio_nfc_irq_rfid_pull, NFCV_PULSE_BUFFER); - /* timebase shall be 1 ns */ - pulse_reader_set_timebase(nfcv_data->emu_air.reader_signal, PulseReaderUnitNanosecond); - /* and configure to already calculate the number of bits */ - pulse_reader_set_bittime(nfcv_data->emu_air.reader_signal, NFCV_PULSE_DURATION_NS); - /* this IO is fed into the µC via a diode, so we need a pulldown */ - pulse_reader_set_pull(nfcv_data->emu_air.reader_signal, GpioPullDown); - - /* start sampling */ - pulse_reader_start(nfcv_data->emu_air.reader_signal); -} - -void nfcv_emu_deinit(NfcVData* nfcv_data) { - furi_assert(nfcv_data); - - furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_nfc); - nfcv_emu_free(nfcv_data); - - if(nfcv_data->emu_protocol_ctx) { - free(nfcv_data->emu_protocol_ctx); - nfcv_data->emu_protocol_ctx = NULL; - } - - /* set registers back to how we found them */ - st25r3916WriteRegister(ST25R3916_REG_OP_CONTROL, 0x00); - st25r3916WriteRegister(ST25R3916_REG_MODE, 0x08); - rfal_platform_spi_release(); -} - -bool nfcv_emu_loop( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - NfcVData* nfcv_data, - uint32_t timeout_ms) { - furi_assert(tx_rx); - furi_assert(nfc_data); - furi_assert(nfcv_data); - - bool ret = false; - uint32_t frame_state = NFCV_FRAME_STATE_SOF1; - uint32_t periods_previous = 0; - uint32_t frame_pos = 0; - uint32_t byte_value = 0; - uint32_t bits_received = 0; - uint32_t timeout = timeout_ms * 1000; - bool wait_for_pulse = false; - - if(!nfcv_data->ready) { - return false; - } - -#ifdef NFCV_DIAGNOSTIC_DUMPS - uint8_t period_buffer[NFCV_DIAGNOSTIC_DUMP_SIZE]; - uint32_t period_buffer_pos = 0; -#endif - - while(true) { - uint32_t periods = pulse_reader_receive(nfcv_data->emu_air.reader_signal, timeout); - uint32_t timestamp = DWT->CYCCNT; - - /* when timed out, reset to SOF state */ - if(periods == PULSE_READER_NO_EDGE || periods == PULSE_READER_LOST_EDGE) { - break; - } - -#ifdef NFCV_DIAGNOSTIC_DUMPS - if(period_buffer_pos < sizeof(period_buffer)) { - period_buffer[period_buffer_pos++] = periods; - } -#endif - - /* short helper for detecting a pulse position */ - if(wait_for_pulse) { - wait_for_pulse = false; - if(periods != 1) { - frame_state = NFCV_FRAME_STATE_RESET; - } - continue; - } - - switch(frame_state) { - case NFCV_FRAME_STATE_SOF1: - if(periods == 1) { - frame_state = NFCV_FRAME_STATE_SOF2; - } else { - frame_state = NFCV_FRAME_STATE_SOF1; - break; - } - break; - - case NFCV_FRAME_STATE_SOF2: - /* waiting for the second low period, telling us about coding */ - if(periods == 6) { - frame_state = NFCV_FRAME_STATE_CODING_256; - periods_previous = 0; - wait_for_pulse = true; - } else if(periods == 4) { - frame_state = NFCV_FRAME_STATE_CODING_4; - periods_previous = 2; - wait_for_pulse = true; - } else { - frame_state = NFCV_FRAME_STATE_RESET; - } - break; - - case NFCV_FRAME_STATE_CODING_256: - if(periods_previous > periods) { - frame_state = NFCV_FRAME_STATE_RESET; - break; - } - - /* previous symbol left us with some pulse periods */ - periods -= periods_previous; - - if(periods > 512) { - frame_state = NFCV_FRAME_STATE_RESET; - break; - } else if(periods == 2) { - frame_state = NFCV_FRAME_STATE_EOF; - break; - } - - periods_previous = 512 - (periods + 1); - byte_value = (periods - 1) / 2; - if(frame_pos < NFCV_FRAMESIZE_MAX) { - nfcv_data->frame[frame_pos++] = (uint8_t)byte_value; - } - - wait_for_pulse = true; - - break; - - case NFCV_FRAME_STATE_CODING_4: - if(periods_previous > periods) { - frame_state = NFCV_FRAME_STATE_RESET; - break; - } - - /* previous symbol left us with some pulse periods */ - periods -= periods_previous; - periods_previous = 0; - - byte_value >>= 2; - bits_received += 2; - - if(periods == 1) { - byte_value |= 0x00 << 6; // -V684 - periods_previous = 6; - } else if(periods == 3) { - byte_value |= 0x01 << 6; - periods_previous = 4; - } else if(periods == 5) { - byte_value |= 0x02 << 6; - periods_previous = 2; - } else if(periods == 7) { - byte_value |= 0x03 << 6; - periods_previous = 0; - } else if(periods == 2) { - frame_state = NFCV_FRAME_STATE_EOF; - break; - } else { - frame_state = NFCV_FRAME_STATE_RESET; - break; - } - - if(bits_received >= 8) { - if(frame_pos < NFCV_FRAMESIZE_MAX) { - nfcv_data->frame[frame_pos++] = (uint8_t)byte_value; - } - bits_received = 0; - } - wait_for_pulse = true; - break; - } - - /* post-state-machine cleanup and reset */ - if(frame_state == NFCV_FRAME_STATE_RESET) { - frame_state = NFCV_FRAME_STATE_SOF1; - } else if(frame_state == NFCV_FRAME_STATE_EOF) { - nfcv_data->frame_length = frame_pos; - nfcv_data->eof_timestamp = timestamp; - break; - } - } - - if(frame_state == NFCV_FRAME_STATE_EOF) { - /* we know that this code uses TIM2, so stop pulse reader */ - pulse_reader_stop(nfcv_data->emu_air.reader_signal); - if(tx_rx->sniff_rx) { - tx_rx->sniff_rx(nfcv_data->frame, frame_pos * 8, false, tx_rx->sniff_context); - } - nfcv_data->emu_protocol_handler(tx_rx, nfc_data, nfcv_data); - - pulse_reader_start(nfcv_data->emu_air.reader_signal); - ret = true; - - } -#ifdef NFCV_VERBOSE - else { - if(frame_state != NFCV_FRAME_STATE_SOF1) { - FURI_LOG_T(TAG, "leaving while in state: %lu", frame_state); - } - } -#endif - -#ifdef NFCV_DIAGNOSTIC_DUMPS - if(period_buffer_pos) { - FURI_LOG_T(TAG, "pulses:"); - for(uint32_t pos = 0; pos < period_buffer_pos; pos++) { - FURI_LOG_T(TAG, " #%lu: %u", pos, period_buffer[pos]); - } - } -#endif - - return ret; -} diff --git a/lib/nfc/protocols/nfcv.h b/lib/nfc/protocols/nfcv.h deleted file mode 100644 index e4139de99..000000000 --- a/lib/nfc/protocols/nfcv.h +++ /dev/null @@ -1,334 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include "nfc_util.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* true: modulating releases load, false: modulating adds load resistor to field coil */ -#define NFCV_LOAD_MODULATION_POLARITY (false) - -#define NFCV_FC (13560000.0f) /* MHz */ -#define NFCV_RESP_SUBC1_PULSE_32 (1.0f / (NFCV_FC / 32) / 2.0f) /* 1.1799 µs */ -#define NFCV_RESP_SUBC1_UNMOD_256 (256.0f / NFCV_FC) /* 18.8791 µs */ -#define NFCV_PULSE_DURATION_NS (128.0f * 1000000000.0f / NFCV_FC) - -/* ISO/IEC 15693-3:2019(E) 10.4.12: maximum number of blocks is defined as 256 */ -#define NFCV_BLOCKS_MAX 256 -/* ISO/IEC 15693-3:2019(E) 10.4.12: maximum size of blocks is defined as 32 */ -#define NFCV_BLOCKSIZE_MAX 32 -/* the resulting memory size a card can have */ -#define NFCV_MEMSIZE_MAX (NFCV_BLOCKS_MAX * NFCV_BLOCKSIZE_MAX) -/* ISO/IEC 15693-3:2019(E) 7.1b: standard allows up to 8192, the maxium frame length that we are expected to receive/send is less */ -#define NFCV_FRAMESIZE_MAX (1 + NFCV_MEMSIZE_MAX + NFCV_BLOCKS_MAX) - -/* maximum string length for log messages */ -#define NFCV_LOG_STR_LEN 128 -/* maximum of pulses to be buffered by pulse reader */ -#define NFCV_PULSE_BUFFER 512 - -//#define NFCV_DIAGNOSTIC_DUMPS -//#define NFCV_DIAGNOSTIC_DUMP_SIZE 256 -//#define NFCV_VERBOSE - -/* helpers to calculate the send time based on DWT->CYCCNT */ -#define NFCV_FDT_USEC(usec) ((usec)*64) -#define NFCV_FDT_FC(ticks) ((ticks)*6400 / 1356) - -/* state machine when receiving frame bits */ -#define NFCV_FRAME_STATE_SOF1 0 -#define NFCV_FRAME_STATE_SOF2 1 -#define NFCV_FRAME_STATE_CODING_4 2 -#define NFCV_FRAME_STATE_CODING_256 3 -#define NFCV_FRAME_STATE_EOF 4 -#define NFCV_FRAME_STATE_RESET 5 - -/* sequences for every section of a frame */ -#define NFCV_SIG_SOF 0 -#define NFCV_SIG_BIT0 1 -#define NFCV_SIG_BIT1 2 -#define NFCV_SIG_EOF 3 -#define NFCV_SIG_LOW_SOF 4 -#define NFCV_SIG_LOW_BIT0 5 -#define NFCV_SIG_LOW_BIT1 6 -#define NFCV_SIG_LOW_EOF 7 - -/* various constants */ -#define NFCV_COMMAND_RETRIES 5 -#define NFCV_UID_LENGTH 8 - -/* ISO15693 protocol flags */ -typedef enum { - /* ISO15693 protocol flags when INVENTORY is NOT set */ - NFCV_REQ_FLAG_SUB_CARRIER = (1 << 0), - NFCV_REQ_FLAG_DATA_RATE = (1 << 1), - NFCV_REQ_FLAG_INVENTORY = (1 << 2), - NFCV_REQ_FLAG_PROTOCOL_EXT = (1 << 3), - NFCV_REQ_FLAG_SELECT = (1 << 4), - NFCV_REQ_FLAG_ADDRESS = (1 << 5), - NFCV_REQ_FLAG_OPTION = (1 << 6), - /* ISO15693 protocol flags when INVENTORY flag is set */ - NFCV_REQ_FLAG_AFI = (1 << 4), - NFCV_REQ_FLAG_NB_SLOTS = (1 << 5) -} NfcVRequestFlags; - -/* ISO15693 protocol flags */ -typedef enum { - NFCV_RES_FLAG_ERROR = (1 << 0), - NFCV_RES_FLAG_VALIDITY = (1 << 1), - NFCV_RES_FLAG_FINAL = (1 << 2), - NFCV_RES_FLAG_PROTOCOL_EXT = (1 << 3), - NFCV_RES_FLAG_SEC_LEN1 = (1 << 4), - NFCV_RES_FLAG_SEC_LEN2 = (1 << 5), - NFCV_RES_FLAG_WAIT_EXT = (1 << 6), -} NfcVRsponseFlags; - -/* flags for SYSINFO response */ -typedef enum { - NFCV_SYSINFO_FLAG_DSFID = (1 << 0), - NFCV_SYSINFO_FLAG_AFI = (1 << 1), - NFCV_SYSINFO_FLAG_MEMSIZE = (1 << 2), - NFCV_SYSINFO_FLAG_ICREF = (1 << 3) -} NfcVSysinfoFlags; - -/* ISO15693 command codes */ -typedef enum { - /* mandatory command codes */ - NFCV_CMD_INVENTORY = 0x01, - NFCV_CMD_STAY_QUIET = 0x02, - /* optional command codes */ - NFCV_CMD_READ_BLOCK = 0x20, - NFCV_CMD_WRITE_BLOCK = 0x21, - NFCV_CMD_LOCK_BLOCK = 0x22, - NFCV_CMD_READ_MULTI_BLOCK = 0x23, - NFCV_CMD_WRITE_MULTI_BLOCK = 0x24, - NFCV_CMD_SELECT = 0x25, - NFCV_CMD_RESET_TO_READY = 0x26, - NFCV_CMD_WRITE_AFI = 0x27, - NFCV_CMD_LOCK_AFI = 0x28, - NFCV_CMD_WRITE_DSFID = 0x29, - NFCV_CMD_LOCK_DSFID = 0x2A, - NFCV_CMD_GET_SYSTEM_INFO = 0x2B, - NFCV_CMD_READ_MULTI_SECSTATUS = 0x2C, - /* advanced command codes */ - NFCV_CMD_ADVANCED = 0xA0, - /* flipper zero custom command codes */ - NFCV_CMD_CUST_ECHO_MODE = 0xDE, - NFCV_CMD_CUST_ECHO_DATA = 0xDF -} NfcVCommands; - -/* ISO15693 Response error codes */ -typedef enum { - NFCV_NOERROR = 0x00, - NFCV_ERROR_CMD_NOT_SUP = 0x01, // Command not supported - NFCV_ERROR_CMD_NOT_REC = 0x02, // Command not recognized (eg. parameter error) - NFCV_ERROR_CMD_OPTION = 0x03, // Command option not supported - NFCV_ERROR_GENERIC = 0x0F, // No additional Info about this error - NFCV_ERROR_BLOCK_UNAVAILABLE = 0x10, - NFCV_ERROR_BLOCK_LOCKED_ALREADY = 0x11, // cannot lock again - NFCV_ERROR_BLOCK_LOCKED = 0x12, // cannot be changed - NFCV_ERROR_BLOCK_WRITE = 0x13, // Writing was unsuccessful - NFCV_ERROR_BLOCL_WRITELOCK = 0x14 // Locking was unsuccessful -} NfcVErrorcodes; - -typedef enum { - NfcVLockBitDsfid = 1 << 0, - NfcVLockBitAfi = 1 << 1, - NfcVLockBitEas = 1 << 2, - NfcVLockBitPpl = 1 << 3, -} NfcVLockBits; - -typedef enum { - NfcVAuthMethodManual, - NfcVAuthMethodTonieBox, -} NfcVAuthMethod; - -typedef enum { - NfcVTypePlain = 0, - NfcVTypeSlix = 1, - NfcVTypeSlixS = 2, - NfcVTypeSlixL = 3, - NfcVTypeSlix2 = 4, - NfcVTypeSniff = 255, -} NfcVSubtype; - -typedef enum { - NfcVSendFlagsNormal = 0, - NfcVSendFlagsSof = 1 << 0, - NfcVSendFlagsCrc = 1 << 1, - NfcVSendFlagsEof = 1 << 2, - NfcVSendFlagsOneSubcarrier = 0, - NfcVSendFlagsTwoSubcarrier = 1 << 3, - NfcVSendFlagsLowRate = 0, - NfcVSendFlagsHighRate = 1 << 4 -} NfcVSendFlags; - -/* SLIX specific config flags */ -typedef enum { - NfcVSlixDataFlagsNone = 0, - NfcVSlixDataFlagsHasKeyRead = 1 << 0, - NfcVSlixDataFlagsHasKeyWrite = 1 << 1, - NfcVSlixDataFlagsHasKeyPrivacy = 1 << 2, - NfcVSlixDataFlagsHasKeyDestroy = 1 << 3, - NfcVSlixDataFlagsHasKeyEas = 1 << 4, - NfcVSlixDataFlagsValidKeyRead = 1 << 8, - NfcVSlixDataFlagsValidKeyWrite = 1 << 9, - NfcVSlixDataFlagsValidKeyPrivacy = 1 << 10, - NfcVSlixDataFlagsValidKeyDestroy = 1 << 11, - NfcVSlixDataFlagsValidKeyEas = 1 << 12, - NfcVSlixDataFlagsPrivacy = 1 << 16, - NfcVSlixDataFlagsDestroyed = 1 << 17 -} NfcVSlixDataFlags; - -/* abstract the file read/write operations for all SLIX types to reduce duplicated code */ -typedef enum { - SlixFeatureRead = 1 << 0, - SlixFeatureWrite = 1 << 1, - SlixFeaturePrivacy = 1 << 2, - SlixFeatureDestroy = 1 << 3, - SlixFeatureEas = 1 << 4, - SlixFeatureSignature = 1 << 5, - SlixFeatureProtection = 1 << 6, - - SlixFeatureSlix = SlixFeatureEas, - SlixFeatureSlixS = - (SlixFeatureRead | SlixFeatureWrite | SlixFeaturePrivacy | SlixFeatureDestroy | - SlixFeatureEas), - SlixFeatureSlixL = (SlixFeaturePrivacy | SlixFeatureDestroy | SlixFeatureEas), - SlixFeatureSlix2 = - (SlixFeatureRead | SlixFeatureWrite | SlixFeaturePrivacy | SlixFeatureDestroy | - SlixFeatureEas | SlixFeatureSignature | SlixFeatureProtection), -} SlixTypeFeatures; - -typedef struct { - uint32_t flags; - uint8_t key_read[4]; - uint8_t key_write[4]; - uint8_t key_privacy[4]; - uint8_t key_destroy[4]; - uint8_t key_eas[4]; - uint8_t rand[2]; - uint8_t signature[32]; - /* SLIX2 options */ - uint8_t pp_pointer; - uint8_t pp_condition; -} NfcVSlixData; - -typedef union { - NfcVSlixData slix; -} NfcVSubtypeData; - -typedef struct { - DigitalSignal* nfcv_resp_sof; - DigitalSignal* nfcv_resp_one; - DigitalSignal* nfcv_resp_zero; - DigitalSignal* nfcv_resp_eof; -} NfcVEmuAirSignals; - -typedef struct { - PulseReader* reader_signal; - DigitalSignal* nfcv_resp_pulse; /* pulse length, fc/32 */ - DigitalSignal* nfcv_resp_half_pulse; /* half pulse length, fc/32 */ - DigitalSignal* nfcv_resp_unmod; /* unmodulated length 256/fc */ - NfcVEmuAirSignals signals_high; - NfcVEmuAirSignals signals_low; - DigitalSequence* nfcv_signal; -} NfcVEmuAir; - -typedef void (*NfcVEmuProtocolHandler)( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data); -typedef bool (*NfcVEmuProtocolFilter)( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data); - -/* the default ISO15693 handler context */ -typedef struct { - uint8_t flags; /* ISO15693-3 flags of the header as specified */ - uint8_t command; /* ISO15693-3 command at offset 1 as specified */ - bool selected; /* ISO15693-3 flags: selected frame */ - bool addressed; /* ISO15693-3 flags: addressed frame */ - bool advanced; /* ISO15693-3 command: advanced command */ - uint8_t address_offset; /* ISO15693-3 offset of the address in frame, if addressed is set */ - uint8_t payload_offset; /* ISO15693-3 offset of the payload in frame */ - - uint8_t response_buffer[NFCV_FRAMESIZE_MAX]; /* pre-allocated response buffer */ - NfcVSendFlags response_flags; /* flags to use when sending response */ - uint32_t send_time; /* timestamp when to send the response */ - - NfcVEmuProtocolFilter emu_protocol_filter; -} NfcVEmuProtocolCtx; - -typedef struct { - /* common ISO15693 fields, being specified in ISO15693-3 */ - uint8_t dsfid; - uint8_t afi; - uint8_t ic_ref; - uint16_t block_num; - uint8_t block_size; - uint8_t data[NFCV_MEMSIZE_MAX]; - uint8_t security_status[1 + NFCV_BLOCKS_MAX]; - bool selected; - bool quiet; - - bool modified; - bool ready; - bool echo_mode; - - /* specfic variant infos */ - NfcVSubtype sub_type; - NfcVSubtypeData sub_data; - NfcVAuthMethod auth_method; - - /* precalced air level data */ - NfcVEmuAir emu_air; - - uint8_t* frame; /* [NFCV_FRAMESIZE_MAX] ISO15693-2 incoming raw data from air layer */ - uint8_t frame_length; /* ISO15693-2 length of incoming data */ - uint32_t eof_timestamp; /* ISO15693-2 EOF timestamp, read from DWT->CYCCNT */ - - /* handler for the protocol layer as specified in ISO15693-3 */ - NfcVEmuProtocolHandler emu_protocol_handler; - void* emu_protocol_ctx; - /* runtime data */ - char last_command[NFCV_LOG_STR_LEN]; - char error[NFCV_LOG_STR_LEN]; -} NfcVData; - -typedef struct { - uint16_t blocks_to_read; - int16_t blocks_read; -} NfcVReader; - -ReturnCode nfcv_read_blocks(NfcVReader* reader, NfcVData* data); -ReturnCode nfcv_read_sysinfo(FuriHalNfcDevData* nfc_data, NfcVData* data); -ReturnCode nfcv_inventory(uint8_t* uid); -bool nfcv_read_card(NfcVReader* reader, FuriHalNfcDevData* nfc_data, NfcVData* data); - -void nfcv_emu_init(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data); -void nfcv_emu_deinit(NfcVData* nfcv_data); -bool nfcv_emu_loop( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - NfcVData* nfcv_data, - uint32_t timeout_ms); -void nfcv_emu_send( - FuriHalNfcTxRxContext* tx_rx, - NfcVData* nfcv, - uint8_t* data, - uint8_t length, - NfcVSendFlags flags, - uint32_t send_time); - -#ifdef __cplusplus -} -#endif diff --git a/lib/nfc/protocols/slix.c b/lib/nfc/protocols/slix.c deleted file mode 100644 index 4b15f4b97..000000000 --- a/lib/nfc/protocols/slix.c +++ /dev/null @@ -1,784 +0,0 @@ - -#include -#include "nfcv.h" -#include "slix.h" -#include "nfc_util.h" -#include -#include "furi_hal_nfc.h" -#include - -#define TAG "Slix" - -ReturnCode slix2_read_nxp_sysinfo(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data) { - furi_assert(nfc_data); - furi_assert(nfcv_data); - - uint8_t rxBuf[32]; - uint16_t received = 0; - ReturnCode ret = ERR_NONE; - - FURI_LOG_D(TAG, "Read NXP SYSTEM INFORMATION..."); - - for(int tries = 0; tries < NFCV_COMMAND_RETRIES; tries++) { - uint8_t cmd[] = {}; - uint8_t uid[NFCV_UID_LENGTH]; - - /* UID is stored reversed in requests */ - for(int pos = 0; pos < nfc_data->uid_len; pos++) { - uid[pos] = nfc_data->uid[nfc_data->uid_len - 1 - pos]; - } - - ReturnCode ret = rfalNfcvPollerTransceiveReq( - NFCV_CMD_NXP_GET_NXP_SYSTEM_INFORMATION, - RFAL_NFCV_REQ_FLAG_DEFAULT, - NFCV_MANUFACTURER_NXP, - uid, - cmd, - sizeof(cmd), - rxBuf, - sizeof(rxBuf), - &received); - - if(ret == ERR_NONE) { - break; - } - } - - if(ret != ERR_NONE || received != 8) { //-V560 - FURI_LOG_D(TAG, "Failed: %d, %d", ret, received); - return ret; - } - FURI_LOG_D(TAG, "Success..."); - - NfcVSlixData* slix = &nfcv_data->sub_data.slix; - slix->pp_pointer = rxBuf[1]; - slix->pp_condition = rxBuf[2]; - - /* convert NXP's to our internal lock bits format */ - nfcv_data->security_status[0] = 0; - nfcv_data->security_status[0] |= (rxBuf[3] & SlixLockBitDsfid) ? NfcVLockBitDsfid : 0; - nfcv_data->security_status[0] |= (rxBuf[3] & SlixLockBitAfi) ? NfcVLockBitAfi : 0; - nfcv_data->security_status[0] |= (rxBuf[3] & SlixLockBitEas) ? NfcVLockBitEas : 0; - nfcv_data->security_status[0] |= (rxBuf[3] & SlixLockBitPpl) ? NfcVLockBitPpl : 0; - - return ERR_NONE; -} - -ReturnCode slix2_read_signature(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data) { - furi_assert(nfc_data); - furi_assert(nfcv_data); - - uint8_t rxBuf[64]; - uint16_t received = 0; - ReturnCode ret = ERR_NONE; - - FURI_LOG_D(TAG, "Read SIGNATURE..."); - - for(int tries = 0; tries < NFCV_COMMAND_RETRIES; tries++) { - uint8_t cmd[] = {}; - uint8_t uid[NFCV_UID_LENGTH]; - - /* UID is stored reversed in requests */ - for(int pos = 0; pos < nfc_data->uid_len; pos++) { - uid[pos] = nfc_data->uid[nfc_data->uid_len - 1 - pos]; - } - - ReturnCode ret = rfalNfcvPollerTransceiveReq( - NFCV_CMD_NXP_READ_SIGNATURE, - RFAL_NFCV_REQ_FLAG_DEFAULT, - NFCV_MANUFACTURER_NXP, - uid, - cmd, - sizeof(cmd), - rxBuf, - sizeof(rxBuf), - &received); - - if(ret == ERR_NONE) { - break; - } - } - - if(ret != ERR_NONE || received != 33) { //-V560 - FURI_LOG_D(TAG, "Failed: %d, %d", ret, received); - return ret; - } - FURI_LOG_D(TAG, "Success..."); - - NfcVSlixData* slix = &nfcv_data->sub_data.slix; - memcpy(slix->signature, &rxBuf[1], 32); - - return ERR_NONE; -} - -ReturnCode slix2_read_custom(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data) { - ReturnCode ret = ERR_NONE; - - ret = slix2_read_nxp_sysinfo(nfc_data, nfcv_data); - if(ret != ERR_NONE) { - return ret; - } - ret = slix2_read_signature(nfc_data, nfcv_data); - - return ret; -} - -static uint32_t slix_read_be(uint8_t* data, uint32_t length) { - uint32_t value = 0; - - for(uint32_t pos = 0; pos < length; pos++) { - value <<= 8; - value |= data[pos]; - } - - return value; -} - -uint8_t slix_get_ti(FuriHalNfcDevData* nfc_data) { - return (nfc_data->uid[3] >> 3) & 3; -} - -bool slix_check_card_type(FuriHalNfcDevData* nfc_data) { - if((nfc_data->uid[0] == 0xE0) && (nfc_data->uid[1] == 0x04) && (nfc_data->uid[2] == 0x01) && - slix_get_ti(nfc_data) == 2) { - return true; - } - return false; -} - -bool slix2_check_card_type(FuriHalNfcDevData* nfc_data) { - if((nfc_data->uid[0] == 0xE0) && (nfc_data->uid[1] == 0x04) && (nfc_data->uid[2] == 0x01) && - slix_get_ti(nfc_data) == 1) { - return true; - } - return false; -} - -bool slix_s_check_card_type(FuriHalNfcDevData* nfc_data) { - if((nfc_data->uid[0] == 0xE0) && (nfc_data->uid[1] == 0x04) && (nfc_data->uid[2] == 0x02)) { - return true; - } - return false; -} - -bool slix_l_check_card_type(FuriHalNfcDevData* nfc_data) { - if((nfc_data->uid[0] == 0xE0) && (nfc_data->uid[1] == 0x04) && (nfc_data->uid[2] == 0x03)) { - return true; - } - return false; -} - -ReturnCode slix_get_random(NfcVData* data) { - uint16_t received = 0; - uint8_t rxBuf[32]; - - ReturnCode ret = rfalNfcvPollerTransceiveReq( - NFCV_CMD_NXP_GET_RANDOM_NUMBER, - RFAL_NFCV_REQ_FLAG_DEFAULT, - NFCV_MANUFACTURER_NXP, - NULL, - NULL, - 0, - rxBuf, - sizeof(rxBuf), - &received); - - if(ret == ERR_NONE) { - if(received != 3) { - return ERR_PROTO; - } - if(data != NULL) { - data->sub_data.slix.rand[0] = rxBuf[2]; - data->sub_data.slix.rand[1] = rxBuf[1]; - } - } - - return ret; -} - -ReturnCode slix_unlock(NfcVData* data, uint32_t password_id) { - furi_assert(data); - - uint16_t received = 0; - uint8_t rxBuf[32]; - uint8_t cmd_set_pass[] = { - password_id, - data->sub_data.slix.rand[1], - data->sub_data.slix.rand[0], - data->sub_data.slix.rand[1], - data->sub_data.slix.rand[0]}; - uint8_t* password = NULL; - - switch(password_id) { - case SLIX_PASS_READ: - password = data->sub_data.slix.key_read; - break; - case SLIX_PASS_WRITE: - password = data->sub_data.slix.key_write; - break; - case SLIX_PASS_PRIVACY: - password = data->sub_data.slix.key_privacy; - break; - case SLIX_PASS_DESTROY: - password = data->sub_data.slix.key_destroy; - break; - case SLIX_PASS_EASAFI: - password = data->sub_data.slix.key_eas; - break; - default: - break; - } - - if(!password) { - return ERR_NOTSUPP; - } - - for(int pos = 0; pos < 4; pos++) { - cmd_set_pass[1 + pos] ^= password[3 - pos]; - } - - ReturnCode ret = rfalNfcvPollerTransceiveReq( - NFCV_CMD_NXP_SET_PASSWORD, - RFAL_NFCV_REQ_FLAG_DATA_RATE, - NFCV_MANUFACTURER_NXP, - NULL, - cmd_set_pass, - sizeof(cmd_set_pass), - rxBuf, - sizeof(rxBuf), - &received); - - return ret; -} - -static void slix_generic_pass_infos( - uint8_t password_id, - NfcVSlixData* slix, - uint8_t** password, - uint32_t* flag_valid, - uint32_t* flag_set) { - switch(password_id) { - case SLIX_PASS_READ: - *password = slix->key_read; - *flag_valid = NfcVSlixDataFlagsValidKeyRead; - *flag_set = NfcVSlixDataFlagsHasKeyRead; - break; - case SLIX_PASS_WRITE: - *password = slix->key_write; - *flag_valid = NfcVSlixDataFlagsValidKeyWrite; - *flag_set = NfcVSlixDataFlagsHasKeyWrite; - break; - case SLIX_PASS_PRIVACY: - *password = slix->key_privacy; - *flag_valid = NfcVSlixDataFlagsValidKeyPrivacy; - *flag_set = NfcVSlixDataFlagsHasKeyPrivacy; - break; - case SLIX_PASS_DESTROY: - *password = slix->key_destroy; - *flag_valid = NfcVSlixDataFlagsValidKeyDestroy; - *flag_set = NfcVSlixDataFlagsHasKeyDestroy; - break; - case SLIX_PASS_EASAFI: - *password = slix->key_eas; - *flag_valid = NfcVSlixDataFlagsValidKeyEas; - *flag_set = NfcVSlixDataFlagsHasKeyEas; - break; - default: - break; - } -} - -bool slix_generic_protocol_filter( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data_in, - uint32_t password_supported) { - furi_assert(tx_rx); - furi_assert(nfc_data); - furi_assert(nfcv_data_in); - - NfcVData* nfcv_data = (NfcVData*)nfcv_data_in; - NfcVEmuProtocolCtx* ctx = nfcv_data->emu_protocol_ctx; - NfcVSlixData* slix = &nfcv_data->sub_data.slix; - - if((slix->flags & NfcVSlixDataFlagsPrivacy) && - ctx->command != NFCV_CMD_NXP_GET_RANDOM_NUMBER && - ctx->command != NFCV_CMD_NXP_SET_PASSWORD) { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "command 0x%02X ignored, privacy mode", - ctx->command); - FURI_LOG_D(TAG, "%s", nfcv_data->last_command); - return true; - } - - bool handled = false; - - switch(ctx->command) { - case NFCV_CMD_NXP_GET_RANDOM_NUMBER: { - slix->rand[0] = furi_hal_random_get(); - slix->rand[1] = furi_hal_random_get(); - - ctx->response_buffer[0] = NFCV_NOERROR; - ctx->response_buffer[1] = slix->rand[1]; - ctx->response_buffer[2] = slix->rand[0]; - - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 3, ctx->response_flags, ctx->send_time); - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "GET_RANDOM_NUMBER -> 0x%02X%02X", - slix->rand[0], - slix->rand[1]); - - handled = true; - break; - } - - case NFCV_CMD_NXP_SET_PASSWORD: { - /* the password to be set is the first parameter */ - uint8_t password_id = nfcv_data->frame[ctx->payload_offset]; - /* right after that is the XORed password */ - uint8_t* password_xored = &nfcv_data->frame[ctx->payload_offset + 1]; - - /* only handle if the password type is supported */ - if(!(password_id & password_supported)) { - break; - } - - /* fetch the last RAND value */ - uint8_t* rand = slix->rand; - - /* first calc the password that has been sent */ - uint8_t password_rcv[4]; - for(int pos = 0; pos < 4; pos++) { - password_rcv[pos] = password_xored[3 - pos] ^ rand[pos % 2]; - } - uint32_t pass_received = slix_read_be(password_rcv, 4); - - /* then determine the password type (or even update if not set yet) */ - uint8_t* password = NULL; - uint32_t flag_valid = 0; - uint32_t flag_set = 0; - - slix_generic_pass_infos(password_id, slix, &password, &flag_valid, &flag_set); - - /* when the password is not supported, return silently */ - if(!password) { - break; - } - - /* check if the password is known */ - bool pass_valid = false; - uint32_t pass_expect = 0; - - if(slix->flags & flag_set) { - /* if so, fetch the stored password and compare */ - pass_expect = slix_read_be(password, 4); - pass_valid = (pass_expect == pass_received); - } else { - /* if not known, just accept it and store that password */ - memcpy(password, password_rcv, 4); - nfcv_data->modified = true; - slix->flags |= flag_set; - - pass_valid = true; - } - - /* if the pass was valid or accepted for other reasons, continue */ - if(pass_valid) { - slix->flags |= flag_valid; - - /* handle actions when a correct password was given, aside of setting the flag */ - switch(password_id) { - case SLIX_PASS_PRIVACY: - slix->flags &= ~NfcVSlixDataFlagsPrivacy; - nfcv_data->modified = true; - break; - case SLIX_PASS_DESTROY: - slix->flags |= NfcVSlixDataFlagsDestroyed; - FURI_LOG_D(TAG, "Pooof! Got destroyed"); - break; - default: - break; - } - - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "SET_PASSWORD #%02X 0x%08lX OK", - password_id, - pass_received); - } else { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "SET_PASSWORD #%02X 0x%08lX/%08lX FAIL", - password_id, - pass_received, - pass_expect); - } - handled = true; - break; - } - - case NFCV_CMD_NXP_WRITE_PASSWORD: { - uint8_t password_id = nfcv_data->frame[ctx->payload_offset]; - - if(!(password_id & password_supported)) { - break; - } - - uint8_t* new_password = &nfcv_data->frame[ctx->payload_offset + 1]; - uint8_t* password = NULL; - uint32_t flag_valid = 0; - uint32_t flag_set = 0; - - slix_generic_pass_infos(password_id, slix, &password, &flag_valid, &flag_set); - - /* when the password is not supported, return silently */ - if(!password) { - break; - } - - bool pass_valid = (slix->flags & flag_valid); - if(!(slix->flags & flag_set)) { - pass_valid = true; - } - - if(pass_valid) { - slix->flags |= flag_valid; - slix->flags |= flag_set; - - memcpy(password, new_password, 4); - - ctx->response_buffer[0] = NFCV_NOERROR; - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - snprintf( - nfcv_data->last_command, sizeof(nfcv_data->last_command), "WRITE_PASSWORD OK"); - } else { - snprintf( - nfcv_data->last_command, sizeof(nfcv_data->last_command), "WRITE_PASSWORD FAIL"); - } - handled = true; - break; - } - - case NFCV_CMD_NXP_ENABLE_PRIVACY: { - ctx->response_buffer[0] = NFCV_NOERROR; - - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, 1, ctx->response_flags, ctx->send_time); - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "NFCV_CMD_NXP_ENABLE_PRIVACY"); - - slix->flags |= NfcVSlixDataFlagsPrivacy; - handled = true; - break; - } - } - - return handled; -} - -bool slix_l_protocol_filter( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data_in) { - furi_assert(tx_rx); - furi_assert(nfc_data); - furi_assert(nfcv_data_in); - - bool handled = false; - - /* many SLIX share some of the functions, place that in a generic handler */ - if(slix_generic_protocol_filter( - tx_rx, - nfc_data, - nfcv_data_in, - SLIX_PASS_PRIVACY | SLIX_PASS_DESTROY | SLIX_PASS_EASAFI)) { - return true; - } - - return handled; -} - -void slix_l_prepare(NfcVData* nfcv_data) { - FURI_LOG_D( - TAG, " Privacy pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_privacy, 4)); - FURI_LOG_D( - TAG, " Destroy pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_destroy, 4)); - FURI_LOG_D(TAG, " EAS pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_eas, 4)); - FURI_LOG_D( - TAG, - " Privacy mode: %s", - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsPrivacy) ? "ON" : "OFF"); - - NfcVEmuProtocolCtx* ctx = nfcv_data->emu_protocol_ctx; - ctx->emu_protocol_filter = &slix_l_protocol_filter; -} - -bool slix_s_protocol_filter( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data_in) { - furi_assert(tx_rx); - furi_assert(nfc_data); - furi_assert(nfcv_data_in); - - bool handled = false; - - /* many SLIX share some of the functions, place that in a generic handler */ - if(slix_generic_protocol_filter(tx_rx, nfc_data, nfcv_data_in, SLIX_PASS_ALL)) { - return true; - } - - return handled; -} - -void slix_s_prepare(NfcVData* nfcv_data) { - FURI_LOG_D( - TAG, " Privacy pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_privacy, 4)); - FURI_LOG_D( - TAG, " Destroy pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_destroy, 4)); - FURI_LOG_D(TAG, " EAS pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_eas, 4)); - FURI_LOG_D( - TAG, - " Privacy mode: %s", - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsPrivacy) ? "ON" : "OFF"); - - NfcVEmuProtocolCtx* ctx = nfcv_data->emu_protocol_ctx; - ctx->emu_protocol_filter = &slix_s_protocol_filter; -} - -bool slix_protocol_filter( - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data_in) { - furi_assert(tx_rx); - furi_assert(nfc_data); - furi_assert(nfcv_data_in); - - bool handled = false; - - /* many SLIX share some of the functions, place that in a generic handler */ - if(slix_generic_protocol_filter(tx_rx, nfc_data, nfcv_data_in, SLIX_PASS_EASAFI)) { - return true; - } - - return handled; -} - -void slix_prepare(NfcVData* nfcv_data) { - FURI_LOG_D( - TAG, " Privacy pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_privacy, 4)); - FURI_LOG_D( - TAG, " Destroy pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_destroy, 4)); - FURI_LOG_D(TAG, " EAS pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_eas, 4)); - FURI_LOG_D( - TAG, - " Privacy mode: %s", - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsPrivacy) ? "ON" : "OFF"); - - NfcVEmuProtocolCtx* ctx = nfcv_data->emu_protocol_ctx; - ctx->emu_protocol_filter = &slix_protocol_filter; -} - -bool slix2_protocol_filter( // -V524 - FuriHalNfcTxRxContext* tx_rx, - FuriHalNfcDevData* nfc_data, - void* nfcv_data_in) { - furi_assert(tx_rx); - furi_assert(nfc_data); - furi_assert(nfcv_data_in); - - NfcVData* nfcv_data = (NfcVData*)nfcv_data_in; - NfcVEmuProtocolCtx* ctx = nfcv_data->emu_protocol_ctx; - NfcVSlixData* slix = &nfcv_data->sub_data.slix; - - bool handled = false; - - /* many SLIX share some of the functions, place that in a generic handler */ - if(slix_generic_protocol_filter(tx_rx, nfc_data, nfcv_data_in, SLIX_PASS_ALL)) { - return true; - } - - switch(ctx->command) { - /* override WRITE BLOCK for block 79 (16 bit counter) */ - case NFCV_CMD_WRITE_BLOCK: - case NFCV_CMD_WRITE_MULTI_BLOCK: { - uint8_t resp_len = 1; - uint8_t blocks = 1; - uint8_t block = nfcv_data->frame[ctx->payload_offset]; - uint8_t data_pos = ctx->payload_offset + 1; - - if(ctx->command == NFCV_CMD_WRITE_MULTI_BLOCK) { - blocks = nfcv_data->frame[data_pos] + 1; - data_pos++; - } - - uint8_t* data = &nfcv_data->frame[data_pos]; - uint32_t data_len = nfcv_data->block_size * blocks; - - if((block + blocks) <= nfcv_data->block_num && - (data_pos + data_len + 2) == nfcv_data->frame_length) { - ctx->response_buffer[0] = NFCV_NOERROR; - - for(int block_num = block; block_num < block + blocks; block_num++) { - /* special case, 16-bit counter */ - if(block_num == 79) { - uint32_t dest; - uint32_t ctr_old; - - memcpy(&dest, &nfcv_data->frame[data_pos], 4); - memcpy(&ctr_old, &nfcv_data->data[nfcv_data->block_size * block_num], 4); - - uint32_t ctr_new = ctr_old; - bool allowed = true; - - /* increment counter */ - if(dest == 1) { - ctr_new = (ctr_old & 0xFFFF0000) | ((ctr_old + 1) & 0xFFFF); - - /* protection flag set? */ - if(ctr_old & 0x01000000) { //-V1051 - allowed = nfcv_data->sub_data.slix.flags & - NfcVSlixDataFlagsValidKeyRead; - } - } else { - ctr_new = dest; - allowed = nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsValidKeyWrite; - } - - if(allowed) { - memcpy( //-V1086 - &nfcv_data->data[nfcv_data->block_size * block_num], - &ctr_new, - 4); - } else { - /* incorrect read or write password */ - ctx->response_buffer[0] = NFCV_RES_FLAG_ERROR; - ctx->response_buffer[1] = NFCV_ERROR_GENERIC; - resp_len = 2; - } - } else { - memcpy( - &nfcv_data->data[nfcv_data->block_size * block_num], - &nfcv_data->frame[data_pos], - nfcv_data->block_size); - } - data_pos += nfcv_data->block_size; - } - nfcv_data->modified = true; - - } else { - ctx->response_buffer[0] = NFCV_RES_FLAG_ERROR; - ctx->response_buffer[1] = NFCV_ERROR_GENERIC; - resp_len = 2; - } - - bool respond = (ctx->response_buffer[0] == NFCV_NOERROR) || - (ctx->addressed || ctx->selected); - - if(respond) { - nfcv_emu_send( - tx_rx, - nfcv_data, - ctx->response_buffer, - resp_len, - ctx->response_flags, - ctx->send_time); - } - - if(ctx->command == NFCV_CMD_WRITE_MULTI_BLOCK) { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "WRITE MULTI BLOCK %d, %d blocks", - block, - blocks); - } else { - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "WRITE BLOCK %d <- %02X %02X %02X %02X", - block, - data[0], - data[1], - data[2], - data[3]); - } - handled = true; - break; - } - - case NFCV_CMD_NXP_READ_SIGNATURE: { - uint32_t len = 0; - ctx->response_buffer[len++] = NFCV_NOERROR; - memcpy(&ctx->response_buffer[len], slix->signature, sizeof(slix->signature)); - len += sizeof(slix->signature); - - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, len, ctx->response_flags, ctx->send_time); - snprintf(nfcv_data->last_command, sizeof(nfcv_data->last_command), "READ_SIGNATURE"); - - handled = true; - break; - } - - case NFCV_CMD_NXP_GET_NXP_SYSTEM_INFORMATION: { - uint32_t len = 0; - uint8_t lock_bits = 0; - - /* convert our internal lock bits format into NXP's */ - lock_bits |= (nfcv_data->security_status[0] & NfcVLockBitDsfid) ? SlixLockBitDsfid : 0; - lock_bits |= (nfcv_data->security_status[0] & NfcVLockBitAfi) ? SlixLockBitAfi : 0; - lock_bits |= (nfcv_data->security_status[0] & NfcVLockBitEas) ? SlixLockBitEas : 0; - lock_bits |= (nfcv_data->security_status[0] & NfcVLockBitPpl) ? SlixLockBitPpl : 0; - - ctx->response_buffer[len++] = NFCV_NOERROR; - ctx->response_buffer[len++] = nfcv_data->sub_data.slix.pp_pointer; - ctx->response_buffer[len++] = nfcv_data->sub_data.slix.pp_condition; - ctx->response_buffer[len++] = lock_bits; - ctx->response_buffer[len++] = 0x7F; /* features LSB */ - ctx->response_buffer[len++] = 0x35; /* features */ - ctx->response_buffer[len++] = 0; /* features */ - ctx->response_buffer[len++] = 0; /* features MSB */ - - nfcv_emu_send( - tx_rx, nfcv_data, ctx->response_buffer, len, ctx->response_flags, ctx->send_time); - snprintf( - nfcv_data->last_command, - sizeof(nfcv_data->last_command), - "GET_NXP_SYSTEM_INFORMATION"); - - handled = true; - break; - } - } - - return handled; -} - -void slix2_prepare(NfcVData* nfcv_data) { - FURI_LOG_D( - TAG, " Privacy pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_privacy, 4)); - FURI_LOG_D( - TAG, " Destroy pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_destroy, 4)); - FURI_LOG_D(TAG, " EAS pass: 0x%08lX", slix_read_be(nfcv_data->sub_data.slix.key_eas, 4)); - FURI_LOG_D( - TAG, - " Privacy mode: %s", - (nfcv_data->sub_data.slix.flags & NfcVSlixDataFlagsPrivacy) ? "ON" : "OFF"); - - NfcVEmuProtocolCtx* ctx = nfcv_data->emu_protocol_ctx; - ctx->emu_protocol_filter = &slix2_protocol_filter; -} diff --git a/lib/nfc/protocols/slix.h b/lib/nfc/protocols/slix.h deleted file mode 100644 index 67f09e46d..000000000 --- a/lib/nfc/protocols/slix.h +++ /dev/null @@ -1,66 +0,0 @@ -#pragma once - -#include -#include -#include "nfc_util.h" -#include - -#define NFCV_MANUFACTURER_NXP 0x04 - -/* ISO15693-3 CUSTOM NXP COMMANDS */ -typedef enum { - NFCV_CMD_NXP_SET_EAS = 0xA2, - NFCV_CMD_NXP_RESET_EAS = 0xA3, - NFCV_CMD_NXP_LOCK_EAS = 0xA4, - NFCV_CMD_NXP_EAS_ALARM = 0xA5, - NFCV_CMD_NXP_PASSWORD_PROTECT_EAS_AFI = 0xA6, - NFCV_CMD_NXP_WRITE_EAS_ID = 0xA7, - NFCV_CMD_NXP_GET_NXP_SYSTEM_INFORMATION = 0xAB, - NFCV_CMD_NXP_INVENTORY_PAGE_READ = 0xB0, - NFCV_CMD_NXP_INVENTORY_PAGE_READ_FAST = 0xB1, - NFCV_CMD_NXP_GET_RANDOM_NUMBER = 0xB2, - NFCV_CMD_NXP_SET_PASSWORD = 0xB3, - NFCV_CMD_NXP_WRITE_PASSWORD = 0xB4, - NFCV_CMD_NXP_64_BIT_PASSWORD_PROTECTION = 0xB5, - NFCV_CMD_NXP_PROTECT_PAGE = 0xB6, - NFCV_CMD_NXP_LOCK_PAGE_PROTECTION_CONDITION = 0xB7, - NFCV_CMD_NXP_DESTROY = 0xB9, - NFCV_CMD_NXP_ENABLE_PRIVACY = 0xBA, - NFCV_CMD_NXP_STAY_QUIET_PERSISTENT = 0xBC, - NFCV_CMD_NXP_READ_SIGNATURE = 0xBD -} SlixCommands; - -/* lock bit bits used in SLIX's NXP SYSTEM INFORMATION response */ -typedef enum { - SlixLockBitAfi = 1 << 0, - SlixLockBitEas = 1 << 1, - SlixLockBitDsfid = 1 << 2, - SlixLockBitPpl = 1 << 3, -} SlixLockBits; - -/* available passwords */ -#define SLIX_PASS_READ 0x01 -#define SLIX_PASS_WRITE 0x02 -#define SLIX_PASS_PRIVACY 0x04 -#define SLIX_PASS_DESTROY 0x08 -#define SLIX_PASS_EASAFI 0x10 - -#define SLIX_PASS_ALL \ - (SLIX_PASS_READ | SLIX_PASS_WRITE | SLIX_PASS_PRIVACY | SLIX_PASS_DESTROY | SLIX_PASS_EASAFI) - -bool slix_check_card_type(FuriHalNfcDevData* nfc_data); -bool slix2_check_card_type(FuriHalNfcDevData* nfc_data); -bool slix_s_check_card_type(FuriHalNfcDevData* nfc_data); -bool slix_l_check_card_type(FuriHalNfcDevData* nfc_data); - -ReturnCode slix2_read_custom(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data); -ReturnCode slix2_read_signature(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data); -ReturnCode slix2_read_nxp_sysinfo(FuriHalNfcDevData* nfc_data, NfcVData* nfcv_data); - -ReturnCode slix_get_random(NfcVData* data); -ReturnCode slix_unlock(NfcVData* data, uint32_t password_id); - -void slix_prepare(NfcVData* nfcv_data); -void slix_s_prepare(NfcVData* nfcv_data); -void slix_l_prepare(NfcVData* nfcv_data); -void slix2_prepare(NfcVData* nfcv_data); diff --git a/lib/nfc/protocols/slix/slix.c b/lib/nfc/protocols/slix/slix.c new file mode 100644 index 000000000..12dc6750d --- /dev/null +++ b/lib/nfc/protocols/slix/slix.c @@ -0,0 +1,433 @@ +#include "slix_i.h" +#include "slix_device_defs.h" + +#include +#include + +#define SLIX_PROTOCOL_NAME "SLIX" +#define SLIX_DEVICE_NAME "SLIX" + +#define SLIX_TYPE_SLIX_SLIX2 (0x01U) +#define SLIX_TYPE_SLIX_S (0x02U) +#define SLIX_TYPE_SLIX_L (0x03U) + +#define SLIX_TYPE_INDICATOR_SLIX (0x02U) +#define SLIX_TYPE_INDICATOR_SLIX2 (0x01U) + +#define SLIX_PASSWORD_READ_KEY "Password Read" +#define SLIX_PASSWORD_WRITE_KEY "Password Write" +#define SLIX_PASSWORD_PRIVACY_KEY "Password Privacy" +#define SLIX_PASSWORD_DESTROY_KEY "Password Destroy" +#define SLIX_PASSWORD_EAS_KEY "Password EAS" +#define SLIX_SIGNATURE_KEY "Signature" +#define SLIX_PRIVACY_MODE_KEY "Privacy Mode" +#define SLIX_PROTECTION_POINTER_KEY "Protection Pointer" +#define SLIX_PROTECTION_CONDITION_KEY "Protection Condition" +#define SLIX_LOCK_EAS_KEY "Lock EAS" +#define SLIX_LOCK_PPL_KEY "Lock PPL" + +typedef struct { + uint8_t iso15693_3[2]; + uint8_t icode_type; + union { + struct { + uint8_t unused_1 : 3; + uint8_t type_indicator : 2; + uint8_t unused_2 : 3; + }; + uint8_t serial_num[5]; + }; +} SlixUidLayout; + +const NfcDeviceBase nfc_device_slix = { + .protocol_name = SLIX_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)slix_alloc, + .free = (NfcDeviceFree)slix_free, + .reset = (NfcDeviceReset)slix_reset, + .copy = (NfcDeviceCopy)slix_copy, + .verify = (NfcDeviceVerify)slix_verify, + .load = (NfcDeviceLoad)slix_load, + .save = (NfcDeviceSave)slix_save, + .is_equal = (NfcDeviceEqual)slix_is_equal, + .get_name = (NfcDeviceGetName)slix_get_device_name, + .get_uid = (NfcDeviceGetUid)slix_get_uid, + .set_uid = (NfcDeviceSetUid)slix_set_uid, + .get_base_data = (NfcDeviceGetBaseData)slix_get_base_data, +}; + +static const char* slix_nfc_device_name[] = { + [SlixTypeSlix] = SLIX_DEVICE_NAME, + [SlixTypeSlixS] = SLIX_DEVICE_NAME "-S", + [SlixTypeSlixL] = SLIX_DEVICE_NAME "-L", + [SlixTypeSlix2] = SLIX_DEVICE_NAME "2", +}; + +static const SlixTypeFeatures slix_type_features[] = { + [SlixTypeSlix] = SLIX_TYPE_FEATURES_SLIX, + [SlixTypeSlixS] = SLIX_TYPE_FEATURES_SLIX_S, + [SlixTypeSlixL] = SLIX_TYPE_FEATURES_SLIX_L, + [SlixTypeSlix2] = SLIX_TYPE_FEATURES_SLIX2, +}; + +typedef struct { + const char* key; + SlixTypeFeatures feature_flag; + SlixPassword default_value; +} SlixPasswordConfig; + +static const SlixPasswordConfig slix_password_configs[] = { + [SlixPasswordTypeRead] = {SLIX_PASSWORD_READ_KEY, SLIX_TYPE_FEATURE_READ, 0x00000000U}, + [SlixPasswordTypeWrite] = {SLIX_PASSWORD_WRITE_KEY, SLIX_TYPE_FEATURE_WRITE, 0x00000000U}, + [SlixPasswordTypePrivacy] = {SLIX_PASSWORD_PRIVACY_KEY, SLIX_TYPE_FEATURE_PRIVACY, 0xFFFFFFFFU}, + [SlixPasswordTypeDestroy] = {SLIX_PASSWORD_DESTROY_KEY, SLIX_TYPE_FEATURE_DESTROY, 0xFFFFFFFFU}, + [SlixPasswordTypeEasAfi] = {SLIX_PASSWORD_EAS_KEY, SLIX_TYPE_FEATURE_EAS, 0x00000000U}, +}; + +static void slix_password_set_defaults(SlixPassword* passwords) { + for(uint32_t i = 0; i < COUNT_OF(slix_password_configs); ++i) { + passwords[i] = slix_password_configs[i].default_value; + } +} + +SlixData* slix_alloc() { + SlixData* data = malloc(sizeof(SlixData)); + + data->iso15693_3_data = iso15693_3_alloc(); + slix_password_set_defaults(data->passwords); + + return data; +} + +void slix_free(SlixData* data) { + furi_assert(data); + + iso15693_3_free(data->iso15693_3_data); + + free(data); +} + +void slix_reset(SlixData* data) { + furi_assert(data); + + iso15693_3_reset(data->iso15693_3_data); + slix_password_set_defaults(data->passwords); + + memset(&data->system_info, 0, sizeof(SlixSystemInfo)); + memset(data->signature, 0, sizeof(SlixSignature)); + + data->privacy = false; +} + +void slix_copy(SlixData* data, const SlixData* other) { + furi_assert(data); + furi_assert(other); + + iso15693_3_copy(data->iso15693_3_data, other->iso15693_3_data); + + memcpy(data->passwords, other->passwords, sizeof(SlixPassword) * SlixPasswordTypeCount); + memcpy(data->signature, other->signature, sizeof(SlixSignature)); + + data->system_info = other->system_info; + data->privacy = other->privacy; +} + +bool slix_verify(SlixData* data, const FuriString* device_type) { + UNUSED(data); + UNUSED(device_type); + // No backward compatibility, unified format only + return false; +} + +static bool slix_load_passwords(SlixPassword* passwords, SlixType slix_type, FlipperFormat* ff) { + bool ret = true; + + for(uint32_t i = 0; i < COUNT_OF(slix_password_configs); ++i) { + const SlixPasswordConfig* password_config = &slix_password_configs[i]; + + if(!slix_type_has_features(slix_type, password_config->feature_flag)) continue; + if(!flipper_format_key_exist(ff, password_config->key)) { + passwords[i] = password_config->default_value; + continue; + } + if(!flipper_format_read_hex( + ff, password_config->key, (uint8_t*)&passwords[i], sizeof(SlixPassword))) { + ret = false; + break; + } + } + + return ret; +} + +bool slix_load(SlixData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + + bool loaded = false; + + do { + if(!iso15693_3_load(data->iso15693_3_data, ff, version)) break; + + const SlixType slix_type = slix_get_type(data); + if(slix_type >= SlixTypeCount) break; + + if(!slix_load_passwords(data->passwords, slix_type, ff)) break; + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_SIGNATURE)) { + if(flipper_format_key_exist(ff, SLIX_SIGNATURE_KEY)) { + if(!flipper_format_read_hex( + ff, SLIX_SIGNATURE_KEY, data->signature, SLIX_SIGNATURE_SIZE)) + break; + } + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_PRIVACY)) { + if(flipper_format_key_exist(ff, SLIX_PRIVACY_MODE_KEY)) { + if(!flipper_format_read_bool(ff, SLIX_PRIVACY_MODE_KEY, &data->privacy, 1)) break; + } + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_PROTECTION)) { + SlixProtection* protection = &data->system_info.protection; + if(flipper_format_key_exist(ff, SLIX_PROTECTION_POINTER_KEY) && + flipper_format_key_exist(ff, SLIX_PROTECTION_CONDITION_KEY)) { + if(!flipper_format_read_hex( + ff, SLIX_PROTECTION_POINTER_KEY, &protection->pointer, 1)) + break; + if(!flipper_format_read_hex( + ff, SLIX_PROTECTION_CONDITION_KEY, &protection->condition, 1)) + break; + } + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_EAS)) { + if(flipper_format_key_exist(ff, SLIX_LOCK_EAS_KEY)) { + SlixLockBits* lock_bits = &data->system_info.lock_bits; + if(!flipper_format_read_bool(ff, SLIX_LOCK_EAS_KEY, &lock_bits->eas, 1)) break; + } + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_PROTECTION)) { + if(flipper_format_key_exist(ff, SLIX_LOCK_PPL_KEY)) { + SlixLockBits* lock_bits = &data->system_info.lock_bits; + if(!flipper_format_read_bool(ff, SLIX_LOCK_PPL_KEY, &lock_bits->ppl, 1)) break; + } + } + + loaded = true; + } while(false); + + return loaded; +} + +static bool + slix_save_passwords(const SlixPassword* passwords, SlixType slix_type, FlipperFormat* ff) { + bool ret = true; + + for(uint32_t i = 0; i < COUNT_OF(slix_password_configs); ++i) { + const SlixPasswordConfig* password_config = &slix_password_configs[i]; + + if(!slix_type_has_features(slix_type, password_config->feature_flag)) continue; + if(!flipper_format_write_hex( + ff, password_config->key, (uint8_t*)&passwords[i], sizeof(SlixPassword))) { + ret = false; + break; + } + } + + return ret; +} + +bool slix_save(const SlixData* data, FlipperFormat* ff) { + furi_assert(data); + + bool saved = false; + + do { + const SlixType slix_type = slix_get_type(data); + if(slix_type >= SlixTypeCount) break; + + if(!iso15693_3_save(data->iso15693_3_data, ff)) break; + if(!flipper_format_write_comment_cstr(ff, SLIX_PROTOCOL_NAME " specific data")) break; + + if(!flipper_format_write_comment_cstr( + ff, + "Passwords are optional. If a password is omitted, a default value will be used")) + break; + + if(!slix_save_passwords(data->passwords, slix_type, ff)) break; + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_SIGNATURE)) { + if(!flipper_format_write_comment_cstr( + ff, + "This is the card's secp128r1 elliptic curve signature. It can not be calculated without knowing NXP's private key.")) + break; + if(!flipper_format_write_hex( + ff, SLIX_SIGNATURE_KEY, data->signature, SLIX_SIGNATURE_SIZE)) + break; + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_PRIVACY)) { + if(!flipper_format_write_bool(ff, SLIX_PRIVACY_MODE_KEY, &data->privacy, 1)) break; + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_PROTECTION)) { + const SlixProtection* protection = &data->system_info.protection; + if(!flipper_format_write_comment_cstr(ff, "Protection pointer configuration")) break; + if(!flipper_format_write_hex( + ff, SLIX_PROTECTION_POINTER_KEY, &protection->pointer, sizeof(uint8_t))) + break; + if(!flipper_format_write_hex( + ff, SLIX_PROTECTION_CONDITION_KEY, &protection->condition, sizeof(uint8_t))) + break; + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_EAS) || + slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_PROTECTION)) { + if(!flipper_format_write_comment_cstr(ff, "SLIX Lock Bits")) break; + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_EAS)) { + const SlixLockBits* lock_bits = &data->system_info.lock_bits; + if(!flipper_format_write_bool(ff, SLIX_LOCK_EAS_KEY, &lock_bits->eas, 1)) break; + } + + if(slix_type_has_features(slix_type, SLIX_TYPE_FEATURE_PROTECTION)) { + const SlixLockBits* lock_bits = &data->system_info.lock_bits; + if(!flipper_format_write_bool(ff, SLIX_LOCK_PPL_KEY, &lock_bits->ppl, 1)) break; + } + + saved = true; + } while(false); + + return saved; +} + +bool slix_is_equal(const SlixData* data, const SlixData* other) { + return iso15693_3_is_equal(data->iso15693_3_data, other->iso15693_3_data) && + memcmp(&data->system_info, &other->system_info, sizeof(SlixSystemInfo)) == 0 && + memcmp( + data->passwords, other->passwords, sizeof(SlixPassword) * SlixPasswordTypeCount) == + 0 && + memcmp(&data->signature, &other->signature, sizeof(SlixSignature)) == 0 && + data->privacy == other->privacy; +} + +const char* slix_get_device_name(const SlixData* data, NfcDeviceNameType name_type) { + UNUSED(name_type); + + const SlixType slix_type = slix_get_type(data); + furi_assert(slix_type < SlixTypeCount); + + return slix_nfc_device_name[slix_type]; +} + +const uint8_t* slix_get_uid(const SlixData* data, size_t* uid_len) { + return iso15693_3_get_uid(data->iso15693_3_data, uid_len); +} + +bool slix_set_uid(SlixData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + return iso15693_3_set_uid(data->iso15693_3_data, uid, uid_len); +} + +const Iso15693_3Data* slix_get_base_data(const SlixData* data) { + furi_assert(data); + + return data->iso15693_3_data; +} + +SlixType slix_get_type(const SlixData* data) { + SlixType type = SlixTypeCount; + + do { + if(iso15693_3_get_manufacturer_id(data->iso15693_3_data) != SLIX_NXP_MANUFACTURER_CODE) + break; + + const SlixUidLayout* uid = (const SlixUidLayout*)data->iso15693_3_data->uid; + + if(uid->icode_type == SLIX_TYPE_SLIX_SLIX2) { + if(uid->type_indicator == SLIX_TYPE_INDICATOR_SLIX) { + type = SlixTypeSlix; + } else if(uid->type_indicator == SLIX_TYPE_INDICATOR_SLIX2) { + type = SlixTypeSlix2; + } + } else if(uid->icode_type == SLIX_TYPE_SLIX_S) { + type = SlixTypeSlixS; + } else if(uid->icode_type == SLIX_TYPE_SLIX_L) { + type = SlixTypeSlixL; + } + + } while(false); + + return type; +} + +SlixPassword slix_get_password(const SlixData* data, SlixPasswordType password_type) { + furi_assert(data); + furi_assert(password_type < SlixPasswordTypeCount); + + return data->passwords[password_type]; +} + +uint16_t slix_get_counter(const SlixData* data) { + furi_assert(data); + const SlixCounter* counter = (const SlixCounter*)iso15693_3_get_block_data( + data->iso15693_3_data, SLIX_COUNTER_BLOCK_NUM); + + return counter->value; +} + +bool slix_is_privacy_mode(const SlixData* data) { + furi_assert(data); + + return data->privacy; +} + +bool slix_is_block_protected( + const SlixData* data, + SlixPasswordType password_type, + uint8_t block_num) { + furi_assert(data); + furi_assert(password_type < SlixPasswordTypeCount); + + bool ret = false; + + do { + if(password_type != SlixPasswordTypeRead && password_type != SlixPasswordTypeWrite) break; + if(block_num >= iso15693_3_get_block_count(data->iso15693_3_data)) break; + if(block_num == SLIX_COUNTER_BLOCK_NUM) break; + + const bool high = block_num >= data->system_info.protection.pointer; + const bool read = password_type == SlixPasswordTypeRead; + + const uint8_t condition = high ? (read ? SLIX_PP_CONDITION_RH : SLIX_PP_CONDITION_WH) : + (read ? SLIX_PP_CONDITION_RL : SLIX_PP_CONDITION_WL); + + ret = data->system_info.protection.condition & condition; + } while(false); + + return ret; +} + +bool slix_is_counter_increment_protected(const SlixData* data) { + furi_assert(data); + + const SlixCounter* counter = (const SlixCounter*)iso15693_3_get_block_data( + data->iso15693_3_data, SLIX_COUNTER_BLOCK_NUM); + + return counter->protection != 0; +} + +bool slix_type_has_features(SlixType slix_type, SlixTypeFeatures features) { + furi_assert(slix_type < SlixTypeCount); + + return (slix_type_features[slix_type] & features) == features; +} + +bool slix_type_supports_password(SlixType slix_type, SlixPasswordType password_type) { + furi_assert(slix_type < SlixTypeCount); + furi_assert(password_type < SlixPasswordTypeCount); + + return slix_type_features[slix_type] & slix_password_configs[password_type].feature_flag; +} diff --git a/lib/nfc/protocols/slix/slix.h b/lib/nfc/protocols/slix/slix.h new file mode 100644 index 000000000..f6c1453c5 --- /dev/null +++ b/lib/nfc/protocols/slix/slix.h @@ -0,0 +1,146 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define SLIX_BLOCK_SIZE (4U) +#define SLIX_SIGNATURE_SIZE (32U) + +#define SLIX_COUNTER_BLOCK_NUM (79U) + +#define SLIX_PP_CONDITION_RL (1U << 0) +#define SLIX_PP_CONDITION_WL (1U << 1) +#define SLIX_PP_CONDITION_RH (1U << 4) +#define SLIX_PP_CONDITION_WH (1U << 5) + +#define SLIX_FEATURE_FLAG_UM_PP (1UL << 0) +#define SLIX_FEATURE_FLAG_COUNTER (1UL << 1) +#define SLIX_FEATURE_FLAG_EAS_ID (1UL << 2) +#define SLIX_FEATURE_FLAG_EAS_PP (1UL << 3) +#define SLIX_FEATURE_FLAG_AFI_PP (1UL << 4) +#define SLIX_FEATURE_FLAG_INVENTORY_READ_EXT (1UL << 5) +#define SLIX_FEATURE_FLAG_EAS_IR (1UL << 6) +#define SLIX_FEATURE_FLAG_ORIGINALITY_SIG (1UL << 8) +#define SLIX_FEATURE_FLAG_ORIGINALITY_SIG_PP (1UL << 9) +#define SLIX_FEATURE_FLAG_PERSISTENT_QUIET (1UL << 10) +#define SLIX_FEATURE_FLAG_PRIVACY (1UL << 12) +#define SLIX_FEATURE_FLAG_DESTROY (1UL << 13) +#define SLIX_FEATURE_EXT (1UL << 31) + +#define SLIX_TYPE_FEATURE_READ (1U << 0) +#define SLIX_TYPE_FEATURE_WRITE (1U << 1) +#define SLIX_TYPE_FEATURE_PRIVACY (1U << 2) +#define SLIX_TYPE_FEATURE_DESTROY (1U << 3) +#define SLIX_TYPE_FEATURE_EAS (1U << 4) +#define SLIX_TYPE_FEATURE_SIGNATURE (1U << 5) +#define SLIX_TYPE_FEATURE_PROTECTION (1U << 6) + +typedef uint32_t SlixTypeFeatures; + +typedef enum { + SlixErrorNone, + SlixErrorTimeout, + SlixErrorFormat, + SlixErrorNotSupported, + SlixErrorInternal, + SlixErrorWrongPassword, + SlixErrorUidMismatch, + SlixErrorUnknown, +} SlixError; + +typedef enum { + SlixTypeSlix, + SlixTypeSlixS, + SlixTypeSlixL, + SlixTypeSlix2, + SlixTypeCount, +} SlixType; + +typedef enum { + SlixPasswordTypeRead, + SlixPasswordTypeWrite, + SlixPasswordTypePrivacy, + SlixPasswordTypeDestroy, + SlixPasswordTypeEasAfi, + SlixPasswordTypeCount, +} SlixPasswordType; + +typedef uint32_t SlixPassword; +typedef uint8_t SlixSignature[SLIX_SIGNATURE_SIZE]; +typedef bool SlixPrivacy; + +typedef struct { + uint8_t pointer; + uint8_t condition; +} SlixProtection; + +typedef struct { + bool eas; + bool ppl; +} SlixLockBits; + +typedef struct { + SlixProtection protection; + SlixLockBits lock_bits; +} SlixSystemInfo; + +typedef struct { + Iso15693_3Data* iso15693_3_data; + SlixSystemInfo system_info; + SlixSignature signature; + SlixPassword passwords[SlixPasswordTypeCount]; + SlixPrivacy privacy; +} SlixData; + +SlixData* slix_alloc(); + +void slix_free(SlixData* data); + +void slix_reset(SlixData* data); + +void slix_copy(SlixData* data, const SlixData* other); + +bool slix_verify(SlixData* data, const FuriString* device_type); + +bool slix_load(SlixData* data, FlipperFormat* ff, uint32_t version); + +bool slix_save(const SlixData* data, FlipperFormat* ff); + +bool slix_is_equal(const SlixData* data, const SlixData* other); + +const char* slix_get_device_name(const SlixData* data, NfcDeviceNameType name_type); + +const uint8_t* slix_get_uid(const SlixData* data, size_t* uid_len); + +bool slix_set_uid(SlixData* data, const uint8_t* uid, size_t uid_len); + +const Iso15693_3Data* slix_get_base_data(const SlixData* data); + +// Getters and tests + +SlixType slix_get_type(const SlixData* data); + +SlixPassword slix_get_password(const SlixData* data, SlixPasswordType password_type); + +uint16_t slix_get_counter(const SlixData* data); + +bool slix_is_privacy_mode(const SlixData* data); + +bool slix_is_block_protected( + const SlixData* data, + SlixPasswordType password_type, + uint8_t block_num); + +bool slix_is_counter_increment_protected(const SlixData* data); + +// Static methods +bool slix_type_has_features(SlixType slix_type, SlixTypeFeatures features); + +bool slix_type_supports_password(SlixType slix_type, SlixPasswordType password_type); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/slix/slix_device_defs.h b/lib/nfc/protocols/slix/slix_device_defs.h new file mode 100644 index 000000000..cadd40eec --- /dev/null +++ b/lib/nfc/protocols/slix/slix_device_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcDeviceBase nfc_device_slix; diff --git a/lib/nfc/protocols/slix/slix_i.c b/lib/nfc/protocols/slix/slix_i.c new file mode 100644 index 000000000..97d66484c --- /dev/null +++ b/lib/nfc/protocols/slix/slix_i.c @@ -0,0 +1,127 @@ +#include "slix_i.h" + +#include + +bool slix_error_response_parse(SlixError* error, const BitBuffer* buf) { + Iso15693_3Error iso15693_3_error; + const bool ret = iso15693_3_error_response_parse(&iso15693_3_error, buf); + + if(ret) { + *error = slix_process_iso15693_3_error(iso15693_3_error); + } + + return ret; +} + +SlixError slix_process_iso15693_3_error(Iso15693_3Error iso15693_3_error) { + switch(iso15693_3_error) { + case Iso15693_3ErrorNone: + return SlixErrorNone; + case Iso15693_3ErrorTimeout: + return SlixErrorTimeout; + case Iso15693_3ErrorFormat: + return SlixErrorFormat; + case Iso15693_3ErrorInternal: + return SlixErrorInternal; + default: + return SlixErrorUnknown; + } +} + +SlixError slix_get_nxp_system_info_response_parse(SlixData* data, const BitBuffer* buf) { + furi_assert(data); + SlixError error = SlixErrorNone; + + do { + if(slix_error_response_parse(&error, buf)) break; + + typedef struct { + uint8_t flags; + uint8_t pp_pointer; + uint8_t pp_condition; + uint8_t lock_bits; + uint32_t feature_flags; + } SlixGetNxpSystemInfoResponseLayout; + + const size_t size_received = bit_buffer_get_size_bytes(buf); + const size_t size_required = sizeof(SlixGetNxpSystemInfoResponseLayout); + + if(size_received != size_required) { + error = SlixErrorFormat; + break; + } + + const SlixGetNxpSystemInfoResponseLayout* response = + (const SlixGetNxpSystemInfoResponseLayout*)bit_buffer_get_data(buf); + + SlixProtection* protection = &data->system_info.protection; + protection->pointer = response->pp_pointer; + protection->condition = response->pp_condition; + + Iso15693_3LockBits* iso15693_3_lock_bits = &data->iso15693_3_data->settings.lock_bits; + iso15693_3_lock_bits->dsfid = response->lock_bits & SLIX_LOCK_BITS_DSFID; + iso15693_3_lock_bits->afi = response->lock_bits & SLIX_LOCK_BITS_AFI; + + SlixLockBits* slix_lock_bits = &data->system_info.lock_bits; + slix_lock_bits->eas = response->lock_bits & SLIX_LOCK_BITS_EAS; + slix_lock_bits->ppl = response->lock_bits & SLIX_LOCK_BITS_PPL; + + } while(false); + + return error; +} + +SlixError slix_read_signature_response_parse(SlixSignature data, const BitBuffer* buf) { + SlixError error = SlixErrorNone; + + do { + if(slix_error_response_parse(&error, buf)) break; + + typedef struct { + uint8_t flags; + uint8_t signature[SLIX_SIGNATURE_SIZE]; + } SlixReadSignatureResponseLayout; + + const size_t size_received = bit_buffer_get_size_bytes(buf); + const size_t size_required = sizeof(SlixReadSignatureResponseLayout); + + if(size_received != size_required) { + error = SlixErrorFormat; + break; + } + + const SlixReadSignatureResponseLayout* response = + (const SlixReadSignatureResponseLayout*)bit_buffer_get_data(buf); + + memcpy(data, response->signature, sizeof(SlixSignature)); + } while(false); + + return error; +} + +void slix_set_password(SlixData* data, SlixPasswordType password_type, SlixPassword password) { + furi_assert(data); + furi_assert(password_type < SlixPasswordTypeCount); + + data->passwords[password_type] = password; +} + +void slix_set_privacy_mode(SlixData* data, bool set) { + furi_assert(data); + + data->privacy = set; +} + +void slix_increment_counter(SlixData* data) { + furi_assert(data); + + const uint8_t* block_data = + iso15693_3_get_block_data(data->iso15693_3_data, SLIX_COUNTER_BLOCK_NUM); + + SlixCounter counter; + memcpy(counter.bytes, block_data, SLIX_BLOCK_SIZE); + counter.value += 1; + + iso15693_3_set_block_data( + data->iso15693_3_data, SLIX_COUNTER_BLOCK_NUM, counter.bytes, sizeof(SlixCounter)); +} diff --git a/lib/nfc/protocols/slix/slix_i.h b/lib/nfc/protocols/slix/slix_i.h new file mode 100644 index 000000000..b5e445f31 --- /dev/null +++ b/lib/nfc/protocols/slix/slix_i.h @@ -0,0 +1,86 @@ +#pragma once + +#include "slix.h" + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define SLIX_NXP_MANUFACTURER_CODE (0x04U) + +#define SLIX_LOCK_BITS_AFI (1U << 0) +#define SLIX_LOCK_BITS_EAS (1U << 1) +#define SLIX_LOCK_BITS_DSFID (1U << 2) +#define SLIX_LOCK_BITS_PPL (1U << 3) + +#define SLIX_CMD_CUSTOM_START (0xA2U) +#define SLIX_CMD_SET_EAS (0xA2U) +#define SLIX_CMD_RESET_EAS (0xA3U) +#define SLIX_CMD_LOCK_EAS (0xA4U) +#define SLIX_CMD_EAS_ALARM (0xA5U) +#define SLIX_CMD_PASSWORD_PROTECT_EAS_AFI (0xA6U) +#define SLIX_CMD_WRITE_EAS_ID (0xA7U) +#define SLIX_CMD_GET_NXP_SYSTEM_INFORMATION (0xABU) +#define SLIX_CMD_INVENTORY_PAGE_READ (0xB0U) +#define SLIX_CMD_INVENTORY_PAGE_READ_FAST (0xB1U) +#define SLIX_CMD_GET_RANDOM_NUMBER (0xB2U) +#define SLIX_CMD_SET_PASSWORD (0xB3U) +#define SLIX_CMD_WRITE_PASSWORD (0xB4U) +#define SLIX_CMD_64_BIT_PASSWORD_PROTECTION (0xB5U) +#define SLIX_CMD_PROTECT_PAGE (0xB6U) +#define SLIX_CMD_LOCK_PAGE_PROTECTION_CONDITION (0xB7U) +#define SLIX_CMD_DESTROY (0xB9U) +#define SLIX_CMD_ENABLE_PRIVACY (0xBAU) +#define SLIX_CMD_STAY_QUIET_PERSISTENT (0xBCU) +#define SLIX_CMD_READ_SIGNATURE (0xBDU) +#define SLIX_CMD_CUSTOM_END (0xBEU) +#define SLIX_CMD_CUSTOM_COUNT (SLIX_CMD_CUSTOM_END - SLIX_CMD_CUSTOM_START) + +#define SLIX_TYPE_FEATURES_SLIX (SLIX_TYPE_FEATURE_EAS) +#define SLIX_TYPE_FEATURES_SLIX_S \ + (SLIX_TYPE_FEATURE_READ | SLIX_TYPE_FEATURE_WRITE | SLIX_TYPE_FEATURE_PRIVACY | \ + SLIX_TYPE_FEATURE_DESTROY | SLIX_TYPE_FEATURE_EAS) +#define SLIX_TYPE_FEATURES_SLIX_L \ + (SLIX_TYPE_FEATURE_PRIVACY | SLIX_TYPE_FEATURE_DESTROY | SLIX_TYPE_FEATURE_EAS) +#define SLIX_TYPE_FEATURES_SLIX2 \ + (SLIX_TYPE_FEATURE_READ | SLIX_TYPE_FEATURE_WRITE | SLIX_TYPE_FEATURE_PRIVACY | \ + SLIX_TYPE_FEATURE_DESTROY | SLIX_TYPE_FEATURE_EAS | SLIX_TYPE_FEATURE_SIGNATURE | \ + SLIX_TYPE_FEATURE_PROTECTION) + +#define SLIX2_FEATURE_FLAGS \ + (SLIX_FEATURE_FLAG_UM_PP | SLIX_FEATURE_FLAG_COUNTER | SLIX_FEATURE_FLAG_EAS_ID | \ + SLIX_FEATURE_FLAG_EAS_PP | SLIX_FEATURE_FLAG_AFI_PP | SLIX_FEATURE_FLAG_INVENTORY_READ_EXT | \ + SLIX_FEATURE_FLAG_EAS_IR | SLIX_FEATURE_FLAG_ORIGINALITY_SIG | \ + SLIX_FEATURE_FLAG_PERSISTENT_QUIET | SLIX_FEATURE_FLAG_PRIVACY | SLIX_FEATURE_FLAG_DESTROY) + +typedef union { + struct { + uint16_t value; + uint8_t reserved; + uint8_t protection; + }; + uint8_t bytes[SLIX_BLOCK_SIZE]; +} SlixCounter; + +// Same behaviour as iso15693_3_error_response_parse +bool slix_error_response_parse(SlixError* error, const BitBuffer* buf); + +SlixError slix_process_iso15693_3_error(Iso15693_3Error iso15693_3_error); + +SlixError slix_get_nxp_system_info_response_parse(SlixData* data, const BitBuffer* buf); + +SlixError slix_read_signature_response_parse(SlixSignature data, const BitBuffer* buf); + +// Setters +void slix_set_password(SlixData* data, SlixPasswordType password_type, SlixPassword password); + +void slix_set_privacy_mode(SlixData* data, bool set); + +void slix_increment_counter(SlixData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/slix/slix_listener.c b/lib/nfc/protocols/slix/slix_listener.c new file mode 100644 index 000000000..204be5ab9 --- /dev/null +++ b/lib/nfc/protocols/slix/slix_listener.c @@ -0,0 +1,79 @@ +#include "slix_listener_i.h" + +#include +#include + +#define TAG "SlixListener" + +#define SLIX_LISTENER_BUF_SIZE (64U) + +static SlixListener* slix_listener_alloc(Iso15693_3Listener* iso15693_3_listener, SlixData* data) { + furi_assert(iso15693_3_listener); + + SlixListener* instance = malloc(sizeof(SlixListener)); + instance->iso15693_3_listener = iso15693_3_listener; + instance->data = data; + + instance->tx_buffer = bit_buffer_alloc(SLIX_LISTENER_BUF_SIZE); + + instance->slix_event.data = &instance->slix_event_data; + instance->generic_event.protocol = NfcProtocolSlix; + instance->generic_event.instance = instance; + instance->generic_event.event_data = &instance->slix_event; + + slix_listener_init_iso15693_3_extensions(instance); + + return instance; +} + +static void slix_listener_free(SlixListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + furi_assert(instance->tx_buffer); + + bit_buffer_free(instance->tx_buffer); + free(instance); +} + +static void + slix_listener_set_callback(SlixListener* instance, NfcGenericCallback callback, void* context) { + furi_assert(instance); + + instance->callback = callback; + instance->context = context; +} + +static const SlixData* slix_listener_get_data(SlixListener* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +static NfcCommand slix_listener_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolIso15693_3); + furi_assert(event.event_data); + + SlixListener* instance = context; + Iso15693_3ListenerEvent* iso15693_3_event = event.event_data; + BitBuffer* rx_buffer = iso15693_3_event->data->buffer; + NfcCommand command = NfcCommandContinue; + + if(iso15693_3_event->type == Iso15693_3ListenerEventTypeCustomCommand) { + const SlixError error = slix_listener_process_request(instance, rx_buffer); + if(error == SlixErrorWrongPassword) { + command = NfcCommandStop; + } + } + + return command; +} + +const NfcListenerBase nfc_listener_slix = { + .alloc = (NfcListenerAlloc)slix_listener_alloc, + .free = (NfcListenerFree)slix_listener_free, + .set_callback = (NfcListenerSetCallback)slix_listener_set_callback, + .get_data = (NfcListenerGetData)slix_listener_get_data, + .run = (NfcListenerRun)slix_listener_run, +}; diff --git a/lib/nfc/protocols/slix/slix_listener.h b/lib/nfc/protocols/slix/slix_listener.h new file mode 100644 index 000000000..7b8518a5b --- /dev/null +++ b/lib/nfc/protocols/slix/slix_listener.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +#include "slix.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct SlixListener SlixListener; + +typedef enum { + SlixListenerEventTypeFieldOff, + SlixListenerEventTypeCustomCommand, +} SlixListenerEventType; + +typedef struct { + BitBuffer* buffer; +} SlixListenerEventData; + +typedef struct { + SlixListenerEventType type; + SlixListenerEventData* data; +} SlixListenerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/slix/slix_listener_defs.h b/lib/nfc/protocols/slix/slix_listener_defs.h new file mode 100644 index 000000000..0598090c4 --- /dev/null +++ b/lib/nfc/protocols/slix/slix_listener_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcListenerBase nfc_listener_slix; diff --git a/lib/nfc/protocols/slix/slix_listener_i.c b/lib/nfc/protocols/slix/slix_listener_i.c new file mode 100644 index 000000000..dfcb6c880 --- /dev/null +++ b/lib/nfc/protocols/slix/slix_listener_i.c @@ -0,0 +1,617 @@ +#include "slix_listener_i.h" + +#include + +#include + +#define TAG "SlixListener" + +typedef SlixError (*SlixRequestHandler)( + SlixListener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags); + +// Helper functions + +static bool + slix_listener_is_password_lock_enabled(SlixListener* instance, SlixPasswordType password_type) { + return !instance->session_state.password_match[password_type]; +} + +static SlixPasswordType slix_listener_get_password_type_by_id(uint8_t id) { + uint32_t type; + + for(type = 0; type < SlixPasswordTypeCount; ++type) { + if(id >> type == 0x01U) break; + } + + return type; +} + +static SlixPassword + slix_listener_unxor_password(const SlixPassword password_xored, uint16_t random) { + return password_xored ^ ((SlixPassword)random << 16 | random); +} + +static SlixError slix_listener_set_password( + SlixListener* instance, + SlixPasswordType password_type, + SlixPassword password) { + SlixError error = SlixErrorNone; + + do { + if(password_type >= SlixPasswordTypeCount) { + error = SlixErrorInternal; + break; + } + + SlixData* slix_data = instance->data; + + if(!slix_type_supports_password(slix_get_type(slix_data), password_type)) { + error = SlixErrorNotSupported; + break; + } + + SlixListenerSessionState* session_state = &instance->session_state; + session_state->password_match[password_type] = + (password == slix_get_password(slix_data, password_type)); + + if(!session_state->password_match[password_type]) { + error = SlixErrorWrongPassword; + break; + } + } while(false); + + return error; +} + +static SlixError slix_listener_write_password( + SlixListener* instance, + SlixPasswordType password_type, + SlixPassword password) { + SlixError error = SlixErrorNone; + + do { + if(password_type >= SlixPasswordTypeCount) { + error = SlixErrorInternal; + break; + } + + SlixData* slix_data = instance->data; + + if(!slix_type_supports_password(slix_get_type(slix_data), password_type)) { + error = SlixErrorNotSupported; + break; + } + + SlixListenerSessionState* session_state = &instance->session_state; + + if(session_state->password_match[password_type]) { + // TODO FL-3634: check for password lock + slix_set_password(slix_data, password_type, password); + // Require another SET_PASSWORD command with the new password + session_state->password_match[password_type] = false; + } else { + error = SlixErrorWrongPassword; + break; + } + } while(false); + + return error; +} + +// Custom SLIX request handlers +static SlixError slix_listener_default_handler( + SlixListener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(instance); + UNUSED(data); + UNUSED(data_size); + UNUSED(flags); + + // Empty placeholder handler + return SlixErrorNotSupported; +} + +static SlixError slix_listener_get_nxp_system_info_handler( + SlixListener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(data); + UNUSED(data_size); + UNUSED(flags); + + const SlixData* slix_data = instance->data; + const Iso15693_3Data* iso15693_data = instance->data->iso15693_3_data; + + const SlixProtection* protection = &slix_data->system_info.protection; + bit_buffer_append_byte(instance->tx_buffer, protection->pointer); + bit_buffer_append_byte(instance->tx_buffer, protection->condition); + + uint8_t lock_bits = 0; + if(iso15693_data->settings.lock_bits.dsfid) { + lock_bits |= SLIX_LOCK_BITS_DSFID; + } + if(iso15693_data->settings.lock_bits.afi) { + lock_bits |= SLIX_LOCK_BITS_AFI; + } + if(slix_data->system_info.lock_bits.eas) { + lock_bits |= SLIX_LOCK_BITS_EAS; + } + if(slix_data->system_info.lock_bits.ppl) { + lock_bits |= SLIX_LOCK_BITS_PPL; + } + bit_buffer_append_byte(instance->tx_buffer, lock_bits); + + const uint32_t feature_flags = SLIX2_FEATURE_FLAGS; + bit_buffer_append_bytes(instance->tx_buffer, (uint8_t*)&feature_flags, sizeof(uint32_t)); + + return SlixErrorNone; +} + +static SlixError slix_listener_get_random_number_handler( + SlixListener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(data); + UNUSED(data_size); + UNUSED(flags); + + SlixListenerSessionState* session_state = &instance->session_state; + session_state->random = furi_hal_random_get(); + bit_buffer_append_bytes( + instance->tx_buffer, (uint8_t*)&session_state->random, sizeof(uint16_t)); + + return SlixErrorNone; +} + +static SlixError slix_listener_set_password_handler( + SlixListener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(flags); + SlixError error = SlixErrorNone; + + do { +#pragma pack(push, 1) + typedef struct { + uint8_t password_id; + SlixPassword password_xored; + } SlixSetPasswordRequestLayout; +#pragma pack(pop) + + if(data_size != sizeof(SlixSetPasswordRequestLayout)) { + error = SlixErrorFormat; + break; + } + + const SlixSetPasswordRequestLayout* request = (const SlixSetPasswordRequestLayout*)data; + const SlixPasswordType password_type = + slix_listener_get_password_type_by_id(request->password_id); + const SlixPassword password_received = + slix_listener_unxor_password(request->password_xored, instance->session_state.random); + + error = slix_listener_set_password(instance, password_type, password_received); + if(error != SlixErrorNone) break; + + if(password_type == SlixPasswordTypePrivacy) { + slix_set_privacy_mode(instance->data, false); + } + } while(false); + + return error; +} + +static SlixError slix_listener_write_password_handler( + SlixListener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(flags); + SlixError error = SlixErrorNone; + + do { +#pragma pack(push, 1) + typedef struct { + uint8_t password_id; + SlixPassword password; + } SlixWritePasswordRequestLayout; +#pragma pack(pop) + + if(data_size != sizeof(SlixWritePasswordRequestLayout)) { + error = SlixErrorFormat; + break; + } + + const SlixWritePasswordRequestLayout* request = + (const SlixWritePasswordRequestLayout*)data; + const SlixPasswordType password_type = + slix_listener_get_password_type_by_id(request->password_id); + + error = slix_listener_write_password(instance, password_type, request->password); + if(error != SlixErrorNone) break; + + } while(false); + + return error; +} + +static SlixError slix_listener_protect_page_handler( + SlixListener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(flags); + SlixError error = SlixErrorNone; + + do { + typedef struct { + uint8_t pointer; + uint8_t condition; + } SlixProtectPageRequestLayout; + + if(data_size != sizeof(SlixProtectPageRequestLayout)) { + error = SlixErrorFormat; + break; + } + + SlixData* slix_data = instance->data; + + if(slix_data->system_info.lock_bits.ppl) { + error = SlixErrorInternal; + break; + } + + const SlixListenerSessionState* session_state = &instance->session_state; + if(!session_state->password_match[SlixPasswordTypeRead] || + !session_state->password_match[SlixPasswordTypeWrite]) { + error = SlixErrorInternal; + break; + } + + const SlixProtectPageRequestLayout* request = (const SlixProtectPageRequestLayout*)data; + + if(request->pointer >= SLIX_COUNTER_BLOCK_NUM) { + error = SlixErrorInternal; + break; + } + + SlixProtection* protection = &slix_data->system_info.protection; + + protection->pointer = request->pointer; + protection->condition = request->condition; + } while(false); + + return error; +} + +static SlixError slix_listener_enable_privacy_handler( + SlixListener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(flags); + SlixError error = SlixErrorNone; + + do { + typedef struct { + SlixPassword password_xored; + } SlixEnablePrivacyRequestLayout; + + if(data_size != sizeof(SlixEnablePrivacyRequestLayout)) { + error = SlixErrorFormat; + break; + } + + const SlixEnablePrivacyRequestLayout* request = + (const SlixEnablePrivacyRequestLayout*)data; + + const SlixPassword password_received = + slix_listener_unxor_password(request->password_xored, instance->session_state.random); + + error = slix_listener_set_password(instance, SlixPasswordTypePrivacy, password_received); + if(error != SlixErrorNone) break; + + slix_set_privacy_mode(instance->data, true); + } while(false); + + return error; +} + +static SlixError slix_listener_read_signature_handler( + SlixListener* instance, + const uint8_t* data, + size_t data_size, + uint8_t flags) { + UNUSED(data); + UNUSED(data_size); + UNUSED(flags); + + bit_buffer_append_bytes(instance->tx_buffer, instance->data->signature, sizeof(SlixSignature)); + return SlixErrorNone; +} + +// Custom SLIX commands handler table +static const SlixRequestHandler slix_request_handler_table[SLIX_CMD_CUSTOM_COUNT] = { + slix_listener_default_handler, // SLIX_CMD_SET_EAS (0xA2U) + slix_listener_default_handler, // SLIX_CMD_RESET_EAS (0xA3U) + slix_listener_default_handler, // SLIX_CMD_LOCK_EAS (0xA4U) + slix_listener_default_handler, // SLIX_CMD_EAS_ALARM (0xA5U) + slix_listener_default_handler, // SLIX_CMD_PASSWORD_PROTECT_EAS_AFI (0xA6U) + slix_listener_default_handler, // SLIX_CMD_WRITE_EAS_ID (0xA7U) + slix_listener_default_handler, // UNUSED (0xA8U) + slix_listener_default_handler, // UNUSED (0xA9U) + slix_listener_default_handler, // UNUSED (0xAAU) + slix_listener_get_nxp_system_info_handler, + slix_listener_default_handler, // UNUSED (0xACU) + slix_listener_default_handler, // UNUSED (0xADU) + slix_listener_default_handler, // UNUSED (0xAEU) + slix_listener_default_handler, // UNUSED (0xAFU) + slix_listener_default_handler, // SLIX_CMD_INVENTORY_PAGE_READ (0xB0U) + slix_listener_default_handler, // SLIX_CMD_INVENTORY_PAGE_READ_FAST (0xB1U) + slix_listener_get_random_number_handler, + slix_listener_set_password_handler, + slix_listener_write_password_handler, + slix_listener_default_handler, // SLIX_CMD_64_BIT_PASSWORD_PROTECTION (0xB5U) + slix_listener_protect_page_handler, + slix_listener_default_handler, // SLIX_CMD_LOCK_PAGE_PROTECTION_CONDITION (0xB7U) + slix_listener_default_handler, // UNUSED (0xB8U) + slix_listener_default_handler, // SLIX_CMD_DESTROY (0xB9U) + slix_listener_enable_privacy_handler, + slix_listener_default_handler, // UNUSED (0xBBU) + slix_listener_default_handler, // SLIX_CMD_STAY_QUIET_PERSISTENT (0xBCU) + slix_listener_read_signature_handler, +}; + +// ISO15693-3 Protocol extension handlers + +static Iso15693_3Error + slix_listener_iso15693_3_inventory_extension_handler(SlixListener* instance, va_list args) { + UNUSED(args); + + return instance->data->privacy ? Iso15693_3ErrorIgnore : Iso15693_3ErrorNone; +} + +static Iso15693_3Error + slix_iso15693_3_read_block_extension_handler(SlixListener* instance, va_list args) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + const uint32_t block_num = va_arg(args, uint32_t); + // SLIX Counter has no read protection + if(block_num == SLIX_COUNTER_BLOCK_NUM) break; + + if(slix_is_block_protected(instance->data, SlixPasswordTypeRead, block_num)) { + if(slix_listener_is_password_lock_enabled(instance, SlixPasswordTypeRead)) { + error = Iso15693_3ErrorInternal; + break; + } + } + } while(false); + + return error; +} + +static Iso15693_3Error + slix_listener_iso15693_3_write_block_extension_handler(SlixListener* instance, va_list args) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + const uint32_t block_num = va_arg(args, uint32_t); + + if(block_num == SLIX_COUNTER_BLOCK_NUM) { + const uint32_t counter = *(va_arg(args, uint32_t*)); + if(counter == 0x00000001U) { + if(slix_is_counter_increment_protected(instance->data) && + slix_listener_is_password_lock_enabled(instance, SlixPasswordTypeRead)) { + error = Iso15693_3ErrorInternal; + break; + } + slix_increment_counter(instance->data); + error = Iso15693_3ErrorFullyHandled; + break; + } + } else if(slix_is_block_protected(instance->data, SlixPasswordTypeRead, block_num)) { + if(slix_listener_is_password_lock_enabled(instance, SlixPasswordTypeRead)) { + error = Iso15693_3ErrorInternal; + break; + } + } + + if(slix_is_block_protected(instance->data, SlixPasswordTypeWrite, block_num)) { + if(slix_listener_is_password_lock_enabled(instance, SlixPasswordTypeWrite)) { + error = Iso15693_3ErrorInternal; + break; + } + } + + } while(false); + + return error; +} + +static Iso15693_3Error + slix_listener_iso15693_3_lock_block_extension_handler(SlixListener* instance, va_list args) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + do { + const uint32_t block_num = va_arg(args, uint32_t); + + // SLIX counter cannot be locked + if(block_num == SLIX_COUNTER_BLOCK_NUM) { + error = Iso15693_3ErrorInternal; + break; + } + + if(slix_is_block_protected(instance->data, SlixPasswordTypeRead, block_num)) { + if(slix_listener_is_password_lock_enabled(instance, SlixPasswordTypeRead)) { + error = Iso15693_3ErrorInternal; + break; + } + } + + if(slix_is_block_protected(instance->data, SlixPasswordTypeWrite, block_num)) { + if(slix_listener_is_password_lock_enabled(instance, SlixPasswordTypeWrite)) { + error = Iso15693_3ErrorInternal; + break; + } + } + + } while(false); + + return error; +} + +static Iso15693_3Error slix_listener_iso15693_3_read_multi_block_extension_handler( + SlixListener* instance, + va_list args) { + Iso15693_3Error error = Iso15693_3ErrorNone; + + const uint32_t block_index_start = va_arg(args, uint32_t); + const uint32_t block_index_end = va_arg(args, uint32_t); + + for(uint32_t i = block_index_start; i <= block_index_end; ++i) { + // SLIX Counter has no read protection + if(i == SLIX_COUNTER_BLOCK_NUM) continue; + + if(slix_is_block_protected(instance->data, SlixPasswordTypeRead, i)) { + if(slix_listener_is_password_lock_enabled(instance, SlixPasswordTypeRead)) { + error = Iso15693_3ErrorInternal; + break; + } + } + } + + return error; +} + +static Iso15693_3Error slix_listener_iso15693_3_write_multi_block_extension_handler( + SlixListener* instance, + va_list args) { + UNUSED(instance); + UNUSED(args); + // No mention of this command in SLIX docs, assuming not supported + return Iso15693_3ErrorNotSupported; +} + +static Iso15693_3Error slix_listener_iso15693_3_write_lock_afi_extension_handler( + SlixListener* instance, + va_list args) { + UNUSED(args); + + return slix_listener_is_password_lock_enabled(instance, SlixPasswordTypeEasAfi) ? + Iso15693_3ErrorInternal : + Iso15693_3ErrorNone; +} + +// Extended ISO15693-3 standard commands handler table (NULL = no extension) +static const Iso15693_3ExtensionHandlerTable slix_iso15693_extension_handler_table = { + .mandatory = + { + (Iso15693_3ExtensionHandler)slix_listener_iso15693_3_inventory_extension_handler, + (Iso15693_3ExtensionHandler)NULL // ISO15693_3_CMD_STAY_QUIET (0x02U) + }, + .optional = + { + (Iso15693_3ExtensionHandler)slix_iso15693_3_read_block_extension_handler, + (Iso15693_3ExtensionHandler)slix_listener_iso15693_3_write_block_extension_handler, + (Iso15693_3ExtensionHandler)slix_listener_iso15693_3_lock_block_extension_handler, + (Iso15693_3ExtensionHandler)slix_listener_iso15693_3_read_multi_block_extension_handler, + (Iso15693_3ExtensionHandler) + slix_listener_iso15693_3_write_multi_block_extension_handler, + (Iso15693_3ExtensionHandler)NULL, // ISO15693_3_CMD_SELECT (0x25U) + (Iso15693_3ExtensionHandler)NULL, // ISO15693_3_CMD_RESET_TO_READY (0x26U) + (Iso15693_3ExtensionHandler)slix_listener_iso15693_3_write_lock_afi_extension_handler, + (Iso15693_3ExtensionHandler)slix_listener_iso15693_3_write_lock_afi_extension_handler, + (Iso15693_3ExtensionHandler)NULL, // ISO15693_3_CMD_WRITE_DSFID (0x29U) + (Iso15693_3ExtensionHandler)NULL, // ISO15693_3_CMD_LOCK_DSFID (0x2AU) + (Iso15693_3ExtensionHandler)NULL, // ISO15693_3_CMD_GET_SYS_INFO (0x2BU) + (Iso15693_3ExtensionHandler)NULL, // ISO15693_3_CMD_GET_BLOCKS_SECURITY (0x2CU) + }, +}; + +SlixError slix_listener_init_iso15693_3_extensions(SlixListener* instance) { + iso15693_3_listener_set_extension_handler_table( + instance->iso15693_3_listener, &slix_iso15693_extension_handler_table, instance); + return SlixErrorNone; +} + +SlixError slix_listener_process_request(SlixListener* instance, const BitBuffer* rx_buffer) { + SlixError error = SlixErrorNone; + + do { + typedef struct { + uint8_t flags; + uint8_t command; + uint8_t manufacturer; + uint8_t data[]; + } SlixRequestLayout; + + const size_t buf_size = bit_buffer_get_size_bytes(rx_buffer); + + if(buf_size < sizeof(SlixRequestLayout)) { + error = SlixErrorFormat; + break; + } + + const SlixRequestLayout* request = + (const SlixRequestLayout*)bit_buffer_get_data(rx_buffer); + + const bool addressed_mode = instance->iso15693_3_listener->session_state.addressed; + + const size_t uid_field_size = addressed_mode ? ISO15693_3_UID_SIZE : 0; + const size_t buf_size_min = sizeof(SlixRequestLayout) + uid_field_size; + + if(buf_size < buf_size_min) { + error = SlixErrorFormat; + break; + } + + if(addressed_mode) { + if(!iso15693_3_is_equal_uid(instance->data->iso15693_3_data, request->data)) { + error = SlixErrorUidMismatch; + break; + } + } + + const uint8_t command = request->command; + const bool is_valid_slix_command = command >= SLIX_CMD_CUSTOM_START && + command < SLIX_CMD_CUSTOM_END; + if(!is_valid_slix_command) { + error = SlixErrorNotSupported; + break; + } + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_RESP_FLAG_NONE); + + const uint8_t* request_data = &request->data[uid_field_size]; + const size_t request_data_size = buf_size - buf_size_min; + + SlixRequestHandler handler = slix_request_handler_table[command - SLIX_CMD_CUSTOM_START]; + error = handler(instance, request_data, request_data_size, request->flags); + + // It's a trick! Send no reply. + if(error == SlixErrorFormat || error == SlixErrorWrongPassword || + error == SlixErrorNotSupported) + break; + + if(error != SlixErrorNone) { + bit_buffer_reset(instance->tx_buffer); + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_RESP_FLAG_ERROR); + bit_buffer_append_byte(instance->tx_buffer, ISO15693_3_RESP_ERROR_UNKNOWN); + } + + const Iso15693_3Error iso15693_error = + iso15693_3_listener_send_frame(instance->iso15693_3_listener, instance->tx_buffer); + error = slix_process_iso15693_3_error(iso15693_error); + } while(false); + + return error; +} diff --git a/lib/nfc/protocols/slix/slix_listener_i.h b/lib/nfc/protocols/slix/slix_listener_i.h new file mode 100644 index 000000000..ce059c5a6 --- /dev/null +++ b/lib/nfc/protocols/slix/slix_listener_i.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +#include "slix_listener.h" +#include "slix_i.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint16_t random; + bool password_match[SlixPasswordTypeCount]; +} SlixListenerSessionState; + +struct SlixListener { + Iso15693_3Listener* iso15693_3_listener; + SlixData* data; + SlixListenerSessionState session_state; + + BitBuffer* tx_buffer; + + NfcGenericEvent generic_event; + SlixListenerEvent slix_event; + SlixListenerEventData slix_event_data; + NfcGenericCallback callback; + void* context; +}; + +SlixError slix_listener_init_iso15693_3_extensions(SlixListener* instance); + +SlixError slix_listener_process_request(SlixListener* instance, const BitBuffer* rx_buffer); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/slix/slix_poller.c b/lib/nfc/protocols/slix/slix_poller.c new file mode 100644 index 000000000..9731bfc6b --- /dev/null +++ b/lib/nfc/protocols/slix/slix_poller.c @@ -0,0 +1,159 @@ +#include "slix_poller_i.h" + +#include + +#include + +#define TAG "SlixPoller" + +#define SLIX_POLLER_BUF_SIZE (64U) + +typedef NfcCommand (*SlixPollerStateHandler)(SlixPoller* instance); + +const SlixData* slix_poller_get_data(SlixPoller* instance) { + furi_assert(instance); + + return instance->data; +} + +static SlixPoller* slix_poller_alloc(Iso15693_3Poller* iso15693_3_poller) { + SlixPoller* instance = malloc(sizeof(SlixPoller)); + instance->iso15693_3_poller = iso15693_3_poller; + instance->data = slix_alloc(); + instance->tx_buffer = bit_buffer_alloc(SLIX_POLLER_BUF_SIZE); + instance->rx_buffer = bit_buffer_alloc(SLIX_POLLER_BUF_SIZE); + + instance->slix_event.data = &instance->slix_event_data; + + instance->general_event.protocol = NfcProtocolSlix; + instance->general_event.event_data = &instance->slix_event; + instance->general_event.instance = instance; + + return instance; +} + +static void slix_poller_free(SlixPoller* instance) { + furi_assert(instance); + + slix_free(instance->data); + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + free(instance); +} + +static NfcCommand slix_poller_handler_idle(SlixPoller* instance) { + iso15693_3_copy( + instance->data->iso15693_3_data, iso15693_3_poller_get_data(instance->iso15693_3_poller)); + + instance->poller_state = SlixPollerStateGetNxpSysInfo; + return NfcCommandContinue; +} + +static NfcCommand slix_poller_handler_get_nfc_system_info(SlixPoller* instance) { + instance->error = + slix_poller_async_get_nxp_system_info(instance, &instance->data->system_info); + if(instance->error == SlixErrorNone) { + instance->poller_state = SlixPollerStateReadSignature; + } else { + instance->poller_state = SlixPollerStateError; + } + + return NfcCommandContinue; +} + +static NfcCommand slix_poller_handler_read_signature(SlixPoller* instance) { + instance->error = slix_poller_async_read_signature(instance, &instance->data->signature); + if(instance->error == SlixErrorNone) { + instance->poller_state = SlixPollerStateReady; + } else { + instance->poller_state = SlixPollerStateError; + } + + return NfcCommandContinue; +} + +static NfcCommand slix_poller_handler_error(SlixPoller* instance) { + instance->slix_event_data.error = instance->error; + instance->slix_event.type = SlixPollerEventTypeError; + NfcCommand command = instance->callback(instance->general_event, instance->context); + instance->poller_state = SlixPollerStateIdle; + return command; +} + +static NfcCommand slix_poller_handler_ready(SlixPoller* instance) { + instance->slix_event.type = SlixPollerEventTypeReady; + NfcCommand command = instance->callback(instance->general_event, instance->context); + return command; +} + +static const SlixPollerStateHandler slix_poller_state_handler[SlixPollerStateNum] = { + [SlixPollerStateIdle] = slix_poller_handler_idle, + [SlixPollerStateError] = slix_poller_handler_error, + [SlixPollerStateGetNxpSysInfo] = slix_poller_handler_get_nfc_system_info, + [SlixPollerStateReadSignature] = slix_poller_handler_read_signature, + [SlixPollerStateReady] = slix_poller_handler_ready, +}; + +static void + slix_poller_set_callback(SlixPoller* instance, NfcGenericCallback callback, void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +static NfcCommand slix_poller_run(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso15693_3); + + SlixPoller* instance = context; + furi_assert(instance); + furi_assert(instance->callback); + + Iso15693_3PollerEvent* iso15693_3_event = event.event_data; + furi_assert(iso15693_3_event); + + NfcCommand command = NfcCommandContinue; + + if(iso15693_3_event->type == Iso15693_3PollerEventTypeReady) { + command = slix_poller_state_handler[instance->poller_state](instance); + } else if(iso15693_3_event->type == Iso15693_3PollerEventTypeError) { + instance->slix_event.type = SlixPollerEventTypeError; + command = instance->callback(instance->general_event, instance->context); + } + + return command; +} + +static bool slix_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(event.protocol == NfcProtocolIso15693_3); + + SlixPoller* instance = context; + furi_assert(instance); + + const Iso15693_3PollerEvent* iso15693_3_event = event.event_data; + furi_assert(iso15693_3_event); + iso15693_3_copy( + instance->data->iso15693_3_data, iso15693_3_poller_get_data(instance->iso15693_3_poller)); + + bool protocol_detected = false; + + if(iso15693_3_event->type == Iso15693_3PollerEventTypeReady) { + if(slix_get_type(instance->data) < SlixTypeCount) { + SlixSystemInfo system_info = {}; + SlixError error = slix_poller_async_get_nxp_system_info(instance, &system_info); + protocol_detected = (error == SlixErrorNone); + } + } + + return protocol_detected; +} + +const NfcPollerBase nfc_poller_slix = { + .alloc = (NfcPollerAlloc)slix_poller_alloc, + .free = (NfcPollerFree)slix_poller_free, + .set_callback = (NfcPollerSetCallback)slix_poller_set_callback, + .run = (NfcPollerRun)slix_poller_run, + .detect = (NfcPollerDetect)slix_poller_detect, + .get_data = (NfcPollerGetData)slix_poller_get_data, +}; diff --git a/lib/nfc/protocols/slix/slix_poller.h b/lib/nfc/protocols/slix/slix_poller.h new file mode 100644 index 000000000..f4c7214de --- /dev/null +++ b/lib/nfc/protocols/slix/slix_poller.h @@ -0,0 +1,29 @@ +#pragma once + +#include "slix.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct SlixPoller SlixPoller; + +typedef enum { + SlixPollerEventTypeError, + SlixPollerEventTypeReady, +} SlixPollerEventType; + +typedef struct { + SlixError error; +} SlixPollerEventData; + +typedef struct { + SlixPollerEventType type; + SlixPollerEventData* data; +} SlixPollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/slix/slix_poller_defs.h b/lib/nfc/protocols/slix/slix_poller_defs.h new file mode 100644 index 000000000..df8f298f0 --- /dev/null +++ b/lib/nfc/protocols/slix/slix_poller_defs.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +extern const NfcPollerBase nfc_poller_slix; diff --git a/lib/nfc/protocols/slix/slix_poller_i.c b/lib/nfc/protocols/slix/slix_poller_i.c new file mode 100644 index 000000000..a36e7694a --- /dev/null +++ b/lib/nfc/protocols/slix/slix_poller_i.c @@ -0,0 +1,69 @@ +#include "slix_poller_i.h" + +#include + +#include "slix_i.h" + +#define TAG "SlixPoller" + +static void slix_poller_prepare_request(SlixPoller* instance, uint8_t command) { + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + bit_buffer_append_byte( + instance->tx_buffer, + ISO15693_3_REQ_FLAG_SUBCARRIER_1 | ISO15693_3_REQ_FLAG_DATA_RATE_HI | + ISO15693_3_REQ_FLAG_T4_ADDRESSED); + bit_buffer_append_byte(instance->tx_buffer, command); + bit_buffer_append_byte(instance->tx_buffer, SLIX_NXP_MANUFACTURER_CODE); + + iso15693_3_append_uid(instance->data->iso15693_3_data, instance->tx_buffer); +} + +SlixError slix_poller_send_frame( + SlixPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + + const Iso15693_3Error iso15693_3_error = + iso15693_3_poller_send_frame(instance->iso15693_3_poller, tx_buffer, rx_buffer, fwt); + return slix_process_iso15693_3_error(iso15693_3_error); +} + +SlixError slix_poller_async_get_nxp_system_info(SlixPoller* instance, SlixSystemInfo* data) { + furi_assert(instance); + furi_assert(data); + + slix_poller_prepare_request(instance, SLIX_CMD_GET_NXP_SYSTEM_INFORMATION); + + SlixError error = SlixErrorNone; + + do { + error = slix_poller_send_frame( + instance, instance->tx_buffer, instance->rx_buffer, ISO15693_3_FDT_POLL_FC); + if(error != SlixErrorNone) break; + error = slix_get_nxp_system_info_response_parse(instance->data, instance->rx_buffer); + } while(false); + + return error; +} + +SlixError slix_poller_async_read_signature(SlixPoller* instance, SlixSignature* data) { + furi_assert(instance); + furi_assert(data); + + slix_poller_prepare_request(instance, SLIX_CMD_READ_SIGNATURE); + + SlixError error = SlixErrorNone; + + do { + error = slix_poller_send_frame( + instance, instance->tx_buffer, instance->rx_buffer, ISO15693_3_FDT_POLL_FC * 2); + if(error != SlixErrorNone) break; + error = slix_read_signature_response_parse(instance->data->signature, instance->rx_buffer); + } while(false); + + return error; +} diff --git a/lib/nfc/protocols/slix/slix_poller_i.h b/lib/nfc/protocols/slix/slix_poller_i.h new file mode 100644 index 000000000..c6a8a3c33 --- /dev/null +++ b/lib/nfc/protocols/slix/slix_poller_i.h @@ -0,0 +1,48 @@ +#pragma once + +#include + +#include "slix_poller.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + SlixPollerStateIdle, + SlixPollerStateGetNxpSysInfo, + SlixPollerStateReadSignature, + SlixPollerStateReady, + SlixPollerStateError, + SlixPollerStateNum, +} SlixPollerState; + +struct SlixPoller { + Iso15693_3Poller* iso15693_3_poller; + SlixData* data; + SlixPollerState poller_state; + SlixError error; + + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + + SlixPollerEventData slix_event_data; + SlixPollerEvent slix_event; + NfcGenericEvent general_event; + NfcGenericCallback callback; + void* context; +}; + +SlixError slix_poller_send_frame( + SlixPoller* instance, + const BitBuffer* tx_data, + BitBuffer* rx_data, + uint32_t fwt); + +SlixError slix_poller_async_get_nxp_system_info(SlixPoller* instance, SlixSystemInfo* data); + +SlixError slix_poller_async_read_signature(SlixPoller* instance, SlixSignature* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/st25tb/st25tb.c b/lib/nfc/protocols/st25tb/st25tb.c new file mode 100644 index 000000000..d3fac7eea --- /dev/null +++ b/lib/nfc/protocols/st25tb/st25tb.c @@ -0,0 +1,234 @@ +#include "st25tb.h" + +#include "core/string.h" +#include "flipper_format.h" +#include + +#include +#include + +#define ST25TB_PROTOCOL_NAME "ST25TB" +#define ST25TB_TYPE_KEY "ST25TB Type" +#define ST25TB_BLOCK_KEY "Block %d" +#define ST25TB_SYSTEM_BLOCK_KEY "System OTP Block" + +typedef struct { + uint8_t blocks_total; + bool has_otp; + const char* full_name; + const char* type_name; +} St25tbFeatures; + +static const St25tbFeatures st25tb_features[St25tbTypeNum] = { + [St25tbType512At] = + { + .blocks_total = 16, + .has_otp = false, + .full_name = "ST25TB512-AT/SRI512", + .type_name = "512AT", + }, + [St25tbType512Ac] = + { + .blocks_total = 16, + .has_otp = true, + .full_name = "ST25TB512-AC/SRT512", + .type_name = "512AC", + }, + [St25tbTypeX512] = + { + .blocks_total = 16, + .has_otp = true, + .full_name = "SRIX512", + .type_name = "X512", + }, + [St25tbType02k] = + { + .blocks_total = 64, + .has_otp = true, + .full_name = "ST25TB02K/SRI2K", + .type_name = "2K", + }, + [St25tbType04k] = + { + .blocks_total = 128, + .has_otp = true, + .full_name = "ST25TB04K/SRI4K", + .type_name = "4K", + }, + [St25tbTypeX4k] = + { + .blocks_total = 128, + .has_otp = true, + .full_name = "SRIX4K", + .type_name = "X4K", + }, +}; + +const NfcDeviceBase nfc_device_st25tb = { + .protocol_name = ST25TB_PROTOCOL_NAME, + .alloc = (NfcDeviceAlloc)st25tb_alloc, + .free = (NfcDeviceFree)st25tb_free, + .reset = (NfcDeviceReset)st25tb_reset, + .copy = (NfcDeviceCopy)st25tb_copy, + .verify = (NfcDeviceVerify)st25tb_verify, + .load = (NfcDeviceLoad)st25tb_load, + .save = (NfcDeviceSave)st25tb_save, + .is_equal = (NfcDeviceEqual)st25tb_is_equal, + .get_name = (NfcDeviceGetName)st25tb_get_device_name, + .get_uid = (NfcDeviceGetUid)st25tb_get_uid, + .set_uid = (NfcDeviceSetUid)st25tb_set_uid, + .get_base_data = (NfcDeviceGetBaseData)st25tb_get_base_data, +}; + +St25tbData* st25tb_alloc() { + St25tbData* data = malloc(sizeof(St25tbData)); + return data; +} + +void st25tb_free(St25tbData* data) { + furi_assert(data); + + free(data); +} + +void st25tb_reset(St25tbData* data) { + memset(data, 0, sizeof(St25tbData)); +} + +void st25tb_copy(St25tbData* data, const St25tbData* other) { + furi_assert(data); + furi_assert(other); + + *data = *other; +} + +bool st25tb_verify(St25tbData* data, const FuriString* device_type) { + UNUSED(data); + return furi_string_equal_str(device_type, ST25TB_PROTOCOL_NAME); +} + +bool st25tb_load(St25tbData* data, FlipperFormat* ff, uint32_t version) { + furi_assert(data); + + bool parsed = false; + + FuriString* temp_str = furi_string_alloc(); + + do { + if(version < NFC_UNIFIED_FORMAT_VERSION) break; + if(!flipper_format_read_string(ff, ST25TB_TYPE_KEY, temp_str)) break; + + bool type_parsed = false; + for(size_t i = 0; i < St25tbTypeNum; i++) { + if(furi_string_equal_str(temp_str, st25tb_features[i].type_name)) { + data->type = i; + type_parsed = true; + } + } + if(!type_parsed) break; + + bool blocks_parsed = true; + for(uint8_t block = 0; block < st25tb_features[data->type].blocks_total; block++) { + furi_string_printf(temp_str, ST25TB_BLOCK_KEY, block); + if(!flipper_format_read_hex( + ff, furi_string_get_cstr(temp_str), (uint8_t*)&data->blocks[block], 4)) { + blocks_parsed = false; + break; + } + } + if(!blocks_parsed) break; + + if(!flipper_format_read_hex( + ff, ST25TB_SYSTEM_BLOCK_KEY, (uint8_t*)&data->system_otp_block, 4)) + break; + + parsed = true; + } while(false); + + furi_string_free(temp_str); + + return parsed; +} + +bool st25tb_save(const St25tbData* data, FlipperFormat* ff) { + furi_assert(data); + + FuriString* temp_str = furi_string_alloc(); + bool saved = false; + + do { + if(!flipper_format_write_comment_cstr(ff, ST25TB_PROTOCOL_NAME " specific data")) break; + if(!flipper_format_write_string_cstr( + ff, ST25TB_TYPE_KEY, st25tb_features[data->type].type_name)) + break; + + bool blocks_saved = true; + for(uint8_t block = 0; block < st25tb_features[data->type].blocks_total; block++) { + furi_string_printf(temp_str, ST25TB_BLOCK_KEY, block); + if(!flipper_format_write_hex( + ff, furi_string_get_cstr(temp_str), (uint8_t*)&data->blocks[block], 4)) { + blocks_saved = false; + break; + } + } + if(!blocks_saved) break; + + if(!flipper_format_write_hex( + ff, ST25TB_SYSTEM_BLOCK_KEY, (uint8_t*)&data->system_otp_block, 4)) + break; + + saved = true; + } while(false); + + furi_string_free(temp_str); + return saved; +} + +bool st25tb_is_equal(const St25tbData* data, const St25tbData* other) { + furi_assert(data); + furi_assert(other); + + return memcmp(data, other, sizeof(St25tbData)) == 0; +} + +uint8_t st25tb_get_block_count(St25tbType type) { + return st25tb_features[type].blocks_total; +} + +const char* st25tb_get_device_name(const St25tbData* data, NfcDeviceNameType name_type) { + furi_assert(data); + furi_assert(data->type < St25tbTypeNum); + + if(name_type == NfcDeviceNameTypeFull) { + return st25tb_features[data->type].full_name; + } else { + return st25tb_features[data->type].type_name; + } +} + +const uint8_t* st25tb_get_uid(const St25tbData* data, size_t* uid_len) { + furi_assert(data); + + if(uid_len) { + *uid_len = ST25TB_UID_SIZE; + } + + return data->uid; +} + +bool st25tb_set_uid(St25tbData* data, const uint8_t* uid, size_t uid_len) { + furi_assert(data); + + const bool uid_valid = uid_len == ST25TB_UID_SIZE; + + if(uid_valid) { + memcpy(data->uid, uid, uid_len); + } + + return uid_valid; +} + +St25tbData* st25tb_get_base_data(const St25tbData* data) { + UNUSED(data); + furi_crash("No base data"); +} diff --git a/lib/nfc/protocols/st25tb/st25tb.h b/lib/nfc/protocols/st25tb/st25tb.h new file mode 100644 index 000000000..1edb296ca --- /dev/null +++ b/lib/nfc/protocols/st25tb/st25tb.h @@ -0,0 +1,80 @@ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ST25TB_UID_SIZE (8U) + +//#define ST25TB_FDT_FC (4205U) +#define ST25TB_FDT_FC (8494U) +#define ST25TB_GUARD_TIME_US (5000U) +#define ST25TB_POLL_POLL_MIN_US (1280U) + +#define ST25TB_MAX_BLOCKS (128U) +#define ST25TB_SYSTEM_OTP_BLOCK (0xFFU) +#define ST25TB_BLOCK_SIZE (4U) + +typedef enum { + St25tbErrorNone, + St25tbErrorNotPresent, + St25tbErrorColResFailed, + St25tbErrorBufferOverflow, + St25tbErrorCommunication, + St25tbErrorFieldOff, + St25tbErrorWrongCrc, + St25tbErrorTimeout, +} St25tbError; + +typedef enum { + St25tbType512At, + St25tbType512Ac, + St25tbTypeX512, + St25tbType02k, + St25tbType04k, + St25tbTypeX4k, + St25tbTypeNum, +} St25tbType; + +typedef struct { + uint8_t uid[ST25TB_UID_SIZE]; + St25tbType type; + uint32_t blocks[ST25TB_MAX_BLOCKS]; + uint32_t system_otp_block; + uint8_t chip_id; +} St25tbData; + +extern const NfcDeviceBase nfc_device_st25tb; + +St25tbData* st25tb_alloc(); + +void st25tb_free(St25tbData* data); + +void st25tb_reset(St25tbData* data); + +void st25tb_copy(St25tbData* data, const St25tbData* other); + +bool st25tb_verify(St25tbData* data, const FuriString* device_type); + +bool st25tb_load(St25tbData* data, FlipperFormat* ff, uint32_t version); + +bool st25tb_save(const St25tbData* data, FlipperFormat* ff); + +bool st25tb_is_equal(const St25tbData* data, const St25tbData* other); + +uint8_t st25tb_get_block_count(St25tbType type); + +const char* st25tb_get_device_name(const St25tbData* data, NfcDeviceNameType name_type); + +const uint8_t* st25tb_get_uid(const St25tbData* data, size_t* uid_len); + +bool st25tb_set_uid(St25tbData* data, const uint8_t* uid, size_t uid_len); + +St25tbData* st25tb_get_base_data(const St25tbData* data); + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/st25tb/st25tb_poller.c b/lib/nfc/protocols/st25tb/st25tb_poller.c new file mode 100644 index 000000000..df659a205 --- /dev/null +++ b/lib/nfc/protocols/st25tb/st25tb_poller.c @@ -0,0 +1,123 @@ +#include "protocols/nfc_protocol.h" +#include "protocols/st25tb/st25tb.h" +#include "st25tb_poller_i.h" + +#include + +#include + +#define TAG "ST25TBPoller" + +const St25tbData* st25tb_poller_get_data(St25tbPoller* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +static St25tbPoller* st25tb_poller_alloc(Nfc* nfc) { + furi_assert(nfc); + + St25tbPoller* instance = malloc(sizeof(St25tbPoller)); + instance->nfc = nfc; + instance->tx_buffer = bit_buffer_alloc(ST25TB_POLLER_MAX_BUFFER_SIZE); + instance->rx_buffer = bit_buffer_alloc(ST25TB_POLLER_MAX_BUFFER_SIZE); + + // RF configuration is the same as 14b + nfc_config(instance->nfc, NfcModePoller, NfcTechIso14443b); + nfc_set_guard_time_us(instance->nfc, ST25TB_GUARD_TIME_US); + nfc_set_fdt_poll_fc(instance->nfc, ST25TB_FDT_FC); + nfc_set_fdt_poll_poll_us(instance->nfc, ST25TB_POLL_POLL_MIN_US); + instance->data = st25tb_alloc(); + + instance->st25tb_event.data = &instance->st25tb_event_data; + instance->general_event.protocol = NfcProtocolSt25tb; + instance->general_event.event_data = &instance->st25tb_event; + instance->general_event.instance = instance; + + return instance; +} + +static void st25tb_poller_free(St25tbPoller* instance) { + furi_assert(instance); + + furi_assert(instance->tx_buffer); + furi_assert(instance->rx_buffer); + furi_assert(instance->data); + + bit_buffer_free(instance->tx_buffer); + bit_buffer_free(instance->rx_buffer); + st25tb_free(instance->data); + free(instance); +} + +static void + st25tb_poller_set_callback(St25tbPoller* instance, NfcGenericCallback callback, void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; +} + +static NfcCommand st25tb_poller_run(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.protocol == NfcProtocolInvalid); + furi_assert(event.event_data); + + St25tbPoller* instance = context; + NfcEvent* nfc_event = event.event_data; + NfcCommand command = NfcCommandContinue; + + if(nfc_event->type == NfcEventTypePollerReady) { + if(instance->state != St25tbPollerStateActivated) { + St25tbError error = st25tb_poller_async_activate(instance, instance->data); + + if(error == St25tbErrorNone) { + instance->st25tb_event.type = St25tbPollerEventTypeReady; + instance->st25tb_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + } else { + instance->st25tb_event.type = St25tbPollerEventTypeError; + instance->st25tb_event_data.error = error; + command = instance->callback(instance->general_event, instance->context); + // Add delay to switch context + furi_delay_ms(100); + } + } else { + instance->st25tb_event.type = St25tbPollerEventTypeReady; + instance->st25tb_event_data.error = St25tbErrorNone; + command = instance->callback(instance->general_event, instance->context); + } + } + + return command; +} + +static bool st25tb_poller_detect(NfcGenericEvent event, void* context) { + furi_assert(context); + furi_assert(event.event_data); + furi_assert(event.instance); + furi_assert(event.protocol == NfcProtocolInvalid); + + bool protocol_detected = false; + St25tbPoller* instance = context; + NfcEvent* nfc_event = event.event_data; + furi_assert(instance->state == St25tbPollerStateIdle); + + if(nfc_event->type == NfcEventTypePollerReady) { + St25tbError error = st25tb_poller_async_initiate(instance, NULL); + protocol_detected = (error == St25tbErrorNone); + } + + return protocol_detected; +} + +const NfcPollerBase nfc_poller_st25tb = { + .alloc = (NfcPollerAlloc)st25tb_poller_alloc, + .free = (NfcPollerFree)st25tb_poller_free, + .set_callback = (NfcPollerSetCallback)st25tb_poller_set_callback, + .run = (NfcPollerRun)st25tb_poller_run, + .detect = (NfcPollerDetect)st25tb_poller_detect, + .get_data = (NfcPollerGetData)st25tb_poller_get_data, +}; diff --git a/lib/nfc/protocols/st25tb/st25tb_poller.h b/lib/nfc/protocols/st25tb/st25tb_poller.h new file mode 100644 index 000000000..a521b6d5b --- /dev/null +++ b/lib/nfc/protocols/st25tb/st25tb_poller.h @@ -0,0 +1,30 @@ +#pragma once + +#include "st25tb.h" +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct St25tbPoller St25tbPoller; + +typedef enum { + St25tbPollerEventTypeError, + St25tbPollerEventTypeReady, +} St25tbPollerEventType; + +typedef struct { + St25tbError error; +} St25tbPollerEventData; + +typedef struct { + St25tbPollerEventType type; + St25tbPollerEventData* data; +} St25tbPollerEvent; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/st25tb/st25tb_poller_defs.h b/lib/nfc/protocols/st25tb/st25tb_poller_defs.h new file mode 100644 index 000000000..86b68024f --- /dev/null +++ b/lib/nfc/protocols/st25tb/st25tb_poller_defs.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +extern const NfcPollerBase nfc_poller_st25tb; + +#ifdef __cplusplus +} +#endif diff --git a/lib/nfc/protocols/st25tb/st25tb_poller_i.c b/lib/nfc/protocols/st25tb/st25tb_poller_i.c new file mode 100644 index 000000000..bcbc69382 --- /dev/null +++ b/lib/nfc/protocols/st25tb/st25tb_poller_i.c @@ -0,0 +1,297 @@ +#include "st25tb_poller_i.h" + +#include "bit_buffer.h" +#include "core/core_defines.h" +#include "protocols/st25tb/st25tb.h" +#include + +#define TAG "ST25TBPoller" + +static St25tbError st25tb_poller_process_error(NfcError error) { + switch(error) { + case NfcErrorNone: + return St25tbErrorNone; + case NfcErrorTimeout: + return St25tbErrorTimeout; + default: + return St25tbErrorNotPresent; + } +} + +static St25tbError st25tb_poller_prepare_trx(St25tbPoller* instance) { + furi_assert(instance); + + if(instance->state == St25tbPollerStateIdle) { + return st25tb_poller_async_activate(instance, NULL); + } + + return St25tbErrorNone; +} + +static St25tbError st25tb_poller_frame_exchange( + St25tbPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + furi_assert(instance); + + const size_t tx_bytes = bit_buffer_get_size_bytes(tx_buffer); + furi_assert( + tx_bytes <= bit_buffer_get_capacity_bytes(instance->tx_buffer) - ISO14443_CRC_SIZE); + + bit_buffer_copy(instance->tx_buffer, tx_buffer); + iso14443_crc_append(Iso14443CrcTypeB, instance->tx_buffer); + + St25tbError ret = St25tbErrorNone; + + do { + NfcError error = + nfc_poller_trx(instance->nfc, instance->tx_buffer, instance->rx_buffer, fwt); + if(error != NfcErrorNone) { + FURI_LOG_D(TAG, "error during trx: %d", error); + ret = st25tb_poller_process_error(error); + break; + } + + bit_buffer_copy(rx_buffer, instance->rx_buffer); + if(!iso14443_crc_check(Iso14443CrcTypeB, instance->rx_buffer)) { + ret = St25tbErrorWrongCrc; + break; + } + + iso14443_crc_trim(rx_buffer); + } while(false); + + return ret; +} + +St25tbType st25tb_get_type_from_uid(const uint8_t uid[ST25TB_UID_SIZE]) { + switch(uid[2] >> 2) { + case 0x0: + case 0x3: + return St25tbTypeX4k; + case 0x4: + return St25tbTypeX512; + case 0x6: + return St25tbType512Ac; + case 0x7: + return St25tbType04k; + case 0xc: + return St25tbType512At; + case 0xf: + return St25tbType02k; + default: + furi_crash("unsupported st25tb type"); + } +} + +St25tbError st25tb_poller_async_initiate(St25tbPoller* instance, uint8_t* chip_id) { + // Send Initiate() + furi_assert(instance); + furi_assert(instance->nfc); + + instance->state = St25tbPollerStateInitiateInProgress; + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + bit_buffer_append_byte(instance->tx_buffer, 0x06); + bit_buffer_append_byte(instance->tx_buffer, 0x00); + + St25tbError ret; + do { + ret = st25tb_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ST25TB_FDT_FC); + if(ret != St25tbErrorNone) { + break; + } + + if(bit_buffer_get_size_bytes(instance->rx_buffer) != 1) { + FURI_LOG_D(TAG, "Unexpected Initiate response size"); + ret = St25tbErrorCommunication; + break; + } + if(chip_id) { + *chip_id = bit_buffer_get_byte(instance->rx_buffer, 0); + } + } while(false); + + return ret; +} + +St25tbError st25tb_poller_async_activate(St25tbPoller* instance, St25tbData* data) { + furi_assert(instance); + furi_assert(instance->nfc); + + st25tb_reset(data); + + St25tbError ret; + + do { + ret = st25tb_poller_async_initiate(instance, &data->chip_id); + if(ret != St25tbErrorNone) { + break; + } + + instance->state = St25tbPollerStateActivationInProgress; + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + // Send Select(Chip_ID), let's just assume that collisions won't ever happen :D + bit_buffer_append_byte(instance->tx_buffer, 0x0E); + bit_buffer_append_byte(instance->tx_buffer, data->chip_id); + + ret = st25tb_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ST25TB_FDT_FC); + if(ret != St25tbErrorNone) { + instance->state = St25tbPollerStateActivationFailed; + break; + } + + if(bit_buffer_get_size_bytes(instance->rx_buffer) != 1) { + FURI_LOG_D(TAG, "Unexpected Select response size"); + instance->state = St25tbPollerStateActivationFailed; + ret = St25tbErrorCommunication; + break; + } + + if(bit_buffer_get_byte(instance->rx_buffer, 0) != data->chip_id) { + FURI_LOG_D(TAG, "ChipID mismatch"); + instance->state = St25tbPollerStateActivationFailed; + ret = St25tbErrorColResFailed; + break; + } + instance->state = St25tbPollerStateActivated; + + ret = st25tb_poller_async_get_uid(instance, data->uid); + if(ret != St25tbErrorNone) { + instance->state = St25tbPollerStateActivationFailed; + break; + } + data->type = st25tb_get_type_from_uid(data->uid); + + bool read_blocks = true; + for(uint8_t i = 0; i < st25tb_get_block_count(data->type); i++) { + ret = st25tb_poller_async_read_block(instance, &data->blocks[i], i); + if(ret != St25tbErrorNone) { + read_blocks = false; + break; + } + } + if(!read_blocks) { + break; + } + ret = st25tb_poller_async_read_block( + instance, &data->system_otp_block, ST25TB_SYSTEM_OTP_BLOCK); + } while(false); + + return ret; +} + +St25tbError st25tb_poller_async_get_uid(St25tbPoller* instance, uint8_t uid[ST25TB_UID_SIZE]) { + furi_assert(instance); + furi_assert(instance->nfc); + + St25tbError ret; + + do { + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + bit_buffer_append_byte(instance->tx_buffer, 0x0B); + + ret = st25tb_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ST25TB_FDT_FC); + if(ret != St25tbErrorNone) { + break; + } + + if(bit_buffer_get_size_bytes(instance->rx_buffer) != ST25TB_UID_SIZE) { + FURI_LOG_D(TAG, "Unexpected Get_UID() response size"); + instance->state = St25tbPollerStateActivationFailed; + ret = St25tbErrorCommunication; + break; + } + bit_buffer_write_bytes(instance->rx_buffer, uid, ST25TB_UID_SIZE); + FURI_SWAP(uid[0], uid[7]); + FURI_SWAP(uid[1], uid[6]); + FURI_SWAP(uid[2], uid[5]); + FURI_SWAP(uid[3], uid[4]); + } while(false); + return ret; +} + +St25tbError + st25tb_poller_async_read_block(St25tbPoller* instance, uint32_t* block, uint8_t block_number) { + furi_assert(instance); + furi_assert(instance->nfc); + furi_assert(block); + furi_assert( + (block_number <= st25tb_get_block_count(instance->data->type)) || + block_number == ST25TB_SYSTEM_OTP_BLOCK); + FURI_LOG_D(TAG, "reading block %d", block_number); + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + // Send Read_block(Addr) + bit_buffer_append_byte(instance->tx_buffer, 0x08); + bit_buffer_append_byte(instance->tx_buffer, block_number); + St25tbError ret; + do { + ret = st25tb_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ST25TB_FDT_FC); + if(ret != St25tbErrorNone) { + break; + } + + if(bit_buffer_get_size_bytes(instance->rx_buffer) != ST25TB_BLOCK_SIZE) { + FURI_LOG_D(TAG, "Unexpected Read_block(Addr) response size"); + ret = St25tbErrorCommunication; + break; + } + bit_buffer_write_bytes(instance->rx_buffer, block, ST25TB_BLOCK_SIZE); + FURI_LOG_D(TAG, "read result: %08lX", *block); + } while(false); + + return ret; +} + +St25tbError st25tb_poller_halt(St25tbPoller* instance) { + furi_assert(instance); + + bit_buffer_reset(instance->tx_buffer); + bit_buffer_reset(instance->rx_buffer); + + // Send Completion() + bit_buffer_append_byte(instance->tx_buffer, 0x0F); + + St25tbError ret; + + do { + ret = st25tb_poller_frame_exchange( + instance, instance->tx_buffer, instance->rx_buffer, ST25TB_FDT_FC); + if(ret != St25tbErrorTimeout) { + break; + } + + instance->state = St25tbPollerStateIdle; + } while(false); + + return ret; +} + +St25tbError st25tb_poller_send_frame( + St25tbPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt) { + St25tbError ret; + + do { + ret = st25tb_poller_prepare_trx(instance); + if(ret != St25tbErrorNone) break; + + ret = st25tb_poller_frame_exchange(instance, tx_buffer, rx_buffer, fwt); + } while(false); + + return ret; +} diff --git a/lib/nfc/protocols/st25tb/st25tb_poller_i.h b/lib/nfc/protocols/st25tb/st25tb_poller_i.h new file mode 100644 index 000000000..7f38f2d45 --- /dev/null +++ b/lib/nfc/protocols/st25tb/st25tb_poller_i.h @@ -0,0 +1,56 @@ +#pragma once + +#include "protocols/st25tb/st25tb.h" +#include "st25tb_poller.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ST25TB_POLLER_MAX_BUFFER_SIZE (16U) + +typedef enum { + St25tbPollerStateIdle, + St25tbPollerStateInitiateInProgress, + St25tbPollerStateInitiateFailed, + St25tbPollerStateActivationInProgress, + St25tbPollerStateActivationFailed, + St25tbPollerStateActivated, +} St25tbPollerState; + +struct St25tbPoller { + Nfc* nfc; + St25tbPollerState state; + St25tbData* data; + BitBuffer* tx_buffer; + BitBuffer* rx_buffer; + + NfcGenericEvent general_event; + St25tbPollerEvent st25tb_event; + St25tbPollerEventData st25tb_event_data; + NfcGenericCallback callback; + void* context; +}; + +const St25tbData* st25tb_poller_get_data(St25tbPoller* instance); + +St25tbError st25tb_poller_async_initiate(St25tbPoller* instance, uint8_t* chip_id); + +St25tbError st25tb_poller_async_activate(St25tbPoller* instance, St25tbData* data); + +St25tbError st25tb_poller_async_get_uid(St25tbPoller* instance, uint8_t uid[ST25TB_UID_SIZE]); + +St25tbError + st25tb_poller_async_read_block(St25tbPoller* instance, uint32_t* block, uint8_t block_number); + +St25tbError st25tb_poller_halt(St25tbPoller* instance); + +St25tbError st25tb_poller_send_frame( + St25tbPoller* instance, + const BitBuffer* tx_buffer, + BitBuffer* rx_buffer, + uint32_t fwt); + +#ifdef __cplusplus +} +#endif diff --git a/lib/print/wrappers.h b/lib/print/wrappers.h index b6f0f004b..7c0d1f92e 100644 --- a/lib/print/wrappers.h +++ b/lib/print/wrappers.h @@ -1,3 +1,5 @@ +#pragma once + #include #include #include @@ -6,7 +8,6 @@ extern "C" { #endif -void _putchar(char character); int __wrap_printf(const char* format, ...); int __wrap_vsnprintf(char* str, size_t size, const char* format, va_list args); int __wrap_puts(const char* str); diff --git a/lib/signal_reader/SConscript b/lib/signal_reader/SConscript new file mode 100644 index 000000000..ea7314420 --- /dev/null +++ b/lib/signal_reader/SConscript @@ -0,0 +1,20 @@ +Import("env") + +env.Append( + CPPPATH=[ + "#/lib/signal_reader", + ], + SDK_HEADERS=[ + File("signal_reader.h"), + ], +) + +libenv = env.Clone(FW_LIB_NAME="signal_reader") +libenv.ApplyLibFlags() +libenv.Append(CCFLAGS=["-O3", "-funroll-loops", "-Ofast"]) + +sources = libenv.GlobRecursive("*.c*") + +lib = libenv.StaticLibrary("${FW_LIB_NAME}", sources) +libenv.Install("${LIB_DIST_DIR}", lib) +Return("lib") diff --git a/lib/signal_reader/parsers/iso15693/iso15693_parser.c b/lib/signal_reader/parsers/iso15693/iso15693_parser.c new file mode 100644 index 000000000..c5326a354 --- /dev/null +++ b/lib/signal_reader/parsers/iso15693/iso15693_parser.c @@ -0,0 +1,300 @@ +#include "iso15693_parser.h" + +#include + +#include + +#define ISO15693_PARSER_SIGNAL_READER_BUFF_SIZE (2) +#define ISO15693_PARSER_BITSTREAM_BUFF_SIZE (32) +#define ISO15693_PARSER_BITRATE_F64MHZ (603U) + +#define TAG "Iso15693Parser" + +typedef enum { + Iso15693ParserStateParseSoF, + Iso15693ParserStateParseFrame, + Iso15693ParserStateFail, +} Iso15693ParserState; + +typedef enum { + Iso15693ParserMode1OutOf4, + Iso15693ParserMode1OutOf256, + + Iso15693ParserModeNum, +} Iso15693ParserMode; + +struct Iso15693Parser { + Iso15693ParserState state; + Iso15693ParserMode mode; + + SignalReader* signal_reader; + + uint8_t bitstream_buff[ISO15693_PARSER_BITSTREAM_BUFF_SIZE]; + size_t bitstream_idx; + uint8_t last_byte; + + bool signal_detected; + bool bit_offset_calculated; + uint8_t bit_offset; + size_t byte_idx; + size_t bytes_to_process; + + uint8_t next_byte; + uint16_t next_byte_part; + bool zero_found; + + BitBuffer* parsed_frame; + bool eof_received; + bool frame_parsed; + + Iso15693ParserCallback callback; + void* context; +}; + +typedef enum { + Iso15693ParserCommandProcessed, + Iso15693ParserCommandWaitData, + Iso15693ParserCommandFail, + Iso15693ParserCommandSuccess, +} Iso15693ParserCommand; + +typedef Iso15693ParserCommand (*Iso15693ParserStateHandler)(Iso15693Parser* instance); + +Iso15693Parser* iso15693_parser_alloc(const GpioPin* pin, size_t max_frame_size) { + Iso15693Parser* instance = malloc(sizeof(Iso15693Parser)); + instance->parsed_frame = bit_buffer_alloc(max_frame_size); + + instance->signal_reader = signal_reader_alloc(pin, ISO15693_PARSER_SIGNAL_READER_BUFF_SIZE); + signal_reader_set_sample_rate( + instance->signal_reader, SignalReaderTimeUnit64Mhz, ISO15693_PARSER_BITRATE_F64MHZ); + signal_reader_set_pull(instance->signal_reader, GpioPullDown); + signal_reader_set_polarity(instance->signal_reader, SignalReaderPolarityNormal); + signal_reader_set_trigger(instance->signal_reader, SignalReaderTriggerRisingFallingEdge); + + return instance; +} + +void iso15693_parser_free(Iso15693Parser* instance) { + furi_assert(instance); + + bit_buffer_free(instance->parsed_frame); + signal_reader_free(instance->signal_reader); + free(instance); +} + +void iso15693_parser_reset(Iso15693Parser* instance) { + furi_assert(instance); + + instance->state = Iso15693ParserStateParseSoF; + instance->mode = Iso15693ParserMode1OutOf4; + memset(instance->bitstream_buff, 0x00, sizeof(instance->bitstream_buff)); + instance->bitstream_idx = 0; + + instance->next_byte = 0; + instance->next_byte_part = 0; + + instance->bit_offset = 0; + instance->byte_idx = 0; + instance->bytes_to_process = 0; + instance->signal_detected = false; + instance->bit_offset_calculated = false; + + instance->last_byte = 0x00; + instance->zero_found = false; + instance->eof_received = false; + + bit_buffer_reset(instance->parsed_frame); + instance->frame_parsed = false; +} + +static void signal_reader_callback(SignalReaderEvent event, void* context) { + furi_assert(context); + furi_assert(event.data->data); + furi_assert(event.data->len == ISO15693_PARSER_SIGNAL_READER_BUFF_SIZE / 2); + + Iso15693Parser* instance = context; + furi_assert(instance->callback); + + const uint8_t sof_1_out_of_4 = 0x21; + const uint8_t sof_1_out_of_256 = 0x81; + const uint8_t eof_single = 0x01; + const uint8_t eof = 0x04; + + if(instance->state == Iso15693ParserStateParseSoF) { + if(event.data->data[0] == sof_1_out_of_4) { + instance->mode = Iso15693ParserMode1OutOf4; + instance->state = Iso15693ParserStateParseFrame; + } else if(event.data->data[0] == sof_1_out_of_256) { + instance->mode = Iso15693ParserMode1OutOf256; + instance->state = Iso15693ParserStateParseFrame; + } else if(event.data->data[0] == eof_single) { + instance->eof_received = true; + instance->callback(Iso15693ParserEventDataReceived, instance->context); + } else { + instance->state = Iso15693ParserStateFail; + instance->callback(Iso15693ParserEventDataReceived, instance->context); + } + } else { + if(instance->mode == Iso15693ParserMode1OutOf4) { + if(event.data->data[0] == eof) { + instance->eof_received = true; + instance->callback(Iso15693ParserEventDataReceived, instance->context); + } else { + instance->bitstream_buff[instance->bytes_to_process] = event.data->data[0]; + instance->bytes_to_process++; + if(instance->bytes_to_process == ISO15693_PARSER_BITSTREAM_BUFF_SIZE) { + instance->callback(Iso15693ParserEventDataReceived, instance->context); + } + } + } else { + instance->bitstream_buff[instance->bytes_to_process] = event.data->data[0]; + instance->bytes_to_process++; + if(instance->bytes_to_process == ISO15693_PARSER_BITSTREAM_BUFF_SIZE) { + instance->callback(Iso15693ParserEventDataReceived, instance->context); + } + } + } +} + +static void iso15693_parser_start_signal_reader(Iso15693Parser* instance) { + iso15693_parser_reset(instance); + signal_reader_start(instance->signal_reader, signal_reader_callback, instance); +} + +void iso15693_parser_start( + Iso15693Parser* instance, + Iso15693ParserCallback callback, + void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; + iso15693_parser_start_signal_reader(instance); +} + +void iso15693_parser_stop(Iso15693Parser* instance) { + furi_assert(instance); + + signal_reader_stop(instance->signal_reader); +} + +static Iso15693ParserCommand iso15693_parser_parse_1_out_of_4(Iso15693Parser* instance) { + Iso15693ParserCommand command = Iso15693ParserCommandWaitData; + const uint8_t bit_patterns_1_out_of_4[] = {0x02, 0x08, 0x20, 0x80}; + + for(size_t i = 0; i < instance->bytes_to_process; i++) { + // Check next pattern + size_t j = 0; + for(j = 0; j < COUNT_OF(bit_patterns_1_out_of_4); j++) { + if(instance->bitstream_buff[i] == bit_patterns_1_out_of_4[j]) { + instance->next_byte |= j << (instance->next_byte_part * 2); + instance->next_byte_part++; + if(instance->next_byte_part == 4) { + instance->next_byte_part = 0; + bit_buffer_append_byte(instance->parsed_frame, instance->next_byte); + instance->next_byte = 0; + } + break; + } + } + if(j == COUNT_OF(bit_patterns_1_out_of_4)) { + command = Iso15693ParserCommandFail; + break; + } + } + + if(command != Iso15693ParserCommandFail) { + if(instance->eof_received) { + command = Iso15693ParserCommandSuccess; + instance->frame_parsed = true; + } + } + + instance->bytes_to_process = 0; + + return command; +} + +static Iso15693ParserCommand iso15693_parser_parse_1_out_of_256(Iso15693Parser* instance) { + Iso15693ParserCommand command = Iso15693ParserCommandWaitData; + const uint8_t eof = 0x04; + + for(size_t i = instance->byte_idx; i < instance->bytes_to_process; i++) { + // Check EoF + if(instance->next_byte_part == 0) { + if(instance->bitstream_buff[i] == eof) { + instance->frame_parsed = true; + command = Iso15693ParserCommandSuccess; + break; + } + } + + if(instance->zero_found) { + if(instance->bitstream_buff[i] != 0x00) { + command = Iso15693ParserCommandFail; + break; + } + } else { + if(instance->bitstream_buff[i] != 0x00) { + for(size_t j = 0; j < 8; j++) { + if(FURI_BIT(instance->bitstream_buff[i], j) == 1) { + bit_buffer_append_byte( + instance->parsed_frame, instance->next_byte_part * 4 + j / 2); + } + } + } + } + instance->next_byte_part = (instance->next_byte_part + 1) % 64; + } + instance->bytes_to_process = 0; + instance->byte_idx = 0; + + return command; +} + +static const Iso15693ParserStateHandler iso15693_parser_state_handlers[Iso15693ParserModeNum] = { + [Iso15693ParserMode1OutOf4] = iso15693_parser_parse_1_out_of_4, + [Iso15693ParserMode1OutOf256] = iso15693_parser_parse_1_out_of_256, +}; + +bool iso15693_parser_run(Iso15693Parser* instance) { + if(instance->state == Iso15693ParserStateFail) { + iso15693_parser_stop(instance); + iso15693_parser_start_signal_reader(instance); + } else if((instance->state == Iso15693ParserStateParseSoF) && (instance->eof_received)) { + instance->frame_parsed = true; + } else if(instance->bytes_to_process) { + Iso15693ParserCommand command = Iso15693ParserCommandProcessed; + while(command == Iso15693ParserCommandProcessed) { + command = iso15693_parser_state_handlers[instance->mode](instance); + } + + if(command == Iso15693ParserCommandFail) { + iso15693_parser_stop(instance); + iso15693_parser_start_signal_reader(instance); + FURI_LOG_D(TAG, "Frame parse failed"); + } + } + + return instance->frame_parsed; +} + +size_t iso15693_parser_get_data_size_bytes(Iso15693Parser* instance) { + furi_assert(instance); + + return bit_buffer_get_size_bytes(instance->parsed_frame); +} + +void iso15693_parser_get_data( + Iso15693Parser* instance, + uint8_t* buff, + size_t buff_size, + size_t* data_bits) { + furi_assert(instance); + furi_assert(buff); + furi_assert(data_bits); + + bit_buffer_write_bytes(instance->parsed_frame, buff, buff_size); + *data_bits = bit_buffer_get_size(instance->parsed_frame); +} diff --git a/lib/signal_reader/parsers/iso15693/iso15693_parser.h b/lib/signal_reader/parsers/iso15693/iso15693_parser.h new file mode 100644 index 000000000..3017a96d7 --- /dev/null +++ b/lib/signal_reader/parsers/iso15693/iso15693_parser.h @@ -0,0 +1,42 @@ +#pragma once + +#include "../../signal_reader.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Iso15693Parser Iso15693Parser; + +typedef enum { + Iso15693ParserEventDataReceived, +} Iso15693ParserEvent; + +typedef void (*Iso15693ParserCallback)(Iso15693ParserEvent event, void* context); + +Iso15693Parser* iso15693_parser_alloc(const GpioPin* pin, size_t max_frame_size); + +void iso15693_parser_free(Iso15693Parser* instance); + +void iso15693_parser_reset(Iso15693Parser* instance); + +void iso15693_parser_start( + Iso15693Parser* instance, + Iso15693ParserCallback callback, + void* context); + +void iso15693_parser_stop(Iso15693Parser* instance); + +bool iso15693_parser_run(Iso15693Parser* instance); + +size_t iso15693_parser_get_data_size_bytes(Iso15693Parser* instance); + +void iso15693_parser_get_data( + Iso15693Parser* instance, + uint8_t* buff, + size_t buff_size, + size_t* data_bits); + +#ifdef __cplusplus +} +#endif diff --git a/lib/signal_reader/signal_reader.c b/lib/signal_reader/signal_reader.c new file mode 100644 index 000000000..7c4d0bae7 --- /dev/null +++ b/lib/signal_reader/signal_reader.c @@ -0,0 +1,317 @@ +#include "signal_reader.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#define SIGNAL_READER_DMA DMA2 + +#define SIGNAL_READER_CAPTURE_TIM (TIM16) +#define SIGNAL_READER_CAPTURE_TIM_CHANNEL LL_TIM_CHANNEL_CH1 + +#define SIGNAL_READER_DMA_GPIO LL_DMA_CHANNEL_2 +#define SIGNAL_READER_DMA_GPIO_IRQ FuriHalInterruptIdDma2Ch2 +#define SIGNAL_READER_DMA_GPIO_DEF SIGNAL_READER_DMA, SIGNAL_READER_DMA_GPIO + +#define SIGNAL_READER_DMA_TRIGGER LL_DMA_CHANNEL_3 +#define SIGNAL_READER_DMA_TRIGGER_IRQ FuriHalInterruptIdDma2Ch3 +#define SIGNAL_READER_DMA_TRIGGER_DEF SIGNAL_READER_DMA, SIGNAL_READER_DMA_TRIGGER + +#define SIGNAL_READER_DMA_CNT_SYNC LL_DMA_CHANNEL_5 +#define SIGNAL_READER_DMA_CNT_SYNC_IRQ FuriHalInterruptIdDma2Ch5 +#define SIGNAL_READER_DMA_CNT_SYNC_DEF SIGNAL_READER_DMA, SIGNAL_READER_DMA_CNT_SYNC + +struct SignalReader { + size_t buffer_size; + const GpioPin* pin; + GpioPull pull; + SignalReaderPolarity polarity; + SignalReaderTrigger trigger; + + uint16_t* gpio_buffer; + uint8_t* bitstream_buffer; + uint32_t cnt_en; + + uint32_t tim_cnt_compensation; + uint32_t tim_arr; + + SignalReaderEvent event; + SignalReaderEventData event_data; + + SignalReaderCallback callback; + void* context; +}; + +#define GPIO_PIN_MAP(pin, prefix) \ + (((pin) == (LL_GPIO_PIN_0)) ? prefix##0 : \ + ((pin) == (LL_GPIO_PIN_1)) ? prefix##1 : \ + ((pin) == (LL_GPIO_PIN_2)) ? prefix##2 : \ + ((pin) == (LL_GPIO_PIN_3)) ? prefix##3 : \ + ((pin) == (LL_GPIO_PIN_4)) ? prefix##4 : \ + ((pin) == (LL_GPIO_PIN_5)) ? prefix##5 : \ + ((pin) == (LL_GPIO_PIN_6)) ? prefix##6 : \ + ((pin) == (LL_GPIO_PIN_7)) ? prefix##7 : \ + ((pin) == (LL_GPIO_PIN_8)) ? prefix##8 : \ + ((pin) == (LL_GPIO_PIN_9)) ? prefix##9 : \ + ((pin) == (LL_GPIO_PIN_10)) ? prefix##10 : \ + ((pin) == (LL_GPIO_PIN_11)) ? prefix##11 : \ + ((pin) == (LL_GPIO_PIN_12)) ? prefix##12 : \ + ((pin) == (LL_GPIO_PIN_13)) ? prefix##13 : \ + ((pin) == (LL_GPIO_PIN_14)) ? prefix##14 : \ + prefix##15) + +#define GET_DMAMUX_EXTI_LINE(pin) GPIO_PIN_MAP(pin, LL_DMAMUX_REQ_GEN_EXTI_LINE) + +SignalReader* signal_reader_alloc(const GpioPin* gpio_pin, uint32_t size) { + SignalReader* instance = malloc(sizeof(SignalReader)); + + instance->pin = gpio_pin; + instance->pull = GpioPullNo; + + instance->buffer_size = size; + instance->gpio_buffer = malloc(sizeof(uint16_t) * size * 8); + instance->bitstream_buffer = malloc(size); + + instance->event.data = &instance->event_data; + + return instance; +} + +void signal_reader_free(SignalReader* instance) { + furi_assert(instance); + furi_assert(instance->gpio_buffer); + furi_assert(instance->bitstream_buffer); + + free(instance->gpio_buffer); + free(instance->bitstream_buffer); + free(instance); +} + +void signal_reader_set_pull(SignalReader* instance, GpioPull pull) { + furi_assert(instance); + + instance->pull = pull; +} + +void signal_reader_set_polarity(SignalReader* instance, SignalReaderPolarity polarity) { + furi_assert(instance); + + instance->polarity = polarity; +} + +void signal_reader_set_sample_rate( + SignalReader* instance, + SignalReaderTimeUnit time_unit, + uint32_t time) { + furi_assert(instance); + UNUSED(time_unit); + + instance->tim_arr = time; +} + +void signal_reader_set_trigger(SignalReader* instance, SignalReaderTrigger trigger) { + furi_assert(instance); + + instance->trigger = trigger; +} + +static void furi_hal_sw_digital_pin_dma_rx_isr(void* context) { + SignalReader* instance = context; + + uint16_t* gpio_buff_start = NULL; + uint8_t* bitstream_buff_start = NULL; + + if(LL_DMA_IsActiveFlag_HT2(SIGNAL_READER_DMA)) { + LL_DMA_ClearFlag_HT2(SIGNAL_READER_DMA); + instance->event.type = SignalReaderEventTypeHalfBufferFilled; + gpio_buff_start = instance->gpio_buffer; + bitstream_buff_start = instance->bitstream_buffer; + + if(instance->callback) { + furi_assert(gpio_buff_start); + furi_assert(bitstream_buff_start); + + for(size_t i = 0; i < instance->buffer_size * 4; i++) { + if((i % 8) == 0) { + bitstream_buff_start[i / 8] = 0; + } + uint8_t bit = 0; + if(instance->polarity == SignalReaderPolarityNormal) { + bit = (gpio_buff_start[i] & instance->pin->pin) == instance->pin->pin; + } else { + bit = (gpio_buff_start[i] & instance->pin->pin) == 0; + } + bitstream_buff_start[i / 8] |= bit << (i % 8); + } + instance->event_data.data = bitstream_buff_start; + instance->event_data.len = instance->buffer_size / 2; + instance->callback(instance->event, instance->context); + } + } + if(LL_DMA_IsActiveFlag_TC2(SIGNAL_READER_DMA)) { + LL_DMA_ClearFlag_TC2(SIGNAL_READER_DMA); + instance->event.type = SignalReaderEventTypeFullBufferFilled; + gpio_buff_start = &instance->gpio_buffer[instance->buffer_size * 4]; + bitstream_buff_start = &instance->bitstream_buffer[instance->buffer_size / 2]; + + if(instance->callback) { + furi_assert(gpio_buff_start); + furi_assert(bitstream_buff_start); + + for(size_t i = 0; i < instance->buffer_size * 4; i++) { + if((i % 8) == 0) { + bitstream_buff_start[i / 8] = 0; + } + uint8_t bit = 0; + if(instance->polarity == SignalReaderPolarityNormal) { + bit = (gpio_buff_start[i] & instance->pin->pin) == instance->pin->pin; + } else { + bit = (gpio_buff_start[i] & instance->pin->pin) == 0; + } + bitstream_buff_start[i / 8] |= bit << (i % 8); + } + instance->event_data.data = bitstream_buff_start; + instance->event_data.len = instance->buffer_size / 2; + instance->callback(instance->event, instance->context); + } + } +} + +void signal_reader_start(SignalReader* instance, SignalReaderCallback callback, void* context) { + furi_assert(instance); + furi_assert(callback); + + instance->callback = callback; + instance->context = context; + + // EXTI delay compensation + instance->tim_cnt_compensation = 9; + instance->cnt_en = SIGNAL_READER_CAPTURE_TIM->CR1; + instance->cnt_en |= TIM_CR1_CEN; + + furi_hal_bus_enable(FuriHalBusTIM16); + + // Capture timer config + LL_TIM_SetPrescaler(SIGNAL_READER_CAPTURE_TIM, 0); + LL_TIM_SetCounterMode(SIGNAL_READER_CAPTURE_TIM, LL_TIM_COUNTERMODE_UP); + LL_TIM_SetAutoReload(SIGNAL_READER_CAPTURE_TIM, instance->tim_arr); + LL_TIM_SetClockDivision(SIGNAL_READER_CAPTURE_TIM, LL_TIM_CLOCKDIVISION_DIV1); + + LL_TIM_DisableARRPreload(SIGNAL_READER_CAPTURE_TIM); + LL_TIM_SetClockSource(SIGNAL_READER_CAPTURE_TIM, LL_TIM_CLOCKSOURCE_INTERNAL); + + // Configure TIM channel CC1 + LL_TIM_OC_InitTypeDef TIM_OC_InitStruct = {}; + TIM_OC_InitStruct.OCMode = LL_TIM_OCMODE_FROZEN; + TIM_OC_InitStruct.OCState = LL_TIM_OCSTATE_DISABLE; + TIM_OC_InitStruct.OCNState = LL_TIM_OCSTATE_DISABLE; + TIM_OC_InitStruct.CompareValue = (instance->tim_arr / 2); + TIM_OC_InitStruct.OCPolarity = LL_TIM_OCPOLARITY_HIGH; + LL_TIM_OC_Init( + SIGNAL_READER_CAPTURE_TIM, SIGNAL_READER_CAPTURE_TIM_CHANNEL, &TIM_OC_InitStruct); + LL_TIM_OC_DisableFast(SIGNAL_READER_CAPTURE_TIM, SIGNAL_READER_CAPTURE_TIM_CHANNEL); + + LL_TIM_SetTriggerOutput(SIGNAL_READER_CAPTURE_TIM, LL_TIM_TRGO_RESET); + LL_TIM_DisableMasterSlaveMode(SIGNAL_READER_CAPTURE_TIM); + + // Start + LL_TIM_GenerateEvent_UPDATE(SIGNAL_READER_CAPTURE_TIM); + + /* We need the EXTI to be configured as interrupt generating line, but no ISR registered */ + furi_hal_gpio_init( + instance->pin, GpioModeInterruptRiseFall, instance->pull, GpioSpeedVeryHigh); + + /* Set DMAMUX request generation signal ID on specified DMAMUX channel */ + LL_DMAMUX_SetRequestSignalID( + DMAMUX1, LL_DMAMUX_REQ_GEN_0, GET_DMAMUX_EXTI_LINE(instance->pin->pin)); + /* Set the polarity of the signal on which the DMA request is generated */ + LL_DMAMUX_SetRequestGenPolarity(DMAMUX1, LL_DMAMUX_REQ_GEN_0, LL_DMAMUX_REQ_GEN_POL_RISING); + /* Set the number of DMA requests that will be authorized after a generation event */ + LL_DMAMUX_SetGenRequestNb(DMAMUX1, LL_DMAMUX_REQ_GEN_0, 1); + + // Configure DMA Sync + LL_DMA_SetMemoryAddress( + SIGNAL_READER_DMA_CNT_SYNC_DEF, (uint32_t)&instance->tim_cnt_compensation); + LL_DMA_SetPeriphAddress( + SIGNAL_READER_DMA_CNT_SYNC_DEF, (uint32_t) & (SIGNAL_READER_CAPTURE_TIM->CNT)); + LL_DMA_ConfigTransfer( + SIGNAL_READER_DMA_CNT_SYNC_DEF, + LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_MODE_CIRCULAR | LL_DMA_PERIPH_NOINCREMENT | + LL_DMA_MEMORY_NOINCREMENT | LL_DMA_PDATAALIGN_HALFWORD | LL_DMA_MDATAALIGN_HALFWORD | + LL_DMA_PRIORITY_VERYHIGH); + LL_DMA_SetDataLength(SIGNAL_READER_DMA_CNT_SYNC_DEF, 1); + LL_DMA_SetPeriphRequest(SIGNAL_READER_DMA_CNT_SYNC_DEF, LL_DMAMUX_REQ_GENERATOR0); + + // Configure DMA Sync + LL_DMA_SetMemoryAddress(SIGNAL_READER_DMA_TRIGGER_DEF, (uint32_t)&instance->cnt_en); + LL_DMA_SetPeriphAddress( + SIGNAL_READER_DMA_TRIGGER_DEF, (uint32_t) & (SIGNAL_READER_CAPTURE_TIM->CR1)); + LL_DMA_ConfigTransfer( + SIGNAL_READER_DMA_TRIGGER_DEF, + LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_NOINCREMENT | + LL_DMA_PDATAALIGN_HALFWORD | LL_DMA_MDATAALIGN_HALFWORD | LL_DMA_PRIORITY_VERYHIGH); + LL_DMA_SetDataLength(SIGNAL_READER_DMA_TRIGGER_DEF, 1); + LL_DMA_SetPeriphRequest(SIGNAL_READER_DMA_TRIGGER_DEF, LL_DMAMUX_REQ_GENERATOR0); + + // Configure DMA Rx pin + LL_DMA_SetMemoryAddress(SIGNAL_READER_DMA_GPIO_DEF, (uint32_t)instance->gpio_buffer); + LL_DMA_SetPeriphAddress(SIGNAL_READER_DMA_GPIO_DEF, (uint32_t) & (instance->pin->port->IDR)); + LL_DMA_ConfigTransfer( + SIGNAL_READER_DMA_GPIO_DEF, + LL_DMA_DIRECTION_PERIPH_TO_MEMORY | LL_DMA_MODE_CIRCULAR | LL_DMA_PERIPH_NOINCREMENT | + LL_DMA_MEMORY_INCREMENT | LL_DMA_PDATAALIGN_HALFWORD | LL_DMA_MDATAALIGN_HALFWORD | + LL_DMA_PRIORITY_HIGH); + LL_DMA_SetDataLength(SIGNAL_READER_DMA_GPIO_DEF, instance->buffer_size * 8); + LL_DMA_SetPeriphRequest(SIGNAL_READER_DMA_GPIO_DEF, LL_DMAMUX_REQ_TIM16_CH1); + + // Configure DMA Channel CC1 + LL_TIM_EnableDMAReq_CC1(SIGNAL_READER_CAPTURE_TIM); + LL_TIM_CC_EnableChannel(SIGNAL_READER_CAPTURE_TIM, SIGNAL_READER_CAPTURE_TIM_CHANNEL); + + // Start DMA irq, higher priority than normal + furi_hal_interrupt_set_isr_ex( + SIGNAL_READER_DMA_GPIO_IRQ, 14, furi_hal_sw_digital_pin_dma_rx_isr, instance); + + // Start DMA Sync timer + LL_DMA_EnableChannel(SIGNAL_READER_DMA_CNT_SYNC_DEF); + + // Start DMA Rx pin + LL_DMA_EnableChannel(SIGNAL_READER_DMA_GPIO_DEF); + // Strat timer + LL_TIM_SetCounter(SIGNAL_READER_CAPTURE_TIM, 0); + if(instance->trigger == SignalReaderTriggerNone) { + LL_TIM_EnableCounter(SIGNAL_READER_CAPTURE_TIM); + } else { + LL_DMA_EnableChannel(SIGNAL_READER_DMA_TRIGGER_DEF); + } + + LL_DMAMUX_EnableRequestGen(DMAMUX1, LL_DMAMUX_REQ_GEN_0); + // Need to clear flags before enabling DMA !!!! + if(LL_DMA_IsActiveFlag_TC2(SIGNAL_READER_DMA)) LL_DMA_ClearFlag_TC1(SIGNAL_READER_DMA); + if(LL_DMA_IsActiveFlag_TE2(SIGNAL_READER_DMA)) LL_DMA_ClearFlag_TE1(SIGNAL_READER_DMA); + LL_DMA_EnableIT_TC(SIGNAL_READER_DMA_GPIO_DEF); + LL_DMA_EnableIT_HT(SIGNAL_READER_DMA_GPIO_DEF); +} + +void signal_reader_stop(SignalReader* instance) { + furi_assert(instance); + + furi_hal_interrupt_set_isr(SIGNAL_READER_DMA_GPIO_IRQ, NULL, NULL); + + // Deinit DMA Rx pin + LL_DMA_DeInit(SIGNAL_READER_DMA_GPIO_DEF); + // Deinit DMA Sync timer + LL_DMA_DeInit(SIGNAL_READER_DMA_CNT_SYNC_DEF); + // Deinit DMA Trigger timer + LL_DMA_DeInit(SIGNAL_READER_DMA_TRIGGER_DEF); + + furi_hal_bus_disable(FuriHalBusTIM16); +} diff --git a/lib/signal_reader/signal_reader.h b/lib/signal_reader/signal_reader.h new file mode 100644 index 000000000..be18f295a --- /dev/null +++ b/lib/signal_reader/signal_reader.h @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + SignalReaderEventTypeHalfBufferFilled, + SignalReaderEventTypeFullBufferFilled, +} SignalReaderEventType; + +typedef struct { + uint8_t* data; + size_t len; +} SignalReaderEventData; + +typedef struct { + SignalReaderEventType type; + SignalReaderEventData* data; +} SignalReaderEvent; + +typedef enum { + SignalReaderTimeUnit64Mhz, +} SignalReaderTimeUnit; + +typedef enum { + SignalReaderPolarityNormal, + SignalReaderPolarityInverted, +} SignalReaderPolarity; + +typedef enum { + SignalReaderTriggerNone, + SignalReaderTriggerRisingFallingEdge, +} SignalReaderTrigger; + +typedef void (*SignalReaderCallback)(SignalReaderEvent event, void* context); + +typedef struct SignalReader SignalReader; + +SignalReader* signal_reader_alloc(const GpioPin* gpio_pin, uint32_t size); + +void signal_reader_free(SignalReader* instance); + +void signal_reader_set_pull(SignalReader* instance, GpioPull pull); + +void signal_reader_set_polarity(SignalReader* instance, SignalReaderPolarity polarity); + +void signal_reader_set_sample_rate( + SignalReader* instance, + SignalReaderTimeUnit time_unit, + uint32_t time); + +void signal_reader_set_trigger(SignalReader* instance, SignalReaderTrigger trigger); + +void signal_reader_start(SignalReader* instance, SignalReaderCallback callback, void* context); + +void signal_reader_stop(SignalReader* instance); + +#ifdef __cplusplus +} +#endif diff --git a/lib/subghz/SConscript b/lib/subghz/SConscript index 96a87f665..ccdd3b0cf 100644 --- a/lib/subghz/SConscript +++ b/lib/subghz/SConscript @@ -13,6 +13,7 @@ env.Append( File("subghz_file_encoder_worker.h"), File("transmitter.h"), File("protocols/raw.h"), + File("protocols/public_api.h"), File("blocks/const.h"), File("blocks/decoder.h"), File("blocks/encoder.h"), diff --git a/lib/subghz/protocols/alutech_at_4n.h b/lib/subghz/protocols/alutech_at_4n.h index b7b5b9ede..a57152556 100644 --- a/lib/subghz/protocols/alutech_at_4n.h +++ b/lib/subghz/protocols/alutech_at_4n.h @@ -23,24 +23,6 @@ void* subghz_protocol_encoder_alutech_at_4n_alloc(SubGhzEnvironment* environment */ void subghz_protocol_encoder_alutech_at_4n_free(void* context); -/** - * Key generation from simple data. - * @param context Pointer to a SubGhzProtocolEncoderAlutech_at_4n instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number, 24 bit - * @param btn Button number, 8 bit - * @param cnt Counter value, 16 bit - * @param preset Modulation, SubGhzRadioPreset - * @return true On success - */ -bool subghz_protocol_alutech_at_4n_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - SubGhzRadioPreset* preset); - /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderAlutech_at_4n instance diff --git a/lib/subghz/protocols/bin_raw.c b/lib/subghz/protocols/bin_raw.c index 6fdfe7aa4..511846797 100644 --- a/lib/subghz/protocols/bin_raw.c +++ b/lib/subghz/protocols/bin_raw.c @@ -9,6 +9,8 @@ #include #include +#include + #define TAG "SubGhzProtocolBinRaw" //change very carefully, RAM ends at the most inopportune moment diff --git a/lib/subghz/protocols/bin_raw.h b/lib/subghz/protocols/bin_raw.h index 82775e575..26cc6ec3a 100644 --- a/lib/subghz/protocols/bin_raw.h +++ b/lib/subghz/protocols/bin_raw.h @@ -1,6 +1,7 @@ #pragma once #include "base.h" +#include "public_api.h" #define SUBGHZ_PROTOCOL_BIN_RAW_NAME "BinRAW" @@ -80,10 +81,6 @@ void subghz_protocol_decoder_bin_raw_feed(void* context, bool level, uint32_t du */ uint8_t subghz_protocol_decoder_bin_raw_get_hash_data(void* context); -void subghz_protocol_decoder_bin_raw_data_input_rssi( - SubGhzProtocolDecoderBinRAW* instance, - float rssi); - /** * Serialize data SubGhzProtocolDecoderBinRAW. * @param context Pointer to a SubGhzProtocolDecoderBinRAW instance diff --git a/lib/subghz/protocols/came_atomo.h b/lib/subghz/protocols/came_atomo.h index 8183877b0..c5e45a68d 100644 --- a/lib/subghz/protocols/came_atomo.h +++ b/lib/subghz/protocols/came_atomo.h @@ -14,22 +14,6 @@ void atomo_decrypt(uint8_t* buff); void atomo_encrypt(uint8_t* buff); -/** - * Key generation from simple data. - * @param context Pointer to a SubGhzProtocolEncoderCameAtomo instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number, 24 bit - * @param cnt Counter value, 16 bit - * @param preset Modulation, SubGhzRadioPreset - * @return true On success - */ -bool subghz_protocol_came_atomo_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint16_t cnt, - SubGhzRadioPreset* preset); - /** * Allocate SubGhzProtocolEncoderCameAtomo. * @param environment Pointer to a SubGhzEnvironment instance diff --git a/lib/subghz/protocols/faac_slh.h b/lib/subghz/protocols/faac_slh.h index 8d03d7907..16b6f031e 100644 --- a/lib/subghz/protocols/faac_slh.h +++ b/lib/subghz/protocols/faac_slh.h @@ -24,28 +24,6 @@ void* subghz_protocol_encoder_faac_slh_alloc(SubGhzEnvironment* environment); */ void subghz_protocol_encoder_faac_slh_free(void* context); -/** - * Key generation from simple data. - * @param context Pointer to a SubGhzProtocolEncoderFaacSLH instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number, 28 bit - * @param btn Button number, 4 bit - * @param cnt Counter value, 16 bit - * @param seed Seed value, 32 bit - * @param manufacture_name Name of manufacturer's key - * @param preset Modulation, SubGhzRadioPreset - * @return true On success - */ -bool subghz_protocol_faac_slh_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint32_t cnt, - uint32_t seed, - const char* manufacture_name, - SubGhzRadioPreset* preset); - /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderFaacSLH instance diff --git a/lib/subghz/protocols/keeloq.h b/lib/subghz/protocols/keeloq.h index a757e82d5..4abd14413 100644 --- a/lib/subghz/protocols/keeloq.h +++ b/lib/subghz/protocols/keeloq.h @@ -1,6 +1,7 @@ #pragma once #include "base.h" +#include "public_api.h" #define SUBGHZ_PROTOCOL_KEELOQ_NAME "KeeLoq" @@ -24,48 +25,6 @@ void* subghz_protocol_encoder_keeloq_alloc(SubGhzEnvironment* environment); */ void subghz_protocol_encoder_keeloq_free(void* context); -/** - * Key generation from simple data. - * @param context Pointer to a SubGhzProtocolEncoderKeeloq instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number, 28 bit - * @param btn Button number, 4 bit - * @param cnt Counter value, 16 bit - * @param manufacture_name Name of manufacturer's key - * @param preset Modulation, SubGhzRadioPreset - * @return true On success - */ -bool subghz_protocol_keeloq_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - const char* manufacture_name, - SubGhzRadioPreset* preset); - -/** - * Key generation for BFT. - * @param context Pointer to a SubGhzProtocolEncoderKeeloq instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number, 28 bit - * @param btn Button number, 4 bit - * @param cnt Counter value, 16 bit - * @param seed Seed value, 32 bit - * @param manufacture_name Name of manufacturer's key - * @param preset Modulation, SubGhzRadioPreset - * @return true On success - */ -bool subghz_protocol_keeloq_bft_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - uint32_t seed, - const char* manufacture_name, - SubGhzRadioPreset* preset); - /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderKeeloq instance diff --git a/lib/subghz/protocols/nice_flor_s.h b/lib/subghz/protocols/nice_flor_s.h index 5f8b30644..4d635d3fb 100644 --- a/lib/subghz/protocols/nice_flor_s.h +++ b/lib/subghz/protocols/nice_flor_s.h @@ -48,26 +48,6 @@ LevelDuration subghz_protocol_encoder_nice_flor_s_yield(void* context); uint64_t subghz_protocol_nice_flor_s_encrypt(uint64_t data, const char* file_name); -/** - * New remote generation. - * @param context Pointer to a SubGhzProtocolEncoderNiceFlorS instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number - * @param btn Button number, 4 bit - * @param cnt Counter value, 16 bit - * @param preset Modulation, SubGhzRadioPreset - * @param nice_one Nice One if true, Nice Flor S if false - * @return true On success - */ -bool subghz_protocol_nice_flor_s_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - SubGhzRadioPreset* preset, - bool nice_one); - /** * Allocate SubGhzProtocolDecoderNiceFlorS. * @param environment Pointer to a SubGhzEnvironment instance diff --git a/lib/subghz/protocols/public_api.h b/lib/subghz/protocols/public_api.h new file mode 100644 index 000000000..d7ae21c2a --- /dev/null +++ b/lib/subghz/protocols/public_api.h @@ -0,0 +1,217 @@ +#pragma once + +#include "../types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Key generation from simple data. + * @param context Pointer to a SubGhzProtocolEncoderSecPlus_v2 instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number, 32 bit + * @param btn Button number, 8 bit + * @param cnt Container value, 28 bit + * @param manufacture_name Name of manufacturer's key + * @param preset Modulation, SubGhzRadioPreset + * @return true On success + */ +bool subghz_protocol_secplus_v2_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint32_t cnt, + SubGhzRadioPreset* preset); + +/** + * Key generation from simple data. + * @param context Pointer to a SubGhzProtocolEncoderKeeloq instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number, 28 bit + * @param btn Button number, 4 bit + * @param cnt Counter value, 16 bit + * @param manufacture_name Name of manufacturer's key + * @param preset Modulation, SubGhzRadioPreset + * @return true On success + */ +bool subghz_protocol_keeloq_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + const char* manufacture_name, + SubGhzRadioPreset* preset); + +/** + * Key generation for BFT. + * @param context Pointer to a SubGhzProtocolEncoderKeeloq instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number, 28 bit + * @param btn Button number, 4 bit + * @param cnt Counter value, 16 bit + * @param seed Seed value, 32 bit + * @param manufacture_name Name of manufacturer's key + * @param preset Modulation, SubGhzRadioPreset + * @return true On success + */ +bool subghz_protocol_keeloq_bft_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + uint32_t seed, + const char* manufacture_name, + SubGhzRadioPreset* preset); + +/** + * Key generation from simple data. + * @param context Pointer to a SubGhzProtocolEncoderFaacSLH instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number, 28 bit + * @param btn Button number, 4 bit + * @param cnt Counter value, 16 bit + * @param seed Seed value, 32 bit + * @param manufacture_name Name of manufacturer's key + * @param preset Modulation, SubGhzRadioPreset + * @return true On success + */ +bool subghz_protocol_faac_slh_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint32_t cnt, + uint32_t seed, + const char* manufacture_name, + SubGhzRadioPreset* preset); + +/** + * Key generation from simple data. + * @param context Pointer to a SubGhzProtocolEncoderAlutech_at_4n instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number, 24 bit + * @param btn Button number, 8 bit + * @param cnt Counter value, 16 bit + * @param preset Modulation, SubGhzRadioPreset + * @return true On success + */ +bool subghz_protocol_alutech_at_4n_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + SubGhzRadioPreset* preset); + +/** + * Key generation from simple data. + * @param context Pointer to a SubGhzProtocolEncoderCameAtomo instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number, 24 bit + * @param cnt Counter value, 16 bit + * @param preset Modulation, SubGhzRadioPreset + * @return true On success + */ +bool subghz_protocol_came_atomo_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint16_t cnt, + SubGhzRadioPreset* preset); + +/** + * New remote generation. + * @param context Pointer to a SubGhzProtocolEncoderNiceFlorS instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number + * @param btn Button number, 4 bit + * @param cnt Counter value, 16 bit + * @param preset Modulation, SubGhzRadioPreset + * @param nice_one Nice One if true, Nice Flor S if false + * @return true On success + */ +bool subghz_protocol_nice_flor_s_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + SubGhzRadioPreset* preset, + bool nice_one); + +/** + * Key generation from simple data. + * @param context Pointer to a SubGhzProtocolEncoderStarLine instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number, 24 bit + * @param btn Button number, 8 bit + * @param cnt Counter value, 16 bit + * @param manufacture_name Name of manufacturer's key + * @param preset Modulation, SubGhzRadioPreset + * @return true On success + */ +bool subghz_protocol_star_line_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + const char* manufacture_name, + SubGhzRadioPreset* preset); + +/** + * Key generation from simple data. + * @param context Pointer to a SubGhzProtocolEncoderSomfyTelis instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number, 24 bit + * @param btn Button number, 8 bit + * @param cnt Counter value, 16 bit + * @param preset Modulation, SubGhzRadioPreset + * @return true On success + */ +bool subghz_protocol_somfy_telis_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + SubGhzRadioPreset* preset); + +/** + * Key generation from simple data. + * @param context Pointer to a SubGhzProtocolEncoderSomfyKeytis instance + * @param flipper_format Pointer to a FlipperFormat instance + * @param serial Serial number, 24 bit + * @param btn Button number, 8 bit + * @param cnt Counter value, 16 bit + * @param preset Modulation, SubGhzRadioPreset + * @return true On success + */ +bool subghz_protocol_somfy_keytis_create_data( + void* context, + FlipperFormat* flipper_format, + uint32_t serial, + uint8_t btn, + uint16_t cnt, + SubGhzRadioPreset* preset); + +typedef struct SubGhzProtocolDecoderBinRAW SubGhzProtocolDecoderBinRAW; + +void subghz_protocol_decoder_bin_raw_data_input_rssi( + SubGhzProtocolDecoderBinRAW* instance, + float rssi); + +/** + * Validation of fixed parts SubGhzProtocolDecoderSecPlus_v1. + * @param fixed fixed parts + * @return true On success + */ +bool subghz_protocol_secplus_v1_check_fixed(uint32_t fixed); + +#ifdef __cplusplus +} +#endif diff --git a/lib/subghz/protocols/secplus_v1.h b/lib/subghz/protocols/secplus_v1.h index 3490f2ca5..e01f8bcda 100644 --- a/lib/subghz/protocols/secplus_v1.h +++ b/lib/subghz/protocols/secplus_v1.h @@ -1,5 +1,7 @@ #pragma once + #include "base.h" +#include "public_api.h" #define SUBGHZ_PROTOCOL_SECPLUS_V1_NAME "Security+ 1.0" @@ -100,13 +102,6 @@ SubGhzProtocolStatus subghz_protocol_decoder_secplus_v1_serialize( SubGhzProtocolStatus subghz_protocol_decoder_secplus_v1_deserialize(void* context, FlipperFormat* flipper_format); -/** - * Validation of fixed parts SubGhzProtocolDecoderSecPlus_v1. - * @param fixed fixed parts - * @return true On success - */ -bool subghz_protocol_secplus_v1_check_fixed(uint32_t fixed); - /** * Getting a textual representation of the received data. * @param context Pointer to a SubGhzProtocolDecoderSecPlus_v1 instance diff --git a/lib/subghz/protocols/secplus_v2.h b/lib/subghz/protocols/secplus_v2.h index 0eea732af..9eb912a27 100644 --- a/lib/subghz/protocols/secplus_v2.h +++ b/lib/subghz/protocols/secplus_v2.h @@ -1,5 +1,7 @@ #pragma once + #include "base.h" +#include "public_api.h" #define SUBGHZ_PROTOCOL_SECPLUS_V2_NAME "Security+ 2.0" @@ -45,25 +47,6 @@ void subghz_protocol_encoder_secplus_v2_stop(void* context); */ LevelDuration subghz_protocol_encoder_secplus_v2_yield(void* context); -/** - * Key generation from simple data. - * @param context Pointer to a SubGhzProtocolEncoderSecPlus_v2 instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number, 32 bit - * @param btn Button number, 8 bit - * @param cnt Container value, 28 bit - * @param manufacture_name Name of manufacturer's key - * @param preset Modulation, SubGhzRadioPreset - * @return true On success - */ -bool subghz_protocol_secplus_v2_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint32_t cnt, - SubGhzRadioPreset* preset); - /** * Allocate SubGhzProtocolDecoderSecPlus_v2. * @param environment Pointer to a SubGhzEnvironment instance diff --git a/lib/subghz/protocols/somfy_keytis.h b/lib/subghz/protocols/somfy_keytis.h index 0e339c889..d7e8df109 100644 --- a/lib/subghz/protocols/somfy_keytis.h +++ b/lib/subghz/protocols/somfy_keytis.h @@ -24,24 +24,6 @@ void* subghz_protocol_encoder_somfy_keytis_alloc(SubGhzEnvironment* environment) */ void subghz_protocol_encoder_somfy_keytis_free(void* context); -/** - * Key generation from simple data. - * @param context Pointer to a SubGhzProtocolEncoderSomfyKeytis instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number, 24 bit - * @param btn Button number, 8 bit - * @param cnt Counter value, 16 bit - * @param preset Modulation, SubGhzRadioPreset - * @return true On success - */ -bool subghz_protocol_somfy_keytis_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - SubGhzRadioPreset* preset); - /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderSomfyKeytis instance diff --git a/lib/subghz/protocols/somfy_telis.h b/lib/subghz/protocols/somfy_telis.h index cb5cf8e96..a072079da 100644 --- a/lib/subghz/protocols/somfy_telis.h +++ b/lib/subghz/protocols/somfy_telis.h @@ -24,24 +24,6 @@ void* subghz_protocol_encoder_somfy_telis_alloc(SubGhzEnvironment* environment); */ void subghz_protocol_encoder_somfy_telis_free(void* context); -/** - * Key generation from simple data. - * @param context Pointer to a SubGhzProtocolEncoderSomfyTelis instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number, 24 bit - * @param btn Button number, 8 bit - * @param cnt Counter value, 16 bit - * @param preset Modulation, SubGhzRadioPreset - * @return true On success - */ -bool subghz_protocol_somfy_telis_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - SubGhzRadioPreset* preset); - /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderSomfyTelis instance diff --git a/lib/subghz/protocols/star_line.h b/lib/subghz/protocols/star_line.h index 851819ec7..e7b15ca0b 100644 --- a/lib/subghz/protocols/star_line.h +++ b/lib/subghz/protocols/star_line.h @@ -24,26 +24,6 @@ void* subghz_protocol_encoder_star_line_alloc(SubGhzEnvironment* environment); */ void subghz_protocol_encoder_star_line_free(void* context); -/** - * Key generation from simple data. - * @param context Pointer to a SubGhzProtocolEncoderStarLine instance - * @param flipper_format Pointer to a FlipperFormat instance - * @param serial Serial number, 24 bit - * @param btn Button number, 8 bit - * @param cnt Counter value, 16 bit - * @param manufacture_name Name of manufacturer's key - * @param preset Modulation, SubGhzRadioPreset - * @return true On success - */ -bool subghz_protocol_star_line_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - const char* manufacture_name, - SubGhzRadioPreset* preset); - /** * Deserialize and generating an upload to send. * @param context Pointer to a SubGhzProtocolEncoderStarLine instance diff --git a/lib/subghz/subghz_protocol_registry.h b/lib/subghz/subghz_protocol_registry.h index e5cf75cda..2dfa9ce8b 100644 --- a/lib/subghz/subghz_protocol_registry.h +++ b/lib/subghz/subghz_protocol_registry.h @@ -10,81 +10,6 @@ extern const SubGhzProtocolRegistry subghz_protocol_registry; typedef struct SubGhzProtocolDecoderBinRAW SubGhzProtocolDecoderBinRAW; -bool subghz_protocol_secplus_v2_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint32_t cnt, - SubGhzRadioPreset* preset); - -bool subghz_protocol_keeloq_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - const char* manufacture_name, - SubGhzRadioPreset* preset); - -bool subghz_protocol_keeloq_bft_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - uint32_t seed, - const char* manufacture_name, - SubGhzRadioPreset* preset); - -void subghz_protocol_decoder_bin_raw_data_input_rssi( - SubGhzProtocolDecoderBinRAW* instance, - float rssi); - -bool subghz_protocol_secplus_v1_check_fixed(uint32_t fixed); - -bool subghz_protocol_faac_slh_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint32_t cnt, - uint32_t seed, - const char* manufacture_name, - SubGhzRadioPreset* preset); - -bool subghz_protocol_came_atomo_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint16_t cnt, - SubGhzRadioPreset* preset); - -bool subghz_protocol_somfy_telis_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - SubGhzRadioPreset* preset); - -bool subghz_protocol_nice_flor_s_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - SubGhzRadioPreset* preset, - bool nice_one); - -bool subghz_protocol_alutech_at_4n_create_data( - void* context, - FlipperFormat* flipper_format, - uint32_t serial, - uint8_t btn, - uint16_t cnt, - SubGhzRadioPreset* preset); - #ifdef __cplusplus } #endif diff --git a/lib/toolbox/SConscript b/lib/toolbox/SConscript index 6f43932d5..eb972a1f8 100644 --- a/lib/toolbox/SConscript +++ b/lib/toolbox/SConscript @@ -31,6 +31,8 @@ env.Append( File("protocols/protocol_dict.h"), File("pretty_format.h"), File("hex.h"), + File("simple_array.h"), + File("bit_buffer.h"), ], ) diff --git a/lib/toolbox/bit_buffer.c b/lib/toolbox/bit_buffer.c new file mode 100644 index 000000000..1943ee833 --- /dev/null +++ b/lib/toolbox/bit_buffer.c @@ -0,0 +1,336 @@ +#include "bit_buffer.h" + +#include + +#define BITS_IN_BYTE (8) + +struct BitBuffer { + uint8_t* data; + uint8_t* parity; + size_t capacity_bytes; + size_t size_bits; +}; + +BitBuffer* bit_buffer_alloc(size_t capacity_bytes) { + furi_assert(capacity_bytes); + + BitBuffer* buf = malloc(sizeof(BitBuffer)); + + buf->data = malloc(capacity_bytes); + size_t parity_buf_size = (capacity_bytes + BITS_IN_BYTE - 1) / BITS_IN_BYTE; + buf->parity = malloc(parity_buf_size); + buf->capacity_bytes = capacity_bytes; + buf->size_bits = 0; + + return buf; +} + +void bit_buffer_free(BitBuffer* buf) { + furi_assert(buf); + + free(buf->data); + free(buf->parity); + free(buf); +} + +void bit_buffer_reset(BitBuffer* buf) { + furi_assert(buf); + + memset(buf->data, 0, buf->capacity_bytes); + size_t parity_buf_size = (buf->capacity_bytes + BITS_IN_BYTE - 1) / BITS_IN_BYTE; + memset(buf->parity, 0, parity_buf_size); + buf->size_bits = 0; +} + +void bit_buffer_copy(BitBuffer* buf, const BitBuffer* other) { + furi_assert(buf); + furi_assert(other); + + if(buf == other) return; + + furi_assert(buf->capacity_bytes * BITS_IN_BYTE >= other->size_bits); + + memcpy(buf->data, other->data, bit_buffer_get_size_bytes(other)); + buf->size_bits = other->size_bits; +} + +void bit_buffer_copy_right(BitBuffer* buf, const BitBuffer* other, size_t start_index) { + furi_assert(buf); + furi_assert(other); + furi_assert(bit_buffer_get_size_bytes(other) > start_index); + furi_assert(buf->capacity_bytes >= bit_buffer_get_size_bytes(other) - start_index); + + memcpy(buf->data, other->data + start_index, bit_buffer_get_size_bytes(other) - start_index); + buf->size_bits = other->size_bits - start_index * BITS_IN_BYTE; +} + +void bit_buffer_copy_left(BitBuffer* buf, const BitBuffer* other, size_t end_index) { + furi_assert(buf); + furi_assert(other); + furi_assert(bit_buffer_get_capacity_bytes(buf) >= end_index); + furi_assert(bit_buffer_get_size_bytes(other) >= end_index); + + memcpy(buf->data, other->data, end_index); + buf->size_bits = end_index * BITS_IN_BYTE; +} + +void bit_buffer_copy_bytes(BitBuffer* buf, const uint8_t* data, size_t size_bytes) { + furi_assert(buf); + furi_assert(data); + furi_assert(buf->capacity_bytes >= size_bytes); + + memcpy(buf->data, data, size_bytes); + buf->size_bits = size_bytes * BITS_IN_BYTE; +} + +void bit_buffer_copy_bits(BitBuffer* buf, const uint8_t* data, size_t size_bits) { + furi_assert(buf); + furi_assert(data); + furi_assert(buf->capacity_bytes * BITS_IN_BYTE >= size_bits); + + size_t size_bytes = (size_bits + BITS_IN_BYTE - 1) / BITS_IN_BYTE; + memcpy(buf->data, data, size_bytes); + buf->size_bits = size_bits; +} + +void bit_buffer_copy_bytes_with_parity(BitBuffer* buf, const uint8_t* data, size_t size_bits) { + furi_assert(buf); + furi_assert(data); + + size_t bits_processed = 0; + size_t curr_byte = 0; + + if(size_bits < BITS_IN_BYTE + 1) { + buf->size_bits = size_bits; + buf->data[0] = data[0]; + } else { + furi_assert(size_bits % (BITS_IN_BYTE + 1) == 0); + while(bits_processed < size_bits) { + buf->data[curr_byte] = data[bits_processed / BITS_IN_BYTE] >> + (bits_processed % BITS_IN_BYTE); + buf->data[curr_byte] |= data[bits_processed / BITS_IN_BYTE + 1] + << (BITS_IN_BYTE - bits_processed % BITS_IN_BYTE); + uint8_t bit = + FURI_BIT(data[bits_processed / BITS_IN_BYTE + 1], bits_processed % BITS_IN_BYTE); + + if(bits_processed % BITS_IN_BYTE) { + buf->parity[curr_byte / BITS_IN_BYTE] = bit; + } else { + buf->parity[curr_byte / BITS_IN_BYTE] |= bit << (bits_processed % BITS_IN_BYTE); + } + bits_processed += BITS_IN_BYTE + 1; + curr_byte++; + } + buf->size_bits = curr_byte * BITS_IN_BYTE; + } +} + +void bit_buffer_write_bytes(const BitBuffer* buf, void* dest, size_t size_bytes) { + furi_assert(buf); + furi_assert(dest); + furi_assert(bit_buffer_get_size_bytes(buf) <= size_bytes); + + memcpy(dest, buf->data, bit_buffer_get_size_bytes(buf)); +} + +void bit_buffer_write_bytes_with_parity( + const BitBuffer* buf, + void* dest, + size_t size_bytes, + size_t* bits_written) { + furi_assert(buf); + furi_assert(dest); + furi_assert(bits_written); + + size_t buf_size_bytes = bit_buffer_get_size_bytes(buf); + size_t buf_size_with_parity_bytes = + (buf_size_bytes * (BITS_IN_BYTE + 1) + BITS_IN_BYTE) / BITS_IN_BYTE; + furi_assert(buf_size_with_parity_bytes <= size_bytes); + + uint8_t next_par_bit = 0; + uint16_t curr_bit_pos = 0; + uint8_t* bitstream = dest; + + for(size_t i = 0; i < buf_size_bytes; i++) { + next_par_bit = FURI_BIT(buf->parity[i / BITS_IN_BYTE], i % BITS_IN_BYTE); + if(curr_bit_pos % BITS_IN_BYTE == 0) { + bitstream[curr_bit_pos / BITS_IN_BYTE] = buf->data[i]; + curr_bit_pos += BITS_IN_BYTE; + bitstream[curr_bit_pos / BITS_IN_BYTE] = next_par_bit; + curr_bit_pos++; + } else { + bitstream[curr_bit_pos / BITS_IN_BYTE] |= buf->data[i] + << (curr_bit_pos % BITS_IN_BYTE); + bitstream[curr_bit_pos / BITS_IN_BYTE + 1] = + buf->data[i] >> (BITS_IN_BYTE - curr_bit_pos % BITS_IN_BYTE); + bitstream[curr_bit_pos / BITS_IN_BYTE + 1] |= next_par_bit + << (curr_bit_pos % BITS_IN_BYTE); + curr_bit_pos += BITS_IN_BYTE + 1; + } + } + + *bits_written = curr_bit_pos; +} + +void bit_buffer_write_bytes_mid( + const BitBuffer* buf, + void* dest, + size_t start_index, + size_t size_bytes) { + furi_assert(buf); + furi_assert(dest); + furi_assert(start_index + size_bytes <= bit_buffer_get_size_bytes(buf)); + + memcpy(dest, buf->data + start_index, size_bytes); +} + +bool bit_buffer_has_partial_byte(const BitBuffer* buf) { + furi_assert(buf); + + return (buf->size_bits % BITS_IN_BYTE) != 0; +} + +bool bit_buffer_starts_with_byte(const BitBuffer* buf, uint8_t byte) { + furi_assert(buf); + + return bit_buffer_get_size_bytes(buf) && (buf->data[0] == byte); +} + +size_t bit_buffer_get_capacity_bytes(const BitBuffer* buf) { + furi_assert(buf); + + return buf->capacity_bytes; +} + +size_t bit_buffer_get_size(const BitBuffer* buf) { + furi_assert(buf); + + return buf->size_bits; +} + +size_t bit_buffer_get_size_bytes(const BitBuffer* buf) { + furi_assert(buf); + + return (buf->size_bits / BITS_IN_BYTE) + (buf->size_bits % BITS_IN_BYTE ? 1 : 0); +} + +uint8_t bit_buffer_get_byte(const BitBuffer* buf, size_t index) { + furi_assert(buf); + furi_assert(buf->capacity_bytes > index); + + return buf->data[index]; +} + +uint8_t bit_buffer_get_byte_from_bit(const BitBuffer* buf, size_t index_bits) { + furi_assert(buf); + furi_assert(buf->capacity_bytes * BITS_IN_BYTE > index_bits); + + const size_t byte_index = index_bits / BITS_IN_BYTE; + const size_t bit_offset = index_bits % BITS_IN_BYTE; + + const uint8_t lo = buf->data[byte_index] >> bit_offset; + const uint8_t hi = buf->data[byte_index + 1] << (BITS_IN_BYTE - bit_offset); + + return lo | hi; +} + +const uint8_t* bit_buffer_get_data(const BitBuffer* buf) { + furi_assert(buf); + + return buf->data; +} + +const uint8_t* bit_buffer_get_parity(const BitBuffer* buf) { + furi_assert(buf); + + return buf->parity; +} + +void bit_buffer_set_byte(BitBuffer* buf, size_t index, uint8_t byte) { + furi_assert(buf); + + const size_t size_bytes = bit_buffer_get_size_bytes(buf); + furi_assert(size_bytes > index); + + buf->data[index] = byte; +} + +void bit_buffer_set_byte_with_parity(BitBuffer* buff, size_t index, uint8_t byte, bool parity) { + furi_assert(buff); + furi_assert(buff->size_bits / BITS_IN_BYTE > index); + + buff->data[index] = byte; + if((index % BITS_IN_BYTE) == 0) { + buff->parity[index / BITS_IN_BYTE] = parity; + } else { + buff->parity[index / BITS_IN_BYTE] |= parity << (index % BITS_IN_BYTE); + } +} + +void bit_buffer_set_size(BitBuffer* buf, size_t new_size) { + furi_assert(buf); + furi_assert(buf->capacity_bytes * BITS_IN_BYTE >= new_size); + + buf->size_bits = new_size; +} + +void bit_buffer_set_size_bytes(BitBuffer* buf, size_t new_size_bytes) { + furi_assert(buf); + furi_assert(buf->capacity_bytes >= new_size_bytes); + + buf->size_bits = new_size_bytes * BITS_IN_BYTE; +} + +void bit_buffer_append(BitBuffer* buf, const BitBuffer* other) { + bit_buffer_append_right(buf, other, 0); +} + +void bit_buffer_append_right(BitBuffer* buf, const BitBuffer* other, size_t start_index) { + furi_assert(buf); + furi_assert(other); + + const size_t size_bytes = bit_buffer_get_size_bytes(buf); + const size_t other_size_bytes = bit_buffer_get_size_bytes(other) - start_index; + + furi_assert(buf->capacity_bytes >= size_bytes + other_size_bytes); + + memcpy(buf->data + size_bytes, other->data + start_index, other_size_bytes); + buf->size_bits += other->size_bits - start_index * BITS_IN_BYTE; +} + +void bit_buffer_append_byte(BitBuffer* buf, uint8_t byte) { + furi_assert(buf); + + const size_t data_size_bytes = bit_buffer_get_size_bytes(buf); + const size_t new_data_size_bytes = data_size_bytes + 1; + furi_assert(new_data_size_bytes <= buf->capacity_bytes); + + buf->data[data_size_bytes] = byte; + buf->size_bits = new_data_size_bytes * BITS_IN_BYTE; +} + +void bit_buffer_append_bytes(BitBuffer* buf, const uint8_t* data, size_t size_bytes) { + furi_assert(buf); + furi_assert(data); + + const size_t buf_size_bytes = bit_buffer_get_size_bytes(buf); + furi_assert(buf->capacity_bytes >= buf_size_bytes + size_bytes); + + memcpy(&buf->data[buf_size_bytes], data, size_bytes); + buf->size_bits += size_bytes * BITS_IN_BYTE; +} + +void bit_buffer_append_bit(BitBuffer* buf, bool bit) { + furi_assert(buf); + furi_assert( + bit_buffer_get_size_bytes(buf) <= + (buf->capacity_bytes - (bit_buffer_has_partial_byte(buf) ? 0 : 1))); + + if(bit) { + const size_t byte_index = buf->size_bits / BITS_IN_BYTE; + const size_t bit_offset = (buf->size_bits % BITS_IN_BYTE); + buf->data[byte_index] |= 1U << bit_offset; + } + + buf->size_bits++; +} diff --git a/lib/toolbox/bit_buffer.h b/lib/toolbox/bit_buffer.h new file mode 100644 index 000000000..5c50e729c --- /dev/null +++ b/lib/toolbox/bit_buffer.h @@ -0,0 +1,325 @@ +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct BitBuffer BitBuffer; + +// Construction, deletion, reset + +/** + * Allocate a BitBuffer instance. + * + * @param [in] capacity_bytes maximum buffer capacity, in bytes + * @return pointer to the allocated BitBuffer instance + */ +BitBuffer* bit_buffer_alloc(size_t capacity_bytes); + +/** + * Delete a BitBuffer instance. + * + * @param [in,out] buf pointer to a BitBuffer instance + */ +void bit_buffer_free(BitBuffer* buf); + +/** + * Clear all data from a BitBuffer instance. + * + * @param [in,out] buf pointer to a BitBuffer instance + */ +void bit_buffer_reset(BitBuffer* buf); + +// Copy and write + +/** + * Copy another BitBuffer instance's contents to this one, replacing + * all of the original data. + * The destination capacity must be no less than the source data size. + * + * @param [in,out] buf pointer to a BitBuffer instance to copy into + * @param [in] other pointer to a BitBuffer instance to copy from + * @note + */ +void bit_buffer_copy(BitBuffer* buf, const BitBuffer* other); + +/** + * Copy all BitBuffer instance's contents to this one, starting from start_index, + * replacing all of the original data. + * The destination capacity must be no less than the source data size + * counting from start_index. + * + * @param [in,out] buf pointer to a BitBuffer instance to copy into + * @param [in] other pointer to a BitBuffer instance to copy from + * @param [in] start_index index to begin copying source data from + */ +void bit_buffer_copy_right(BitBuffer* buf, const BitBuffer* other, size_t start_index); + +/** + * Copy all BitBuffer instance's contents to this one, ending with end_index, + * replacing all of the original data. + * The destination capacity must be no less than the source data size + * counting to end_index. + * + * @param [in,out] buf pointer to a BitBuffer instance to copy into + * @param [in] other pointer to a BitBuffer instance to copy from + * @param [in] end_index index to end copying source data at + */ +void bit_buffer_copy_left(BitBuffer* buf, const BitBuffer* other, size_t end_index); + +/** + * Copy a byte array to a BitBuffer instance, replacing all of the original data. + * The destination capacity must be no less than the source data size. + * + * @param [in,out] buf pointer to a BitBuffer instance to copy into + * @param [in] data pointer to the byte array to be copied + * @param [in] size_bytes size of the data to be copied, in bytes + */ +void bit_buffer_copy_bytes(BitBuffer* buf, const uint8_t* data, size_t size_bytes); + +/** + * Copy a byte array to a BitBuffer instance, replacing all of the original data. + * The destination capacity must be no less than the source data size. + * + * @param [in,out] buf pointer to a BitBuffer instance to copy into + * @param [in] data pointer to the byte array to be copied + * @param [in] size_bits size of the data to be copied, in bits + */ +void bit_buffer_copy_bits(BitBuffer* buf, const uint8_t* data, size_t size_bits); + +/** + * Copy a byte with parity array to a BitBuffer instance, replacing all of the original data. + * The destination capacity must be no less than the source data size. + * + * @param [in,out] buf pointer to a BitBuffer instance to copy into + * @param [in] data pointer to the byte array to be copied + * @param [in] size_bitss size of the data to be copied, in bits + */ +void bit_buffer_copy_bytes_with_parity(BitBuffer* buf, const uint8_t* data, size_t size_bits); + +/** + * Write a BitBuffer instance's entire contents to an arbitrary memory location. + * The destination memory must be allocated. Additionally, the destination + * capacity must be no less than the source data size. + * + * @param [in] buf pointer to a BitBuffer instance to write from + * @param [out] dest pointer to the destination memory location + * @param [in] size_bytes maximum destination data size, in bytes + */ +void bit_buffer_write_bytes(const BitBuffer* buf, void* dest, size_t size_bytes); + +/** + * Write a BitBuffer instance's entire contents to an arbitrary memory location. + * Additionally, place a parity bit after each byte. + * The destination memory must be allocated. Additionally, the destination + * capacity must be no less than the source data size plus parity. + * + * @param [in] buf pointer to a BitBuffer instance to write from + * @param [out] dest pointer to the destination memory location + * @param [in] size_bytes maximum destination data size, in bytes + * @param [out] bits_written actual number of bits writen, in bits + */ +void bit_buffer_write_bytes_with_parity( + const BitBuffer* buf, + void* dest, + size_t size_bytes, + size_t* bits_written); + +/** + * Write a slice of BitBuffer instance's contents to an arbitrary memory location. + * The destination memory must be allocated. Additionally, the destination + * capacity must be no less than the requested slice size. + * + * @param [in] buf pointer to a BitBuffer instance to write from + * @param [out] dest pointer to the destination memory location + * @param [in] start_index index to begin copying source data from + * @param [in] size_bytes data slice size, in bytes + */ +void bit_buffer_write_bytes_mid( + const BitBuffer* buf, + void* dest, + size_t start_index, + size_t size_bytes); + +// Checks + +/** + * Check whether a BitBuffer instance contains a partial byte (i.e. the bit count + * is not divisible by 8). + * + * @param [in] buf pointer to a BitBuffer instance to be checked + * @return true if the instance contains a partial byte, false otherwise + */ +bool bit_buffer_has_partial_byte(const BitBuffer* buf); + +/** + * Check whether a BitBuffer instance's contents start with the designated byte. + * + * @param [in] buf pointer to a BitBuffer instance to be checked + * @param [in] byte byte value to be checked against + * @return true if data starts with designated byte, false otherwise + */ +bool bit_buffer_starts_with_byte(const BitBuffer* buf, uint8_t byte); + +// Getters + +/** + * Get a BitBuffer instance's capacity (i.e. the maximum possible amount of data), in bytes. + * + * @param [in] buf pointer to a BitBuffer instance to be queried + * @return capacity, in bytes + */ +size_t bit_buffer_get_capacity_bytes(const BitBuffer* buf); + +/** + * Get a BitBuffer instance's data size (i.e. the amount of stored data), in bits. + * Might be not divisible by 8 (see bit_buffer_is_partial_byte). + * + * @param [in] buf pointer to a BitBuffer instance to be queried + * @return data size, in bits. + */ +size_t bit_buffer_get_size(const BitBuffer* buf); + +/** + * Get a BitBuffer instance's data size (i.e. the amount of stored data), in bytes. + * If a partial byte is present, it is also counted. + * + * @param [in] buf pointer to a BitBuffer instance to be queried + * @return data size, in bytes. + */ +size_t bit_buffer_get_size_bytes(const BitBuffer* buf); + +/** + * Get a byte value at a specified index in a BitBuffer instance. + * The index must be valid (i.e. less than the instance's data size in bytes). + * + * @param [in] buf pointer to a BitBuffer instance to be queried + * @param [in] index index of the byte in question + */ +uint8_t bit_buffer_get_byte(const BitBuffer* buf, size_t index); + +/** + * Get a byte value starting from the specified bit index in a BitBuffer instance. + * The resulting byte might correspond to a single byte (if the index is a multiple + * of 8), or two overlapping bytes combined. + * The index must be valid (i.e. less than the instance's data size in bits). + * + * @param [in] buf pointer to a BitBuffer instance to be queried + * @param [in] index bit index of the byte in question + */ +uint8_t bit_buffer_get_byte_from_bit(const BitBuffer* buf, size_t index_bits); + +/** + * Get the pointer to a BitBuffer instance's underlying data. + * + * @param [in] buf pointer to a BitBuffer instance to be queried + * @return pointer to the underlying data + */ +const uint8_t* bit_buffer_get_data(const BitBuffer* buf); + +/** + * Get the pointer to a BitBuffer instance's underlying data. + * + * @param [in] buf pointer to a BitBuffer instance to be queried + * @return pointer to the underlying data + */ +const uint8_t* bit_buffer_get_parity(const BitBuffer* buf); + +// Setters + +/** + * Set byte value at a specified index in a BitBuffer instance. + * The index must be valid (i.e. less than the instance's data size in bytes). + * + * @param [in,out] buf pointer to a BitBuffer instance to be modified + * @param [in] index index of the byte in question + * @param [in] byte byte value to be set at index + */ +void bit_buffer_set_byte(BitBuffer* buf, size_t index, uint8_t byte); + +/** + * Set byte and parity bit value at a specified index in a BitBuffer instance. + * The index must be valid (i.e. less than the instance's data size in bytes). + * + * @param [in,out] buf pointer to a BitBuffer instance to be modified + * @param [in] index index of the byte in question + * @param [in] byte byte value to be set at index + * @param [in] parity parity bit value to be set at index + */ +void bit_buffer_set_byte_with_parity(BitBuffer* buff, size_t index, uint8_t byte, bool parity); + +/** + * Resize a BitBuffer instance to a new size, in bits. + * @warning May cause bugs. Use only if absolutely necessary. + * + * @param [in,out] buf pointer to a BitBuffer instance to be resized + * @param [in] new_size the new size of the buffer, in bits + */ +void bit_buffer_set_size(BitBuffer* buf, size_t new_size); + +/** + * Resize a BitBuffer instance to a new size, in bytes. + * @warning May cause bugs. Use only if absolutely necessary. + * + * @param [in,out] buf pointer to a BitBuffer instance to be resized + * @param [in] new_size_bytes the new size of the buffer, in bytes + */ +void bit_buffer_set_size_bytes(BitBuffer* buf, size_t new_size_bytes); + +// Modification + +/** + * Append all BitBuffer's instance contents to this one. The destination capacity + * must be no less than its original data size plus source data size. + * + * @param [in,out] buf pointer to a BitBuffer instance to be appended to + * @param [in] other pointer to a BitBuffer instance to be appended + */ +void bit_buffer_append(BitBuffer* buf, const BitBuffer* other); + +/** + * Append a BitBuffer's instance contents to this one, starting from start_index. + * The destination capacity must be no less than the source data size + * counting from start_index. + * + * @param [in,out] buf pointer to a BitBuffer instance to be appended to + * @param [in] other pointer to a BitBuffer instance to be appended + * @param [in] start_index index to begin copying source data from + */ +void bit_buffer_append_right(BitBuffer* buf, const BitBuffer* other, size_t start_index); + +/** + * Append a byte to a BitBuffer instance. + * The destination capacity must be no less its original data size plus one. + * + * @param [in,out] buf pointer to a BitBuffer instance to be appended to + * @param [in] byte byte value to be appended + */ +void bit_buffer_append_byte(BitBuffer* buf, uint8_t byte); + +/** + * Append a byte array to a BitBuffer instance. + * The destination capacity must be no less its original data size plus source data size. + * + * @param [in,out] buf pointer to a BitBuffer instance to be appended to + * @param [in] data pointer to the byte array to be appended + * @param [in] size_bytes size of the data to be appended, in bytes + */ +void bit_buffer_append_bytes(BitBuffer* buf, const uint8_t* data, size_t size_bytes); + +/** + * Append a bit to a BitBuffer instance. + * The destination capacity must be sufficient to accomodate the additional bit. + * + * @param [in,out] buf pointer to a BitBuffer instance to be appended to + * @param [in] bit bit value to be appended + */ +void bit_buffer_append_bit(BitBuffer* buf, bool bit); + +#ifdef __cplusplus +} +#endif diff --git a/lib/toolbox/buffer_stream.c b/lib/toolbox/buffer_stream.c index 37b2514ef..e8cb334d5 100644 --- a/lib/toolbox/buffer_stream.c +++ b/lib/toolbox/buffer_stream.c @@ -112,7 +112,7 @@ bool buffer_stream_send_from_isr(BufferStream* buffer_stream, const uint8_t* dat return result; } -Buffer* buffer_stream_receive(BufferStream* buffer_stream, TickType_t timeout) { +Buffer* buffer_stream_receive(BufferStream* buffer_stream, uint32_t timeout) { Buffer* buffer; size_t size = furi_stream_buffer_receive(buffer_stream->stream, &buffer, sizeof(Buffer*), timeout); diff --git a/lib/toolbox/buffer_stream.h b/lib/toolbox/buffer_stream.h index 9db547753..5c3dc0a34 100644 --- a/lib/toolbox/buffer_stream.h +++ b/lib/toolbox/buffer_stream.h @@ -69,7 +69,7 @@ bool buffer_stream_send_from_isr(BufferStream* buffer_stream, const uint8_t* dat * @param timeout * @return Buffer* */ -Buffer* buffer_stream_receive(BufferStream* buffer_stream, TickType_t timeout); +Buffer* buffer_stream_receive(BufferStream* buffer_stream, uint32_t timeout); /** * @brief Get stream overrun count diff --git a/lib/toolbox/simple_array.c b/lib/toolbox/simple_array.c new file mode 100644 index 000000000..7aed8e34b --- /dev/null +++ b/lib/toolbox/simple_array.c @@ -0,0 +1,127 @@ +#include "simple_array.h" + +#include + +struct SimpleArray { + const SimpleArrayConfig* config; + SimpleArrayElement* data; + uint32_t count; +}; + +SimpleArray* simple_array_alloc(const SimpleArrayConfig* config) { + SimpleArray* instance = malloc(sizeof(SimpleArray)); + instance->config = config; + return instance; +} + +void simple_array_free(SimpleArray* instance) { + furi_assert(instance); + + simple_array_reset(instance); + free(instance); +} + +void simple_array_init(SimpleArray* instance, uint32_t count) { + furi_assert(instance); + furi_assert(count > 0); + + simple_array_reset(instance); + + instance->data = malloc(count * instance->config->type_size); + instance->count = count; + + SimpleArrayInit init = instance->config->init; + if(init) { + for(uint32_t i = 0; i < instance->count; ++i) { + init(simple_array_get(instance, i)); + } + } +} + +void simple_array_reset(SimpleArray* instance) { + furi_assert(instance); + + if(instance->data) { + SimpleArrayReset reset = instance->config->reset; + + if(reset) { + for(uint32_t i = 0; i < instance->count; ++i) { + reset(simple_array_get(instance, i)); + } + } + + free(instance->data); + + instance->count = 0; + instance->data = NULL; + } +} + +void simple_array_copy(SimpleArray* instance, const SimpleArray* other) { + furi_assert(instance); + furi_assert(other); + furi_assert(instance->config == other->config); + + simple_array_reset(instance); + + if(other->count == 0) { + return; + } + + simple_array_init(instance, other->count); + + SimpleArrayCopy copy = instance->config->copy; + if(copy) { + for(uint32_t i = 0; i < other->count; ++i) { + copy(simple_array_get(instance, i), simple_array_cget(other, i)); + } + } else { + memcpy(instance->data, other->data, other->count * instance->config->type_size); + } +} + +bool simple_array_is_equal(const SimpleArray* instance, const SimpleArray* other) { + furi_assert(instance); + furi_assert(other); + + // Equal if the same object + if(instance == other) return true; + + return (instance->config == other->config) && (instance->count == other->count) && + ((instance->data == other->data) || (instance->data == NULL) || (other->data == NULL) || + (memcmp(instance->data, other->data, other->count) == 0)); +} + +uint32_t simple_array_get_count(const SimpleArray* instance) { + furi_assert(instance); + return instance->count; +} + +SimpleArrayElement* simple_array_get(SimpleArray* instance, uint32_t index) { + furi_assert(instance); + furi_assert(index < instance->count); + + return instance->data + index * instance->config->type_size; +} + +const SimpleArrayElement* simple_array_cget(const SimpleArray* instance, uint32_t index) { + return simple_array_get((SimpleArrayElement*)instance, index); +} + +SimpleArrayData* simple_array_get_data(SimpleArray* instance) { + furi_assert(instance); + furi_assert(instance->data); + + return instance->data; +} + +const SimpleArrayData* simple_array_cget_data(const SimpleArray* instance) { + return simple_array_get_data((SimpleArray*)instance); +} + +const SimpleArrayConfig simple_array_config_uint8_t = { + .init = NULL, + .copy = NULL, + .reset = NULL, + .type_size = sizeof(uint8_t), +}; diff --git a/lib/toolbox/simple_array.h b/lib/toolbox/simple_array.h new file mode 100644 index 000000000..a608db08d --- /dev/null +++ b/lib/toolbox/simple_array.h @@ -0,0 +1,148 @@ +/** + * @file simple_array.h + * + * @brief This file provides a simple (non-type safe) array for elements with + * (optional) in-place construction support. + * + * No append, remove or take operations are supported. + * Instead, the user must call simple_array_init() in order to reserve the memory for n elements. + * In case if init() is specified in the configuration, then the elements are constructed in-place. + * + * To clear all elements from the array, call simple_array_reset(), which will also call reset() + * for each element in case if it was specified in the configuration. This is useful if a custom + * destructor is required for a particular type. Calling simple_array_free() will also result in a + * simple_array_reset() call automatically. + * + */ +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct SimpleArray SimpleArray; + +typedef void SimpleArrayData; +typedef void SimpleArrayElement; + +typedef void (*SimpleArrayInit)(SimpleArrayElement* elem); +typedef void (*SimpleArrayReset)(SimpleArrayElement* elem); +typedef void (*SimpleArrayCopy)(SimpleArrayElement* elem, const SimpleArrayElement* other); + +/** Simple Array configuration structure. Defined per type. */ +typedef struct { + SimpleArrayInit init; /**< Initialisation (in-place constructor) method. */ + SimpleArrayReset reset; /**< Reset (custom destructor) method. */ + SimpleArrayCopy copy; /**< Copy (custom copy-constructor) method. */ + const size_t type_size; /** Type size, in bytes. */ +} SimpleArrayConfig; + +/** + * Allocate a SimpleArray instance with the given configuration. + * + * @param [in] config Pointer to the type-specific configuration + * @return Pointer to the allocated SimpleArray instance + */ +SimpleArray* simple_array_alloc(const SimpleArrayConfig* config); + +/** + * Free a SimpleArray instance and release its contents. + * + * @param [in] instance Pointer to the SimpleArray instance to be freed + */ +void simple_array_free(SimpleArray* instance); + +/** + * Initialise a SimpleArray instance by allocating additional space to contain + * the requested number of elements. + * If init() is specified in the config, then it is called for each element, + * otherwise the data is filled with zeroes. + * + * @param [in] instance Pointer to the SimpleArray instance to be init'd + * @param [in] count Number of elements to be allocated and init'd + */ +void simple_array_init(SimpleArray* instance, uint32_t count); + +/** + * Reset a SimpleArray instance and delete all of its elements. + * If reset() is specified in the config, then it is called for each element, + * otherwise the data is simply free()'d. + * + * @param [in] instance Pointer to the SimpleArray instance to be reset + */ +void simple_array_reset(SimpleArray* instance); + +/** + * Copy (duplicate) another SimpleArray instance to this one. + * If copy() is specified in the config, then it is called for each element, + * otherwise the data is simply memcpy()'d. + * + * @param [in] instance Pointer to the SimpleArray instance to copy to + * @param [in] other Pointer to the SimpleArray instance to copy from + */ +void simple_array_copy(SimpleArray* instance, const SimpleArray* other); + +/** + * Check if another SimpleArray instance is equal (the same object or holds the + * same data) to this one. + * + * @param [in] instance Pointer to the SimpleArray instance to be compared + * @param [in] other Pointer to the SimpleArray instance to be compared + * @return True if instances are considered equal, false otherwise + */ +bool simple_array_is_equal(const SimpleArray* instance, const SimpleArray* other); + +/** + * Get the count of elements currently contained in a SimpleArray instance. + * + * @param [in] instance Pointer to the SimpleArray instance to query the count from + * @return Count of elements contained in the instance + */ +uint32_t simple_array_get_count(const SimpleArray* instance); + +/** + * Get a pointer to an element contained in a SimpleArray instance. + * + * @param [in] instance Pointer to the SimpleArray instance to get an element from + * @param [in] index Index of the element in question. MUST be less than total element count + * @return Pointer to the element specified by index + */ +SimpleArrayElement* simple_array_get(SimpleArray* instance, uint32_t index); + +/** + * Get a const pointer to an element contained in a SimpleArray instance. + * + * @param [in] instance Pointer to the SimpleArray instance to get an element from + * @param [in] index Index of the element in question. MUST be less than total element count + * @return Const pointer to the element specified by index + */ +const SimpleArrayElement* simple_array_cget(const SimpleArray* instance, uint32_t index); + +/** + * Get a pointer to the internal data of a SimpleArray instance. + * + * @param [in] instance Pointer to the SimpleArray instance to get the data of + * @return Pointer to the instance's internal data + */ +SimpleArrayData* simple_array_get_data(SimpleArray* instance); + +/** + * Get a constant pointer to the internal data of a SimpleArray instance. + * + * @param [in] instance Pointer to the SimpleArray instance to get the data of + * @return Constant pointer to the instance's internal data + */ +const SimpleArrayData* simple_array_cget_data(const SimpleArray* instance); + +// Standard preset configurations + +// Preset configuration for a byte(uint8_t) array. +extern const SimpleArrayConfig simple_array_config_uint8_t; + +#ifdef __cplusplus +} +#endif diff --git a/scripts/ReadMe.md b/scripts/ReadMe.md index a9feba11b..359ce472a 100644 --- a/scripts/ReadMe.md +++ b/scripts/ReadMe.md @@ -52,10 +52,10 @@ ob.py set # Assets delivery -Run in the root folder of the repo: +Build the firmware and run in the root folder of the repo: ```bash -python scripts/storage.py -p send assets/resources /ext +python scripts/storage.py -p send build/latest/resources /ext ``` diff --git a/scripts/assets.py b/scripts/assets.py index bd8b38ae6..1099f0c33 100755 --- a/scripts/assets.py +++ b/scripts/assets.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 import os +import shutil from flipper.app import App from flipper.assets.icon import file2image @@ -220,6 +221,7 @@ class Main(App): if not os.path.isdir(directory_path): self.logger.error(f'"{directory_path}" is not a directory') exit(255) + manifest_file = os.path.join(directory_path, "Manifest") old_manifest = Manifest() if os.path.exists(manifest_file): @@ -234,13 +236,15 @@ class Main(App): self.logger.info("Comparing new manifest with existing") only_in_old, changed, only_in_new = Manifest.compare(old_manifest, new_manifest) for record in only_in_old: - self.logger.info(f"Only in old: {record}") + self.logger.debug(f"Only in old: {record}") for record in changed: self.logger.info(f"Changed: {record}") for record in only_in_new: - self.logger.info(f"Only in new: {record}") + self.logger.debug(f"Only in new: {record}") if any((only_in_old, changed, only_in_new)): - self.logger.warning("Manifests are different, updating") + self.logger.info( + f"Manifest updated ({len(only_in_new)} new, {len(only_in_old)} removed, {len(changed)} changed)" + ) new_manifest.save(manifest_file) else: self.logger.info("Manifest is up-to-date!") diff --git a/scripts/fbt/appmanifest.py b/scripts/fbt/appmanifest.py index 1a6cae9b1..bef4eb02b 100644 --- a/scripts/fbt/appmanifest.py +++ b/scripts/fbt/appmanifest.py @@ -64,6 +64,7 @@ class FlipperApplication: order: int = 0 sdk_headers: List[str] = field(default_factory=list) targets: List[str] = field(default_factory=lambda: ["all"]) + resources: Optional[str] = None # .fap-specific sources: List[str] = field(default_factory=lambda: ["*.c*"]) @@ -239,12 +240,12 @@ class AppBuildset: FlipperAppType.SETTINGS, FlipperAppType.STARTUP, ) - EXTERNAL_APP_TYPES = ( - FlipperAppType.EXTERNAL, - FlipperAppType.MENUEXTERNAL, - FlipperAppType.PLUGIN, - FlipperAppType.DEBUG, - ) + EXTERNAL_APP_TYPES_MAP = { + FlipperAppType.EXTERNAL: True, + FlipperAppType.PLUGIN: True, + FlipperAppType.DEBUG: True, + FlipperAppType.MENUEXTERNAL: False, + } @staticmethod def print_writer(message): @@ -272,11 +273,15 @@ class AppBuildset: self._check_unsatisfied() # unneeded? self._check_target_match() self._group_plugins() - self.apps = sorted( + self._apps = sorted( list(map(self.appmgr.get, self.appnames)), key=lambda app: app.appid, ) + @property + def apps(self): + return list(self._apps) + def _is_missing_dep(self, dep_name: str): return dep_name not in self.appnames @@ -313,8 +318,8 @@ class AppBuildset: def _process_ext_apps(self): extapps = [ app - for apptype in self.EXTERNAL_APP_TYPES - for app in self.get_apps_of_type(apptype, True) + for (apptype, global_lookup) in self.EXTERNAL_APP_TYPES_MAP.items() + for app in self.get_apps_of_type(apptype, global_lookup) ] extapps.extend(map(self.appmgr.get, self._extra_ext_appnames)) @@ -385,13 +390,13 @@ class AppBuildset: def get_apps_cdefs(self): cdefs = set() - for app in self.apps: + for app in self._apps: cdefs.update(app.cdefines) return sorted(list(cdefs)) def get_sdk_headers(self): sdk_headers = [] - for app in self.apps: + for app in self._apps: sdk_headers.extend( [ src._appdir.File(header) @@ -402,17 +407,21 @@ class AppBuildset: return sdk_headers def get_apps_of_type(self, apptype: FlipperAppType, all_known: bool = False): + """Looks up apps of given type in current app set. If all_known is true, + ignores app set and checks all loaded apps' manifests.""" return sorted( filter( lambda app: app.apptype == apptype, - self.appmgr.known_apps.values() if all_known else self.apps, + self.appmgr.known_apps.values() + if all_known + else map(self.appmgr.get, self.appnames), ), key=lambda app: app.order, ) def get_builtin_apps(self): return list( - filter(lambda app: app.apptype in self.BUILTIN_APP_TYPES, self.apps) + filter(lambda app: app.apptype in self.BUILTIN_APP_TYPES, self._apps) ) def get_builtin_app_folders(self): diff --git a/scripts/fbt_tools/fbt_apps.py b/scripts/fbt_tools/fbt_apps.py index 9a0718055..edce194f0 100644 --- a/scripts/fbt_tools/fbt_apps.py +++ b/scripts/fbt_tools/fbt_apps.py @@ -21,8 +21,13 @@ def LoadAppManifest(env, entry): APP_MANIFEST_NAME = "application.fam" manifest_glob = entry.glob(APP_MANIFEST_NAME) if len(manifest_glob) == 0: + try: + disk_node = next(filter(lambda d: d.exists(), entry.get_all_rdirs())) + except Exception: + disk_node = entry + raise FlipperManifestException( - f"Folder {entry}: manifest {APP_MANIFEST_NAME} is missing" + f"App folder '{disk_node.abspath}': missing manifest ({APP_MANIFEST_NAME})" ) app_manifest_file_path = manifest_glob[0].rfile().abspath diff --git a/scripts/fbt_tools/fbt_assets.py b/scripts/fbt_tools/fbt_assets.py index d923c328f..492a66b66 100644 --- a/scripts/fbt_tools/fbt_assets.py +++ b/scripts/fbt_tools/fbt_assets.py @@ -5,9 +5,10 @@ from ansi.color import fg from SCons.Action import Action from SCons.Builder import Builder from SCons.Errors import StopError +from SCons.Node.FS import File -def icons_emitter(target, source, env): +def _icons_emitter(target, source, env): icons_src = env.GlobRecursive("*.png", env["ICON_SRC_DIR"]) icons_src += env.GlobRecursive("**/frame_rate", env["ICON_SRC_DIR"]) @@ -18,7 +19,7 @@ def icons_emitter(target, source, env): return target, icons_src -def proto_emitter(target, source, env): +def _proto_emitter(target, source, env): target = [] for src in source: basename = os.path.splitext(src.name)[0] @@ -27,25 +28,26 @@ def proto_emitter(target, source, env): return target, source -def dolphin_emitter(target, source, env): +def _dolphin_emitter(target, source, env): res_root_dir = source[0].Dir(env["DOLPHIN_RES_TYPE"]) - source = [res_root_dir] + source = list() source.extend(env.GlobRecursive("*.*", res_root_dir.srcnode())) target_base_dir = target[0] env.Replace(_DOLPHIN_OUT_DIR=target[0]) + env.Replace(_DOLPHIN_SRC_DIR=res_root_dir) if env["DOLPHIN_RES_TYPE"] == "external": target = [target_base_dir.File("manifest.txt")] ## A detailed list of files to be generated - ## works better if we just leave target the folder - # target = [] + # Not used ATM, becasuse it inflates the internal dependency graph too much + # Preserve original paths, do .png -> .bm conversion # target.extend( # map( # lambda node: target_base_dir.File( # res_root_dir.rel_path(node).replace(".png", ".bm") # ), - # filter(lambda node: isinstance(node, SCons.Node.FS.File), source), + # filter(lambda node: isinstance(node, File), source), # ) # ) else: @@ -55,7 +57,7 @@ def dolphin_emitter(target, source, env): target_base_dir.File(asset_basename + ".h"), ] - # Debug output + ## Debug output # print( # f"Dolphin res type: {env['DOLPHIN_RES_TYPE']},\ntarget files:", # list(f.path for f in target), @@ -65,7 +67,7 @@ def dolphin_emitter(target, source, env): return target, source -def _invoke_git(args, source_dir): +def __invoke_git(args, source_dir): cmd = ["git"] cmd.extend(args) return ( @@ -75,25 +77,38 @@ def _invoke_git(args, source_dir): ) -def proto_ver_generator(target, source, env): +def _proto_ver_generator(target, source, env): target_file = target[0] src_dir = source[0].dir.abspath - try: - _invoke_git( - ["fetch", "--tags"], - source_dir=src_dir, - ) - except (subprocess.CalledProcessError, EnvironmentError): - # Not great, not terrible - print(fg.boldred("Git: fetch failed")) - try: - git_describe = _invoke_git( - ["describe", "--tags", "--abbrev=0"], - source_dir=src_dir, - ) - except (subprocess.CalledProcessError, EnvironmentError): - raise StopError("Git: describe failed") + def fetch(unshallow=False): + git_args = ["fetch", "--tags"] + if unshallow: + git_args.append("--unshallow") + + try: + __invoke_git(git_args, source_dir=src_dir) + except (subprocess.CalledProcessError, EnvironmentError): + # Not great, not terrible + print(fg.boldred("Git: fetch failed")) + + def describe(): + try: + return __invoke_git( + ["describe", "--tags", "--abbrev=0"], + source_dir=src_dir, + ) + except (subprocess.CalledProcessError, EnvironmentError): + return None + + fetch() + git_describe = describe() + if not git_describe: + fetch(unshallow=True) + git_describe = describe() + + if not git_describe: + raise StopError("Failed to process git tags for protobuf versioning") git_major, git_minor = git_describe.split(".") version_file_data = ( @@ -127,7 +142,6 @@ def generate(env): ICONSCOMSTR="\tICONS\t${TARGET}", PROTOCOMSTR="\tPROTO\t${SOURCE}", DOLPHINCOMSTR="\tDOLPHIN\t${DOLPHIN_RES_TYPE}", - RESMANIFESTCOMSTR="\tMANIFEST\t${TARGET}", PBVERCOMSTR="\tPBVER\t${TARGET}", ) @@ -135,37 +149,74 @@ def generate(env): BUILDERS={ "IconBuilder": Builder( action=Action( - '${PYTHON3} ${ASSETS_COMPILER} icons ${ICON_SRC_DIR} ${TARGET.dir} --filename "${ICON_FILE_NAME}"', + [ + [ + "${PYTHON3}", + "${ASSETS_COMPILER}", + "icons", + "${ICON_SRC_DIR}", + "${TARGET.dir}", + "--filename", + "${ICON_FILE_NAME}", + ], + ], "${ICONSCOMSTR}", ), - emitter=icons_emitter, + emitter=_icons_emitter, ), "ProtoBuilder": Builder( action=Action( - "${PYTHON3} ${NANOPB_COMPILER} -q -I${SOURCE.dir.posix} -D${TARGET.dir.posix} ${SOURCES.posix}", + [ + [ + "${PYTHON3}", + "${NANOPB_COMPILER}", + "-q", + "-I${SOURCE.dir.posix}", + "-D${TARGET.dir.posix}", + "${SOURCES.posix}", + ], + ], "${PROTOCOMSTR}", ), - emitter=proto_emitter, + emitter=_proto_emitter, suffix=".pb.c", src_suffix=".proto", ), "DolphinSymBuilder": Builder( action=Action( - "${PYTHON3} ${ASSETS_COMPILER} dolphin -s dolphin_${DOLPHIN_RES_TYPE} ${SOURCE} ${_DOLPHIN_OUT_DIR}", + [ + [ + "${PYTHON3}", + "${ASSETS_COMPILER}", + "dolphin", + "-s", + "dolphin_${DOLPHIN_RES_TYPE}", + "${_DOLPHIN_SRC_DIR}", + "${_DOLPHIN_OUT_DIR}", + ], + ], "${DOLPHINCOMSTR}", ), - emitter=dolphin_emitter, + emitter=_dolphin_emitter, ), "DolphinExtBuilder": Builder( action=Action( - "${PYTHON3} ${ASSETS_COMPILER} dolphin ${SOURCE} ${_DOLPHIN_OUT_DIR}", + [ + [ + "${PYTHON3}", + "${ASSETS_COMPILER}", + "dolphin", + "${_DOLPHIN_SRC_DIR}", + "${_DOLPHIN_OUT_DIR}", + ], + ], "${DOLPHINCOMSTR}", ), - emitter=dolphin_emitter, + emitter=_dolphin_emitter, ), "ProtoVerBuilder": Builder( action=Action( - proto_ver_generator, + _proto_ver_generator, "${PBVERCOMSTR}", ), ), diff --git a/scripts/fbt_tools/fbt_dist.py b/scripts/fbt_tools/fbt_dist.py index 3645008c5..160f5fa03 100644 --- a/scripts/fbt_tools/fbt_dist.py +++ b/scripts/fbt_tools/fbt_dist.py @@ -96,7 +96,21 @@ def DistCommand(env, name, source, **kw): command = env.Command( target, source, - '@${PYTHON3} "${DIST_SCRIPT}" copy -p ${DIST_PROJECTS} -s "${DIST_SUFFIX}" ${DIST_EXTRA}', + action=Action( + [ + [ + "${PYTHON3}", + "${DIST_SCRIPT}", + "copy", + "-p", + "${DIST_PROJECTS}", + "-s", + "${DIST_SUFFIX}", + "${DIST_EXTRA}", + ] + ], + "${DISTCOMSTR}", + ), **kw, ) env.Pseudo(target) @@ -106,7 +120,10 @@ def DistCommand(env, name, source, **kw): def generate(env): if not env["VERBOSE"]: - env.SetDefault(COPROCOMSTR="\tCOPRO\t${TARGET}") + env.SetDefault( + COPROCOMSTR="\tCOPRO\t${TARGET}", + DISTCOMSTR="\tDIST\t${TARGET}", + ) env.AddMethod(AddFwProject) env.AddMethod(DistCommand) env.AddMethod(AddFwFlashTarget) diff --git a/scripts/fbt_tools/fbt_extapps.py b/scripts/fbt_tools/fbt_extapps.py index 963429f24..b88fa7929 100644 --- a/scripts/fbt_tools/fbt_extapps.py +++ b/scripts/fbt_tools/fbt_extapps.py @@ -1,7 +1,5 @@ import itertools -import os import pathlib -import shutil from dataclasses import dataclass, field from typing import Dict, List, Optional @@ -149,16 +147,10 @@ class AppBuilder: CPPPATH=[self.app_work_dir, self.app._appdir], ) - app_sources = list( - itertools.chain.from_iterable( - self.app_env.GlobRecursive( - source_type, - self.app_work_dir, - exclude="lib", - ) - for source_type in self.app.sources - ) + app_sources = self.app_env.GatherSources( + [self.app.sources, "!lib"], self.app_work_dir ) + if not app_sources: raise UserError(f"No source files found for {self.app.appid}") @@ -290,7 +282,7 @@ def prepare_app_metadata(target, source, env): ) -def validate_app_imports(target, source, env): +def _validate_app_imports(target, source, env): sdk_cache = SdkCache(env["SDK_DEFINITION"].path, load_version_only=False) app_syms = set() with open(target[0].path, "rt") as f: @@ -342,35 +334,7 @@ def GetExtAppByIdOrPath(env, app_dir): return app_artifacts -def resources_fap_dist_emitter(target, source, env): - # Initially we have a single target - target dir - # Here we inject pairs of (target, source) for each file - resources_root = target[0] - - target = [] - for app_artifacts in env["EXT_APPS"].values(): - for _, dist_path in filter( - lambda dist_entry: dist_entry[0], app_artifacts.dist_entries - ): - source.append(app_artifacts.compact) - target.append(resources_root.File(dist_path)) - - assert len(target) == len(source) - return (target, source) - - -def resources_fap_dist_action(target, source, env): - # FIXME: find a proper way to remove stale files - target_dir = env.Dir("${RESOURCES_ROOT}/apps") - shutil.rmtree(target_dir.path, ignore_errors=True) - - # Iterate over pairs generated in emitter - for src, target in zip(source, target): - os.makedirs(os.path.dirname(target.path), exist_ok=True) - shutil.copy(src.path, target.path) - - -def embed_app_metadata_emitter(target, source, env): +def _embed_app_metadata_emitter(target, source, env): app = env["APP"] # Hack: change extension for fap libs @@ -407,33 +371,52 @@ def generate_embed_app_metadata_actions(source, target, env, for_signature): Action(prepare_app_metadata, "$APPMETA_COMSTR"), ] - objcopy_str = ( - "${OBJCOPY} " - "--remove-section .ARM.attributes " - "--add-section ${_FAP_META_SECTION}=${APP._section_fapmeta} " - ) + objcopy_args = [ + "${OBJCOPY}", + "--remove-section", + ".ARM.attributes", + "--add-section", + "${_FAP_META_SECTION}=${APP._section_fapmeta}", + "--set-section-flags", + "${_FAP_META_SECTION}=contents,noload,readonly,data", + ] if app._section_fapfileassets: actions.append(Action(prepare_app_file_assets, "$APPFILE_COMSTR")) - objcopy_str += ( - "--add-section ${_FAP_FILEASSETS_SECTION}=${APP._section_fapfileassets} " + objcopy_args.extend( + ( + "--add-section", + "${_FAP_FILEASSETS_SECTION}=${APP._section_fapfileassets}", + "--set-section-flags", + "${_FAP_FILEASSETS_SECTION}=contents,noload,readonly,data", + ) ) - objcopy_str += ( - "--set-section-flags ${_FAP_META_SECTION}=contents,noload,readonly,data " - "--strip-debug --strip-unneeded " - "--add-gnu-debuglink=${SOURCE} " - "${SOURCES} ${TARGET}" + objcopy_args.extend( + ( + "--strip-debug", + "--strip-unneeded", + "--add-gnu-debuglink=${SOURCE}", + "${SOURCES}", + "${TARGET}", + ) ) actions.extend( ( Action( - objcopy_str, + [objcopy_args], "$APPMETAEMBED_COMSTR", ), Action( - "${PYTHON3} ${FBT_SCRIPT_DIR}/fastfap.py ${TARGET} ${OBJCOPY}", + [ + [ + "${PYTHON3}", + "${FBT_SCRIPT_DIR}/fastfap.py", + "${TARGET}", + "${OBJCOPY}", + ] + ], "$FASTFAP_COMSTR", ), ) @@ -511,7 +494,6 @@ def generate(env, **kw): ) if not env["VERBOSE"]: env.SetDefault( - FAPDISTCOMSTR="\tFAPDIST\t${TARGET}", APPMETA_COMSTR="\tAPPMETA\t${TARGET}", APPFILE_COMSTR="\tAPPFILE\t${TARGET}", APPMETAEMBED_COMSTR="\tFAP\t${TARGET}", @@ -534,18 +516,11 @@ def generate(env, **kw): env.Append( BUILDERS={ - "FapDist": Builder( - action=Action( - resources_fap_dist_action, - "$FAPDISTCOMSTR", - ), - emitter=resources_fap_dist_emitter, - ), "EmbedAppMetadata": Builder( generator=generate_embed_app_metadata_actions, suffix=".fap", src_suffix=".elf", - emitter=embed_app_metadata_emitter, + emitter=_embed_app_metadata_emitter, ), "ValidateAppImports": Builder( action=[ @@ -554,7 +529,7 @@ def generate(env, **kw): None, # "$APPDUMP_COMSTR", ), Action( - validate_app_imports, + _validate_app_imports, "$APPCHECK_COMSTR", ), ], diff --git a/scripts/fbt_tools/fbt_hwtarget.py b/scripts/fbt_tools/fbt_hwtarget.py index e7f857b1e..8e55b7d96 100644 --- a/scripts/fbt_tools/fbt_hwtarget.py +++ b/scripts/fbt_tools/fbt_hwtarget.py @@ -2,9 +2,9 @@ import json class HardwareTargetLoader: - def __init__(self, env, target_scons_dir, target_id): + def __init__(self, env, root_target_scons_dir, target_id): self.env = env - self.target_scons_dir = target_scons_dir + self.all_targets_root_dir = root_target_scons_dir self.target_dir = self._getTargetDir(target_id) # self.target_id = target_id self.layered_target_dirs = [] @@ -23,7 +23,7 @@ class HardwareTargetLoader: self._processTargetDefinitions(target_id) def _getTargetDir(self, target_id): - return self.target_scons_dir.Dir(f"f{target_id}") + return self.all_targets_root_dir.Dir(f"f{target_id}") def _loadDescription(self, target_id): target_json_file = self._getTargetDir(target_id).File("target.json") @@ -34,14 +34,14 @@ class HardwareTargetLoader: return vals def _processTargetDefinitions(self, target_id): - self.layered_target_dirs.append(f"targets/f{target_id}") + target_dir = self._getTargetDir(target_id) + self.layered_target_dirs.append(target_dir) config = self._loadDescription(target_id) for path_list in ("include_paths", "sdk_header_paths"): getattr(self, path_list).extend( - f"#/firmware/targets/f{target_id}/{p}" - for p in config.get(path_list, []) + target_dir.Dir(p) for p in config.get(path_list, []) ) self.excluded_sources.extend(config.get("excluded_sources", [])) @@ -50,7 +50,7 @@ class HardwareTargetLoader: file_attrs = ( # (name, use_src_node) - ("startup_script", False), + ("startup_script", True), ("linker_script_flash", True), ("linker_script_ram", True), ("linker_script_app", True), @@ -59,9 +59,10 @@ class HardwareTargetLoader: for attr_name, use_src_node in file_attrs: if (val := config.get(attr_name)) and not getattr(self, attr_name): - node = self.env.File(f"firmware/targets/f{target_id}/{val}") + node = target_dir.File(val) if use_src_node: node = node.srcnode() + # print(f"Got node {node}, {node.path} for {attr_name}") setattr(self, attr_name, node) for attr_name in ("linker_dependencies",): @@ -84,8 +85,8 @@ class HardwareTargetLoader: ) seen_filenames.update(f.name for f in accepted_sources) sources.extend(accepted_sources) - # print(f"Found {len(sources)} sources: {list(f.name for f in sources)}") - return sources + # print(f"Found {len(sources)} sources: {list(f.path for f in sources)}") + return list(f.get_path(self.all_targets_root_dir) for f in sources) def gatherSdkHeaders(self): sdk_headers = [] @@ -101,7 +102,7 @@ class HardwareTargetLoader: def ConfigureForTarget(env, target_id): - target_loader = HardwareTargetLoader(env, env.Dir("#/firmware/targets"), target_id) + target_loader = HardwareTargetLoader(env, env["TARGETS_ROOT"], target_id) env.Replace( TARGET_CFG=target_loader, SDK_DEFINITION=target_loader.sdk_symbols, diff --git a/scripts/fbt_tools/fbt_resources.py b/scripts/fbt_tools/fbt_resources.py new file mode 100644 index 000000000..4c3146ba4 --- /dev/null +++ b/scripts/fbt_tools/fbt_resources.py @@ -0,0 +1,117 @@ +import os +import shutil + +from SCons.Action import Action +from SCons.Builder import Builder +from SCons.Errors import StopError +from SCons.Node.FS import Dir, File + + +def __generate_resources_dist_entries(env): + src_target_entries = [] + + resources_root = env.Dir(env["RESOURCES_ROOT"]) + + for app_artifacts in env["FW_EXTAPPS"].application_map.values(): + for _, dist_path in filter( + lambda dist_entry: dist_entry[0], app_artifacts.dist_entries + ): + src_target_entries.append( + ( + app_artifacts.compact, + resources_root.File(dist_path), + ) + ) + + # Deploy apps' resources too + for app in env["APPBUILD"].apps: + if not app.resources: + continue + apps_resource_dir = app._appdir.Dir(app.resources) + for res_file in env.GlobRecursive("*", apps_resource_dir): + if not isinstance(res_file, File): + continue + src_target_entries.append( + ( + res_file, + resources_root.File( + res_file.get_path(apps_resource_dir), + ), + ) + ) + + # Deploy other stuff from _EXTRA_DIST + for extra_dist in env["_EXTRA_DIST"]: + if isinstance(extra_dist, Dir): + src_target_entries.append( + ( + extra_dist, + resources_root.Dir(extra_dist.name), + ) + ) + else: + raise StopError(f"Unsupported extra dist type: {type(extra_dist)}") + + return src_target_entries + + +def _resources_dist_emitter(target, source, env): + src_target_entries = __generate_resources_dist_entries(env) + source = list(map(lambda entry: entry[0], src_target_entries)) + return (target, source) + + +def _resources_dist_action(target, source, env): + dist_entries = __generate_resources_dist_entries(env) + assert len(dist_entries) == len(source) + shutil.rmtree(env.Dir(env["RESOURCES_ROOT"]).abspath, ignore_errors=True) + for src, target in dist_entries: + if isinstance(src, File): + os.makedirs(os.path.dirname(target.path), exist_ok=True) + shutil.copy(src.path, target.path) + elif isinstance(src, Dir): + shutil.copytree(src.path, target.path) + else: + raise StopError(f"Unsupported dist entry type: {type(src)}") + + +def generate(env, **kw): + env.SetDefault( + ASSETS_COMPILER="${FBT_SCRIPT_DIR}/assets.py", + ) + + if not env["VERBOSE"]: + env.SetDefault( + RESOURCEDISTCOMSTR="\tRESDIST\t${RESOURCES_ROOT}", + RESMANIFESTCOMSTR="\tMANIFST\t${TARGET}", + ) + + env.Append( + BUILDERS={ + "ManifestBuilder": Builder( + action=[ + Action( + _resources_dist_action, + "${RESOURCEDISTCOMSTR}", + ), + Action( + [ + [ + "${PYTHON3}", + "${ASSETS_COMPILER}", + "manifest", + "${TARGET.dir.posix}", + "--timestamp=${GIT_UNIX_TIMESTAMP}", + ] + ], + "${RESMANIFESTCOMSTR}", + ), + ], + emitter=_resources_dist_emitter, + ), + } + ) + + +def exists(env): + return True diff --git a/scripts/fbt_tools/fbt_sdk.py b/scripts/fbt_tools/fbt_sdk.py index 2f7d62388..6350f14b8 100644 --- a/scripts/fbt_tools/fbt_sdk.py +++ b/scripts/fbt_tools/fbt_sdk.py @@ -37,13 +37,13 @@ def ProcessSdkDepends(env, filename): return depends -def api_amalgam_emitter(target, source, env): +def _api_amalgam_emitter(target, source, env): target.append(env.ChangeFileExtension(target[0], ".d")) target.append(env.ChangeFileExtension(target[0], ".i.c")) return target, source -def api_amalgam_gen_origin_header(target, source, env): +def _api_amalgam_gen_origin_header(target, source, env): mega_file = env.subst("${TARGET}.c", target=target[0]) with open(mega_file, "wt") as sdk_c: sdk_c.write( @@ -183,12 +183,12 @@ class SdkTreeBuilder: self._generate_sdk_meta() -def deploy_sdk_header_tree_action(target, source, env): +def _deploy_sdk_header_tree_action(target, source, env): sdk_tree = SdkTreeBuilder(env, target, source) return sdk_tree.deploy_action() -def deploy_sdk_header_tree_emitter(target, source, env): +def _deploy_sdk_header_tree_emitter(target, source, env): sdk_tree = SdkTreeBuilder(env, target, source) return sdk_tree.emitter(target, source, env) @@ -227,7 +227,7 @@ def _check_sdk_is_up2date(sdk_cache: SdkCache): ) -def validate_api_cache(source, target, env): +def _validate_api_cache(source, target, env): # print(f"Generating SDK for {source[0]} to {target[0]}") current_sdk = SdkCollector() current_sdk.process_source_file_for_sdk(source[0].path) @@ -240,7 +240,7 @@ def validate_api_cache(source, target, env): _check_sdk_is_up2date(sdk_cache) -def generate_api_table(source, target, env): +def _generate_api_table(source, target, env): sdk_cache = SdkCache(source[0].path) _check_sdk_is_up2date(sdk_cache) @@ -278,10 +278,10 @@ def generate(env, **kw): env.Append( BUILDERS={ "ApiAmalgamator": Builder( - emitter=api_amalgam_emitter, + emitter=_api_amalgam_emitter, action=[ Action( - api_amalgam_gen_origin_header, + _api_amalgam_gen_origin_header, "$SDK_AMALGAMATE_HEADER_COMSTR", ), Action( @@ -293,15 +293,15 @@ def generate(env, **kw): ), "SDKHeaderTreeExtractor": Builder( action=Action( - deploy_sdk_header_tree_action, + _deploy_sdk_header_tree_action, "$SDKTREE_COMSTR", ), - emitter=deploy_sdk_header_tree_emitter, + emitter=_deploy_sdk_header_tree_emitter, src_suffix=".d", ), "ApiTableValidator": Builder( action=Action( - validate_api_cache, + _validate_api_cache, "$SDKSYM_UPDATER_COMSTR", ), suffix=".csv", @@ -309,7 +309,7 @@ def generate(env, **kw): ), "ApiSymbolTable": Builder( action=Action( - generate_api_table, + _generate_api_table, "$APITABLE_GENERATOR_COMSTR", ), suffix=".h", diff --git a/scripts/fbt_tools/fbt_version.py b/scripts/fbt_tools/fbt_version.py index aead13b29..f1a782523 100644 --- a/scripts/fbt_tools/fbt_version.py +++ b/scripts/fbt_tools/fbt_version.py @@ -2,7 +2,7 @@ from SCons.Action import Action from SCons.Builder import Builder -def version_emitter(target, source, env): +def _version_emitter(target, source, env): target_dir = target[0] target = [ target_dir.File("version.inc.h"), @@ -24,7 +24,7 @@ def generate(env): '-o ${TARGET.dir.posix} --dir "${ROOT_DIR}"', "${VERSIONCOMSTR}", ), - emitter=version_emitter, + emitter=_version_emitter, ), } ) diff --git a/scripts/fbt_tools/pvsstudio.py b/scripts/fbt_tools/pvsstudio.py index 211f46aee..f43db126e 100644 --- a/scripts/fbt_tools/pvsstudio.py +++ b/scripts/fbt_tools/pvsstudio.py @@ -17,7 +17,7 @@ def _set_browser_action(target, source, env): __no_browser = True -def emit_pvsreport(target, source, env): +def _emit_pvsreport(target, source, env): target_dir = env["REPORT_DIR"] if env["PLATFORM"] == "win32": # Report generator on Windows emits to a subfolder of given output folder @@ -96,7 +96,7 @@ def generate(env): ], "${PVSCONVCOMSTR}", ), - emitter=emit_pvsreport, + emitter=_emit_pvsreport, src_suffix=".log", ), } diff --git a/scripts/fbt_tools/sconsrecursiveglob.py b/scripts/fbt_tools/sconsrecursiveglob.py index e7eb8fb72..de64c76b7 100644 --- a/scripts/fbt_tools/sconsrecursiveglob.py +++ b/scripts/fbt_tools/sconsrecursiveglob.py @@ -1,7 +1,9 @@ +import itertools + import SCons from fbt.util import GLOB_FILE_EXCLUSION -from SCons.Script import Flatten from SCons.Node.FS import has_glob_magic +from SCons.Script import Flatten def GlobRecursive(env, pattern, node=".", exclude=[]): @@ -23,12 +25,35 @@ def GlobRecursive(env, pattern, node=".", exclude=[]): # Otherwise, just assume that file at path exists else: results.append(node.File(pattern)) + ## Debug # print(f"Glob result for {pattern} from {node}: {results}") return results +def GatherSources(env, sources_list, node="."): + sources_list = list(set(Flatten(sources_list))) + include_sources = list(filter(lambda x: not x.startswith("!"), sources_list)) + exclude_sources = list(x[1:] for x in sources_list if x.startswith("!")) + gathered_sources = list( + itertools.chain.from_iterable( + env.GlobRecursive( + source_type, + node, + exclude=exclude_sources, + ) + for source_type in include_sources + ) + ) + ## Debug + # print( + # f"Gathered sources for {sources_list} from {node}: {list(f.path for f in gathered_sources)}" + # ) + return gathered_sources + + def generate(env): env.AddMethod(GlobRecursive) + env.AddMethod(GatherSources) def exists(env): diff --git a/scripts/flipper/assets/dolphin.py b/scripts/flipper/assets/dolphin.py index e9089a1b9..cf98c8253 100644 --- a/scripts/flipper/assets/dolphin.py +++ b/scripts/flipper/assets/dolphin.py @@ -55,7 +55,7 @@ class DolphinBubbleAnimation: if not os.path.isfile(meta_filename): raise Exception(f"Animation meta file doesn't exist: { meta_filename }") - self.logger.info(f"Loading meta from {meta_filename}") + self.logger.debug(f"Loading meta from {meta_filename}") file = FlipperFormatFile() file.load(meta_filename) diff --git a/scripts/meta.py b/scripts/meta.py deleted file mode 100755 index f47ef65fb..000000000 --- a/scripts/meta.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python3 - -import json - -from flipper.app import App - - -class Main(App): - def init(self): - self.subparsers = self.parser.add_subparsers(help="sub-command help") - - # generate - self.parser_generate = self.subparsers.add_parser( - "generate", help="Generate JSON meta file" - ) - self.parser_generate.add_argument("-p", dest="project", required=True) - self.parser_generate.add_argument( - "-DBUILD_DATE", dest="build_date", required=True - ) - self.parser_generate.add_argument("-DGIT_COMMIT", dest="commit", required=True) - self.parser_generate.add_argument("-DGIT_BRANCH", dest="branch", required=True) - self.parser_generate.add_argument( - "-DTARGET", dest="target", type=int, required=True - ) - self.parser_generate.set_defaults(func=self.generate) - - # merge - self.parser_merge = self.subparsers.add_parser( - "merge", help="Merge JSON meta files" - ) - self.parser_merge.add_argument( - "-i", dest="input", action="append", nargs="+", required=True - ) - self.parser_merge.set_defaults(func=self.merge) - - def generate(self): - meta = {} - for k, v in vars(self.args).items(): - if k in ["project", "func", "debug"]: - continue - if isinstance(v, str): - v = v.strip('"') - meta[self.args.project + "_" + k] = v - - print(json.dumps(meta, indent=4)) - return 0 - - def merge(self): - full = {} - for path in self.args.input[0]: - with open(path, mode="r") as file: - dict = json.loads(file.read()) - full.update(dict) - - print(json.dumps(full, indent=4)) - return 0 - - -if __name__ == "__main__": - Main()() diff --git a/scripts/ufbt/project_template/app_template/.github/workflows/build.yml b/scripts/ufbt/project_template/app_template/.github/workflows/build.yml index c11ffc180..143847c4a 100644 --- a/scripts/ufbt/project_template/app_template/.github/workflows/build.yml +++ b/scripts/ufbt/project_template/app_template/.github/workflows/build.yml @@ -27,9 +27,9 @@ jobs: name: 'ufbt: Build for ${{ matrix.name }}' steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Build with ufbt - uses: flipperdevices/flipperzero-ufbt-action@v0.1.1 + uses: flipperdevices/flipperzero-ufbt-action@v0.1 id: build-app with: sdk-channel: ${{ matrix.sdk-channel }} diff --git a/scripts/version.py b/scripts/version.py index be1c51ce7..a37592137 100755 --- a/scripts/version.py +++ b/scripts/version.py @@ -53,7 +53,7 @@ class GitVersion: ) else: commit_date = datetime.strptime( - self._exec_git("log -1 --format=%cd").strip(), + self._exec_git("log -1 --format=%cd --date=default").strip(), "%a %b %d %H:%M:%S %Y %z", ) diff --git a/site_scons/extapps.scons b/site_scons/extapps.scons index f9227ed37..769b3eb15 100644 --- a/site_scons/extapps.scons +++ b/site_scons/extapps.scons @@ -14,7 +14,6 @@ appenv = ENV["APPENV"] = ENV.Clone( "fbt_assets", "fbt_sdk", ], - RESOURCES_ROOT=ENV.Dir("#/assets/resources"), ) appenv.Replace( @@ -56,7 +55,6 @@ appenv.AppendUnique( @dataclass class FlipperExtAppBuildArtifacts: application_map: dict = field(default_factory=dict) - resources_dist: NodeList = field(default_factory=NodeList) sdk_tree: NodeList = field(default_factory=NodeList) @@ -78,8 +76,6 @@ Alias( list(app_artifact.validator for app_artifact in extapps.application_map.values()), ) -extapps.resources_dist = appenv.FapDist(appenv["RESOURCES_ROOT"], []) - if appsrc := appenv.subst("$APPSRC"): launch_target = appenv.AddAppLaunchTarget(appsrc, "launch") diff --git a/firmware/ReadMe.md b/targets/ReadMe.md similarity index 100% rename from firmware/ReadMe.md rename to targets/ReadMe.md diff --git a/firmware/SConscript b/targets/SConscript similarity index 100% rename from firmware/SConscript rename to targets/SConscript diff --git a/firmware/targets/f18/api_symbols.csv b/targets/f18/api_symbols.csv similarity index 93% rename from firmware/targets/f18/api_symbols.csv rename to targets/f18/api_symbols.csv index 612ef28fd..0eadd799d 100644 --- a/firmware/targets/f18/api_symbols.csv +++ b/targets/f18/api_symbols.csv @@ -1,5 +1,5 @@ entry,status,name,type,params -Version,+,39.2,, +Version,+,44.0,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, Header,+,applications/services/cli/cli_vcp.h,, @@ -36,51 +36,7 @@ Header,+,applications/services/notification/notification_messages.h,, Header,+,applications/services/power/power_service/power.h,, Header,+,applications/services/rpc/rpc_app.h,, Header,+,applications/services/storage/storage.h,, -Header,+,firmware/targets/f18/furi_hal/furi_hal_resources.h,, -Header,+,firmware/targets/f18/furi_hal/furi_hal_spi_config.h,, -Header,+,firmware/targets/f18/furi_hal/furi_hal_target_hw.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_bus.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_clock.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_console.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_dma.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_flash.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_gpio.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_i2c_config.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_i2c_types.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_idle_timer.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_interrupt.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_os.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_pwm.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_spi_types.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_uart.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_usb_cdc.h,, -Header,+,firmware/targets/f7/platform_specific/intrinsic_export.h,, -Header,+,firmware/targets/f7/platform_specific/math_wrapper.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_bt.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_bt_hid.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_bt_serial.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_cortex.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_crypto.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_debug.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_i2c.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_info.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_light.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_memory.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_mpu.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_power.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_random.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_region.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_rtc.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_sd.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_speaker.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_spi.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_usb.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_usb_ccid.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_usb_hid.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_usb_hid_u2f.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_version.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_vibro.h,, +Header,+,lib/digital_signal/digital_sequence.h,, Header,+,lib/digital_signal/digital_signal.h,, Header,+,lib/drivers/cc1101_regs.h,, Header,+,lib/flipper_application/api_hashtable/api_hashtable.h,, @@ -132,11 +88,15 @@ Header,+,lib/mlib/m-rbtree.h,, Header,+,lib/mlib/m-tuple.h,, Header,+,lib/mlib/m-variant.h,, Header,+,lib/music_worker/music_worker.h,, +Header,+,lib/nanopb/pb.h,, +Header,+,lib/nanopb/pb_decode.h,, +Header,+,lib/nanopb/pb_encode.h,, Header,+,lib/one_wire/maxim_crc.h,, Header,+,lib/one_wire/one_wire_host.h,, Header,+,lib/one_wire/one_wire_slave.h,, Header,+,lib/print/wrappers.h,, Header,+,lib/pulse_reader/pulse_reader.h,, +Header,+,lib/signal_reader/signal_reader.h,, Header,+,lib/stm32wb_hal/Inc/stm32wbxx_ll_adc.h,, Header,+,lib/stm32wb_hal/Inc/stm32wbxx_ll_bus.h,, Header,+,lib/stm32wb_hal/Inc/stm32wbxx_ll_comp.h,, @@ -166,6 +126,7 @@ Header,+,lib/stm32wb_hal/Inc/stm32wbxx_ll_utils.h,, Header,+,lib/stm32wb_hal/Inc/stm32wbxx_ll_wwdg.h,, Header,+,lib/toolbox/api_lock.h,, Header,+,lib/toolbox/args.h,, +Header,+,lib/toolbox/bit_buffer.h,, Header,+,lib/toolbox/compress.h,, Header,+,lib/toolbox/crc32_calc.h,, Header,+,lib/toolbox/dir_walk.h,, @@ -180,6 +141,7 @@ Header,+,lib/toolbox/pretty_format.h,, Header,+,lib/toolbox/protocols/protocol_dict.h,, Header,+,lib/toolbox/saved_struct.h,, Header,+,lib/toolbox/sha256.h,, +Header,+,lib/toolbox/simple_array.h,, Header,+,lib/toolbox/stream/buffered_file_stream.h,, Header,+,lib/toolbox/stream/file_stream.h,, Header,+,lib/toolbox/stream/stream.h,, @@ -187,6 +149,51 @@ Header,+,lib/toolbox/stream/string_stream.h,, Header,+,lib/toolbox/tar/tar_archive.h,, Header,+,lib/toolbox/value_index.h,, Header,+,lib/toolbox/version.h,, +Header,+,targets/f18/furi_hal/furi_hal_resources.h,, +Header,+,targets/f18/furi_hal/furi_hal_spi_config.h,, +Header,+,targets/f18/furi_hal/furi_hal_target_hw.h,, +Header,+,targets/f7/furi_hal/furi_hal_bus.h,, +Header,+,targets/f7/furi_hal/furi_hal_clock.h,, +Header,+,targets/f7/furi_hal/furi_hal_console.h,, +Header,+,targets/f7/furi_hal/furi_hal_dma.h,, +Header,+,targets/f7/furi_hal/furi_hal_flash.h,, +Header,+,targets/f7/furi_hal/furi_hal_gpio.h,, +Header,+,targets/f7/furi_hal/furi_hal_i2c_config.h,, +Header,+,targets/f7/furi_hal/furi_hal_i2c_types.h,, +Header,+,targets/f7/furi_hal/furi_hal_idle_timer.h,, +Header,+,targets/f7/furi_hal/furi_hal_interrupt.h,, +Header,+,targets/f7/furi_hal/furi_hal_os.h,, +Header,+,targets/f7/furi_hal/furi_hal_pwm.h,, +Header,+,targets/f7/furi_hal/furi_hal_spi_types.h,, +Header,+,targets/f7/furi_hal/furi_hal_uart.h,, +Header,+,targets/f7/furi_hal/furi_hal_usb_cdc.h,, +Header,+,targets/f7/platform_specific/intrinsic_export.h,, +Header,+,targets/f7/platform_specific/math_wrapper.h,, +Header,+,targets/furi_hal_include/furi_hal.h,, +Header,+,targets/furi_hal_include/furi_hal_bt.h,, +Header,+,targets/furi_hal_include/furi_hal_bt_hid.h,, +Header,+,targets/furi_hal_include/furi_hal_bt_serial.h,, +Header,+,targets/furi_hal_include/furi_hal_cortex.h,, +Header,+,targets/furi_hal_include/furi_hal_crypto.h,, +Header,+,targets/furi_hal_include/furi_hal_debug.h,, +Header,+,targets/furi_hal_include/furi_hal_i2c.h,, +Header,+,targets/furi_hal_include/furi_hal_info.h,, +Header,+,targets/furi_hal_include/furi_hal_light.h,, +Header,+,targets/furi_hal_include/furi_hal_memory.h,, +Header,+,targets/furi_hal_include/furi_hal_mpu.h,, +Header,+,targets/furi_hal_include/furi_hal_power.h,, +Header,+,targets/furi_hal_include/furi_hal_random.h,, +Header,+,targets/furi_hal_include/furi_hal_region.h,, +Header,+,targets/furi_hal_include/furi_hal_rtc.h,, +Header,+,targets/furi_hal_include/furi_hal_sd.h,, +Header,+,targets/furi_hal_include/furi_hal_speaker.h,, +Header,+,targets/furi_hal_include/furi_hal_spi.h,, +Header,+,targets/furi_hal_include/furi_hal_usb.h,, +Header,+,targets/furi_hal_include/furi_hal_usb_ccid.h,, +Header,+,targets/furi_hal_include/furi_hal_usb_hid.h,, +Header,+,targets/furi_hal_include/furi_hal_usb_hid_u2f.h,, +Header,+,targets/furi_hal_include/furi_hal_version.h,, +Header,+,targets/furi_hal_include/furi_hal_vibro.h,, Function,-,LL_ADC_CommonDeInit,ErrorStatus,ADC_Common_TypeDef* Function,-,LL_ADC_CommonInit,ErrorStatus,"ADC_Common_TypeDef*, const LL_ADC_CommonInitTypeDef*" Function,-,LL_ADC_CommonStructInit,void,LL_ADC_CommonInitTypeDef* @@ -287,6 +294,7 @@ Function,-,LL_mDelay,void,uint32_t Function,-,SystemCoreClockUpdate,void, Function,-,SystemInit,void, Function,-,_Exit,void,int +Function,+,__aeabi_uldivmod,void*,"uint64_t, uint64_t" Function,-,__assert,void,"const char*, int, const char*" Function,+,__assert_func,void,"const char*, int, const char*, const char*" Function,+,__clear_cache,void,"void*, void*" @@ -294,10 +302,10 @@ Function,-,__eprintf,void,"const char*, const char*, unsigned int, const char*" Function,+,__errno,int*, Function,-,__fpclassifyd,int,double Function,-,__fpclassifyf,int,float -Function,+,__furi_crash,void, +Function,+,__furi_crash_implementation,void, Function,+,__furi_critical_enter,__FuriCriticalInfo, Function,+,__furi_critical_exit,void,__FuriCriticalInfo -Function,+,__furi_halt,void, +Function,+,__furi_halt_implementation,void, Function,-,__getdelim,ssize_t,"char**, size_t*, int, FILE*" Function,-,__getline,ssize_t,"char**, size_t*, FILE*" Function,-,__isinfd,int,double @@ -409,7 +417,6 @@ Function,-,_perror_r,void,"_reent*, const char*" Function,-,_printf_r,int,"_reent*, const char*, ..." Function,-,_putc_r,int,"_reent*, int, FILE*" Function,-,_putc_unlocked_r,int,"_reent*, int, FILE*" -Function,-,_putchar,void,char Function,-,_putchar_r,int,"_reent*, int" Function,-,_putchar_unlocked_r,int,"_reent*, int" Function,-,_putenv_r,int,"_reent*, char*" @@ -521,6 +528,36 @@ Function,-,atoll,long long,const char* Function,-,basename,char*,const char* Function,-,bcmp,int,"const void*, const void*, size_t" Function,-,bcopy,void,"const void*, void*, size_t" +Function,+,bit_buffer_alloc,BitBuffer*,size_t +Function,+,bit_buffer_append,void,"BitBuffer*, const BitBuffer*" +Function,+,bit_buffer_append_bit,void,"BitBuffer*, _Bool" +Function,+,bit_buffer_append_byte,void,"BitBuffer*, uint8_t" +Function,+,bit_buffer_append_bytes,void,"BitBuffer*, const uint8_t*, size_t" +Function,+,bit_buffer_append_right,void,"BitBuffer*, const BitBuffer*, size_t" +Function,+,bit_buffer_copy,void,"BitBuffer*, const BitBuffer*" +Function,+,bit_buffer_copy_bits,void,"BitBuffer*, const uint8_t*, size_t" +Function,+,bit_buffer_copy_bytes,void,"BitBuffer*, const uint8_t*, size_t" +Function,+,bit_buffer_copy_bytes_with_parity,void,"BitBuffer*, const uint8_t*, size_t" +Function,+,bit_buffer_copy_left,void,"BitBuffer*, const BitBuffer*, size_t" +Function,+,bit_buffer_copy_right,void,"BitBuffer*, const BitBuffer*, size_t" +Function,+,bit_buffer_free,void,BitBuffer* +Function,+,bit_buffer_get_byte,uint8_t,"const BitBuffer*, size_t" +Function,+,bit_buffer_get_byte_from_bit,uint8_t,"const BitBuffer*, size_t" +Function,+,bit_buffer_get_capacity_bytes,size_t,const BitBuffer* +Function,+,bit_buffer_get_data,const uint8_t*,const BitBuffer* +Function,+,bit_buffer_get_parity,const uint8_t*,const BitBuffer* +Function,+,bit_buffer_get_size,size_t,const BitBuffer* +Function,+,bit_buffer_get_size_bytes,size_t,const BitBuffer* +Function,+,bit_buffer_has_partial_byte,_Bool,const BitBuffer* +Function,+,bit_buffer_reset,void,BitBuffer* +Function,+,bit_buffer_set_byte,void,"BitBuffer*, size_t, uint8_t" +Function,+,bit_buffer_set_byte_with_parity,void,"BitBuffer*, size_t, uint8_t, _Bool" +Function,+,bit_buffer_set_size,void,"BitBuffer*, size_t" +Function,+,bit_buffer_set_size_bytes,void,"BitBuffer*, size_t" +Function,+,bit_buffer_starts_with_byte,_Bool,"const BitBuffer*, uint8_t" +Function,+,bit_buffer_write_bytes,void,"const BitBuffer*, void*, size_t" +Function,+,bit_buffer_write_bytes_mid,void,"const BitBuffer*, void*, size_t, size_t" +Function,+,bit_buffer_write_bytes_with_parity,void,"const BitBuffer*, void*, size_t, size_t*" Function,+,ble_app_get_key_storage_buff,void,"uint8_t**, uint16_t*" Function,+,ble_app_init,_Bool, Function,+,ble_app_thread_stop,void, @@ -678,24 +715,19 @@ Function,+,dialog_message_set_text,void,"DialogMessage*, const char*, uint8_t, u Function,+,dialog_message_show,DialogMessageButton,"DialogsApp*, const DialogMessage*" Function,+,dialog_message_show_storage_error,void,"DialogsApp*, const char*" Function,-,difftime,double,"time_t, time_t" -Function,-,digital_sequence_add,void,"DigitalSequence*, uint8_t" +Function,+,digital_sequence_add_signal,void,"DigitalSequence*, uint8_t" Function,-,digital_sequence_alloc,DigitalSequence*,"uint32_t, const GpioPin*" Function,-,digital_sequence_clear,void,DigitalSequence* Function,-,digital_sequence_free,void,DigitalSequence* -Function,-,digital_sequence_send,_Bool,DigitalSequence* -Function,-,digital_sequence_set_sendtime,void,"DigitalSequence*, uint32_t" -Function,-,digital_sequence_set_signal,void,"DigitalSequence*, uint8_t, DigitalSignal*" -Function,-,digital_sequence_timebase_correction,void,"DigitalSequence*, float" -Function,-,digital_signal_add,void,"DigitalSignal*, uint32_t" -Function,-,digital_signal_add_pulse,void,"DigitalSignal*, uint32_t, _Bool" +Function,+,digital_sequence_register_signal,void,"DigitalSequence*, uint8_t, const DigitalSignal*" +Function,+,digital_sequence_transmit,void,DigitalSequence* +Function,+,digital_signal_add_period,void,"DigitalSignal*, uint32_t" +Function,+,digital_signal_add_period_with_level,void,"DigitalSignal*, uint32_t, _Bool" Function,-,digital_signal_alloc,DigitalSignal*,uint32_t -Function,-,digital_signal_append,_Bool,"DigitalSignal*, DigitalSignal*" Function,-,digital_signal_free,void,DigitalSignal* -Function,-,digital_signal_get_edge,uint32_t,"DigitalSignal*, uint32_t" -Function,-,digital_signal_get_edges_cnt,uint32_t,DigitalSignal* -Function,-,digital_signal_get_start_level,_Bool,DigitalSignal* -Function,-,digital_signal_prepare_arr,void,DigitalSignal* -Function,-,digital_signal_send,void,"DigitalSignal*, const GpioPin*" +Function,+,digital_signal_get_size,uint32_t,const DigitalSignal* +Function,+,digital_signal_get_start_level,_Bool,const DigitalSignal* +Function,+,digital_signal_set_start_level,void,"DigitalSignal*, _Bool" Function,-,diprintf,int,"int, const char*, ..." Function,+,dir_walk_alloc,DirWalk*,Storage* Function,+,dir_walk_close,void,DirWalk* @@ -718,8 +750,6 @@ Function,-,dprintf,int,"int, const char*, ..." Function,-,drand48,double, Function,-,drem,double,"double, double" Function,-,dremf,float,"float, float" -Function,-,eTaskConfirmSleepModeStatus,eSleepModeStatus, -Function,-,eTaskGetState,eTaskState,TaskHandle_t Function,+,elements_bold_rounded_frame,void,"Canvas*, uint8_t, uint8_t, uint8_t, uint8_t" Function,+,elements_bubble,void,"Canvas*, uint8_t, uint8_t, uint8_t, uint8_t" Function,+,elements_bubble_str,void,"Canvas*, uint8_t, uint8_t, const char*, Align, Align" @@ -1309,6 +1339,7 @@ Function,+,furi_hal_vibro_on,void,_Bool Function,-,furi_init,void, Function,+,furi_kernel_get_tick_frequency,uint32_t, Function,+,furi_kernel_is_irq_or_masked,_Bool, +Function,+,furi_kernel_is_running,_Bool, Function,+,furi_kernel_lock,int32_t, Function,+,furi_kernel_restore_lock,int32_t,int32_t Function,+,furi_kernel_unlock,int32_t, @@ -1419,7 +1450,6 @@ Function,+,furi_string_utf8_push,void,"FuriString*, FuriStringUnicodeValue" Function,+,furi_string_vprintf,int,"FuriString*, const char[], va_list" Function,+,furi_thread_alloc,FuriThread*, Function,+,furi_thread_alloc_ex,FuriThread*,"const char*, uint32_t, FuriThreadCallback, void*" -Function,+,furi_thread_catch,void, Function,-,furi_thread_disable_heap_trace,void,FuriThread* Function,+,furi_thread_enable_heap_trace,void,FuriThread* Function,+,furi_thread_enumerate,uint32_t,"FuriThreadId*, uint32_t" @@ -1460,8 +1490,11 @@ Function,+,furi_thread_suspend,void,FuriThreadId Function,+,furi_thread_yield,void, Function,+,furi_timer_alloc,FuriTimer*,"FuriTimerCallback, FuriTimerType, void*" Function,+,furi_timer_free,void,FuriTimer* +Function,+,furi_timer_get_expire_time,uint32_t,FuriTimer* Function,+,furi_timer_is_running,uint32_t,FuriTimer* Function,+,furi_timer_pending_callback,void,"FuriTimerPendigCallback, void*, uint32_t" +Function,+,furi_timer_restart,FuriStatus,"FuriTimer*, uint32_t" +Function,+,furi_timer_set_thread_priority,void,FuriTimerThreadPriority Function,+,furi_timer_start,FuriStatus,"FuriTimer*, uint32_t" Function,+,furi_timer_stop,FuriStatus,FuriTimer* Function,-,fwrite,size_t,"const void*, size_t, size_t, FILE*" @@ -1776,8 +1809,35 @@ Function,+,path_extract_dirname,void,"const char*, FuriString*" Function,+,path_extract_extension,void,"FuriString*, char*, size_t" Function,+,path_extract_filename,void,"FuriString*, FuriString*, _Bool" Function,+,path_extract_filename_no_ext,void,"const char*, FuriString*" -Function,-,pcTaskGetName,char*,TaskHandle_t -Function,-,pcTimerGetName,const char*,TimerHandle_t +Function,+,pb_close_string_substream,_Bool,"pb_istream_t*, pb_istream_t*" +Function,+,pb_decode,_Bool,"pb_istream_t*, const pb_msgdesc_t*, void*" +Function,+,pb_decode_bool,_Bool,"pb_istream_t*, _Bool*" +Function,+,pb_decode_ex,_Bool,"pb_istream_t*, const pb_msgdesc_t*, void*, unsigned int" +Function,+,pb_decode_fixed32,_Bool,"pb_istream_t*, void*" +Function,+,pb_decode_fixed64,_Bool,"pb_istream_t*, void*" +Function,+,pb_decode_svarint,_Bool,"pb_istream_t*, int64_t*" +Function,+,pb_decode_tag,_Bool,"pb_istream_t*, pb_wire_type_t*, uint32_t*, _Bool*" +Function,+,pb_decode_varint,_Bool,"pb_istream_t*, uint64_t*" +Function,+,pb_decode_varint32,_Bool,"pb_istream_t*, uint32_t*" +Function,+,pb_default_field_callback,_Bool,"pb_istream_t*, pb_ostream_t*, const pb_field_t*" +Function,+,pb_encode,_Bool,"pb_ostream_t*, const pb_msgdesc_t*, const void*" +Function,+,pb_encode_ex,_Bool,"pb_ostream_t*, const pb_msgdesc_t*, const void*, unsigned int" +Function,+,pb_encode_fixed32,_Bool,"pb_ostream_t*, const void*" +Function,+,pb_encode_fixed64,_Bool,"pb_ostream_t*, const void*" +Function,+,pb_encode_string,_Bool,"pb_ostream_t*, const pb_byte_t*, size_t" +Function,+,pb_encode_submessage,_Bool,"pb_ostream_t*, const pb_msgdesc_t*, const void*" +Function,+,pb_encode_svarint,_Bool,"pb_ostream_t*, int64_t" +Function,+,pb_encode_tag,_Bool,"pb_ostream_t*, pb_wire_type_t, uint32_t" +Function,+,pb_encode_tag_for_field,_Bool,"pb_ostream_t*, const pb_field_iter_t*" +Function,+,pb_encode_varint,_Bool,"pb_ostream_t*, uint64_t" +Function,+,pb_get_encoded_size,_Bool,"size_t*, const pb_msgdesc_t*, const void*" +Function,+,pb_istream_from_buffer,pb_istream_t,"const pb_byte_t*, size_t" +Function,+,pb_make_string_substream,_Bool,"pb_istream_t*, pb_istream_t*" +Function,+,pb_ostream_from_buffer,pb_ostream_t,"pb_byte_t*, size_t" +Function,+,pb_read,_Bool,"pb_istream_t*, pb_byte_t*, size_t" +Function,+,pb_release,void,"const pb_msgdesc_t*, void*" +Function,+,pb_skip_field,_Bool,"pb_istream_t*, pb_wire_type_t" +Function,+,pb_write,_Bool,"pb_ostream_t*, const pb_byte_t*, size_t" Function,-,pclose,int,FILE* Function,-,perror,void,const char* Function,+,plugin_manager_alloc,PluginManager*,"const char*, uint32_t, const ElfApiInterface*" @@ -1852,12 +1912,6 @@ Function,-,putchar_unlocked,int,int Function,-,putenv,int,char* Function,-,puts,int,const char* Function,-,putw,int,"int, FILE*" -Function,-,pvPortCalloc,void*,"size_t, size_t" -Function,-,pvPortMalloc,void*,size_t -Function,-,pvTaskGetThreadLocalStoragePointer,void*,"TaskHandle_t, BaseType_t" -Function,-,pvTaskIncrementMutexHeldCount,TaskHandle_t, -Function,-,pvTimerGetTimerID,void*,const TimerHandle_t -Function,-,pxPortInitialiseStack,StackType_t*,"StackType_t*, TaskFunction_t, void*" Function,-,qsort,void,"void*, size_t, size_t, __compar_fn_t" Function,-,qsort_r,void,"void*, size_t, size_t, int (*)(const void*, const void*, void*), void*" Function,-,quick_exit,void,int @@ -1887,7 +1941,7 @@ Function,-,round,double,double Function,+,roundf,float,float Function,-,roundl,long double,long double Function,+,rpc_session_close,void,RpcSession* -Function,+,rpc_session_feed,size_t,"RpcSession*, uint8_t*, size_t, TickType_t" +Function,+,rpc_session_feed,size_t,"RpcSession*, uint8_t*, size_t, uint32_t" Function,+,rpc_session_get_available_size,size_t,RpcSession* Function,+,rpc_session_get_owner,RpcOwner,RpcSession* Function,+,rpc_session_open,RpcSession*,"Rpc*, RpcOwner" @@ -1896,14 +1950,12 @@ Function,+,rpc_session_set_close_callback,void,"RpcSession*, RpcSessionClosedCal Function,+,rpc_session_set_context,void,"RpcSession*, void*" Function,+,rpc_session_set_send_bytes_callback,void,"RpcSession*, RpcSendBytesCallback" Function,+,rpc_session_set_terminated_callback,void,"RpcSession*, RpcSessionTerminatedCallback" -Function,+,rpc_system_app_confirm,void,"RpcAppSystem*, RpcAppSystemEvent, _Bool" +Function,+,rpc_system_app_confirm,void,"RpcAppSystem*, _Bool" Function,+,rpc_system_app_error_reset,void,RpcAppSystem* Function,+,rpc_system_app_exchange_data,void,"RpcAppSystem*, const uint8_t*, size_t" -Function,+,rpc_system_app_get_data,const char*,RpcAppSystem* Function,+,rpc_system_app_send_exited,void,RpcAppSystem* Function,+,rpc_system_app_send_started,void,RpcAppSystem* Function,+,rpc_system_app_set_callback,void,"RpcAppSystem*, RpcAppSystemCallback, void*" -Function,+,rpc_system_app_set_data_exchange_callback,void,"RpcAppSystem*, RpcAppSystemDataExchangeCallback, void*" Function,+,rpc_system_app_set_error_code,void,"RpcAppSystem*, uint32_t" Function,+,rpc_system_app_set_error_text,void,"RpcAppSystem*, const char*" Function,-,rpmatch,int,const char* @@ -1954,6 +2006,25 @@ Function,+,sha256_finish,void,"sha256_context*, unsigned char[32]" Function,+,sha256_process,void,sha256_context* Function,+,sha256_start,void,sha256_context* Function,+,sha256_update,void,"sha256_context*, const unsigned char*, unsigned int" +Function,+,signal_reader_alloc,SignalReader*,"const GpioPin*, uint32_t" +Function,+,signal_reader_free,void,SignalReader* +Function,+,signal_reader_set_polarity,void,"SignalReader*, SignalReaderPolarity" +Function,+,signal_reader_set_pull,void,"SignalReader*, GpioPull" +Function,+,signal_reader_set_sample_rate,void,"SignalReader*, SignalReaderTimeUnit, uint32_t" +Function,+,signal_reader_set_trigger,void,"SignalReader*, SignalReaderTrigger" +Function,+,signal_reader_start,void,"SignalReader*, SignalReaderCallback, void*" +Function,+,signal_reader_stop,void,SignalReader* +Function,+,simple_array_alloc,SimpleArray*,const SimpleArrayConfig* +Function,+,simple_array_cget,const SimpleArrayElement*,"const SimpleArray*, uint32_t" +Function,+,simple_array_cget_data,const SimpleArrayData*,const SimpleArray* +Function,+,simple_array_copy,void,"SimpleArray*, const SimpleArray*" +Function,+,simple_array_free,void,SimpleArray* +Function,+,simple_array_get,SimpleArrayElement*,"SimpleArray*, uint32_t" +Function,+,simple_array_get_count,uint32_t,const SimpleArray* +Function,+,simple_array_get_data,SimpleArrayData*,SimpleArray* +Function,+,simple_array_init,void,"SimpleArray*, uint32_t" +Function,+,simple_array_is_equal,_Bool,"const SimpleArray*, const SimpleArray*" +Function,+,simple_array_reset,void,SimpleArray* Function,-,sin,double,double Function,-,sincos,void,"double, double*, double*" Function,-,sincosf,void,"float, float*, float*" @@ -2200,67 +2271,10 @@ Function,-,uECC_sign_deterministic,int,"const uint8_t*, const uint8_t*, unsigned Function,-,uECC_valid_public_key,int,"const uint8_t*, uECC_Curve" Function,-,uECC_verify,int,"const uint8_t*, const uint8_t*, unsigned, const uint8_t*, uECC_Curve" Function,+,uint8_to_hex_chars,void,"const uint8_t*, uint8_t*, int" -Function,-,ulTaskGenericNotifyTake,uint32_t,"UBaseType_t, BaseType_t, TickType_t" -Function,-,ulTaskGenericNotifyValueClear,uint32_t,"TaskHandle_t, UBaseType_t, uint32_t" -Function,-,ulTaskGetIdleRunTimeCounter,uint32_t, -Function,-,ulTaskGetIdleRunTimePercent,uint32_t, Function,-,ungetc,int,"int, FILE*" Function,-,unsetenv,int,const char* Function,-,usbd_poll,void,usbd_device* Function,-,utoa,char*,"unsigned, char*, int" -Function,-,uxListRemove,UBaseType_t,ListItem_t* -Function,-,uxTaskGetNumberOfTasks,UBaseType_t, -Function,-,uxTaskGetStackHighWaterMark,UBaseType_t,TaskHandle_t -Function,-,uxTaskGetStackHighWaterMark2,uint16_t,TaskHandle_t -Function,-,uxTaskGetSystemState,UBaseType_t,"TaskStatus_t*, const UBaseType_t, uint32_t*" -Function,-,uxTaskGetTaskNumber,UBaseType_t,TaskHandle_t -Function,-,uxTaskPriorityGet,UBaseType_t,const TaskHandle_t -Function,-,uxTaskPriorityGetFromISR,UBaseType_t,const TaskHandle_t -Function,-,uxTaskResetEventItemValue,TickType_t, -Function,-,uxTimerGetReloadMode,UBaseType_t,TimerHandle_t -Function,-,uxTimerGetTimerNumber,UBaseType_t,TimerHandle_t -Function,-,vApplicationGetIdleTaskMemory,void,"StaticTask_t**, StackType_t**, uint32_t*" -Function,-,vApplicationGetTimerTaskMemory,void,"StaticTask_t**, StackType_t**, uint32_t*" -Function,-,vListInitialise,void,List_t* -Function,-,vListInitialiseItem,void,ListItem_t* -Function,-,vListInsert,void,"List_t*, ListItem_t*" -Function,-,vListInsertEnd,void,"List_t*, ListItem_t*" -Function,-,vPortDefineHeapRegions,void,const HeapRegion_t* -Function,-,vPortEndScheduler,void, -Function,+,vPortEnterCritical,void, -Function,+,vPortExitCritical,void, -Function,-,vPortFree,void,void* -Function,-,vPortGetHeapStats,void,HeapStats_t* -Function,-,vPortInitialiseBlocks,void, -Function,-,vPortSuppressTicksAndSleep,void,TickType_t -Function,-,vTaskAllocateMPURegions,void,"TaskHandle_t, const MemoryRegion_t*" -Function,-,vTaskDelay,void,const TickType_t -Function,-,vTaskDelete,void,TaskHandle_t -Function,-,vTaskEndScheduler,void, -Function,-,vTaskGenericNotifyGiveFromISR,void,"TaskHandle_t, UBaseType_t, BaseType_t*" -Function,-,vTaskGetInfo,void,"TaskHandle_t, TaskStatus_t*, BaseType_t, eTaskState" -Function,-,vTaskGetRunTimeStats,void,char* -Function,-,vTaskInternalSetTimeOutState,void,TimeOut_t* -Function,-,vTaskList,void,char* -Function,-,vTaskMissedYield,void, -Function,-,vTaskPlaceOnEventList,void,"List_t*, const TickType_t" -Function,-,vTaskPlaceOnEventListRestricted,void,"List_t*, TickType_t, const BaseType_t" -Function,-,vTaskPlaceOnUnorderedEventList,void,"List_t*, const TickType_t, const TickType_t" -Function,-,vTaskPriorityDisinheritAfterTimeout,void,"const TaskHandle_t, UBaseType_t" -Function,+,vTaskPrioritySet,void,"TaskHandle_t, UBaseType_t" -Function,-,vTaskRemoveFromUnorderedEventList,void,"ListItem_t*, const TickType_t" -Function,-,vTaskResume,void,TaskHandle_t -Function,-,vTaskSetTaskNumber,void,"TaskHandle_t, const UBaseType_t" -Function,-,vTaskSetThreadLocalStoragePointer,void,"TaskHandle_t, BaseType_t, void*" -Function,-,vTaskSetTimeOutState,void,TimeOut_t* -Function,-,vTaskStartScheduler,void, -Function,-,vTaskStepTick,void,TickType_t -Function,-,vTaskSuspend,void,TaskHandle_t -Function,-,vTaskSuspendAll,void, -Function,-,vTaskSwitchContext,void, -Function,-,vTimerSetReloadMode,void,"TimerHandle_t, const BaseType_t" -Function,-,vTimerSetTimerID,void,"TimerHandle_t, void*" -Function,-,vTimerSetTimerNumber,void,"TimerHandle_t, UBaseType_t" Function,+,validator_is_file_alloc_init,ValidatorIsFile*,"const char*, const char*, const char*" Function,+,validator_is_file_callback,_Bool,"const char*, FuriString*, void*" Function,+,validator_is_file_free,void,ValidatorIsFile* @@ -2375,43 +2389,6 @@ Function,+,widget_alloc,Widget*, Function,+,widget_free,void,Widget* Function,+,widget_get_view,View*,Widget* Function,+,widget_reset,void,Widget* -Function,-,xPortGetFreeHeapSize,size_t, -Function,-,xPortGetMinimumEverFreeHeapSize,size_t, -Function,-,xPortStartScheduler,BaseType_t, -Function,-,xTaskAbortDelay,BaseType_t,TaskHandle_t -Function,-,xTaskCallApplicationTaskHook,BaseType_t,"TaskHandle_t, void*" -Function,-,xTaskCatchUpTicks,BaseType_t,TickType_t -Function,-,xTaskCheckForTimeOut,BaseType_t,"TimeOut_t*, TickType_t*" -Function,-,xTaskCreate,BaseType_t,"TaskFunction_t, const char*, const uint16_t, void*, UBaseType_t, TaskHandle_t*" -Function,-,xTaskCreateStatic,TaskHandle_t,"TaskFunction_t, const char*, const uint32_t, void*, UBaseType_t, StackType_t*, StaticTask_t*" -Function,-,xTaskDelayUntil,BaseType_t,"TickType_t*, const TickType_t" -Function,-,xTaskGenericNotify,BaseType_t,"TaskHandle_t, UBaseType_t, uint32_t, eNotifyAction, uint32_t*" -Function,-,xTaskGenericNotifyFromISR,BaseType_t,"TaskHandle_t, UBaseType_t, uint32_t, eNotifyAction, uint32_t*, BaseType_t*" -Function,-,xTaskGenericNotifyStateClear,BaseType_t,"TaskHandle_t, UBaseType_t" -Function,-,xTaskGenericNotifyWait,BaseType_t,"UBaseType_t, uint32_t, uint32_t, uint32_t*, TickType_t" -Function,-,xTaskGetCurrentTaskHandle,TaskHandle_t, -Function,+,xTaskGetHandle,TaskHandle_t,const char* -Function,-,xTaskGetIdleTaskHandle,TaskHandle_t, -Function,+,xTaskGetSchedulerState,BaseType_t, -Function,+,xTaskGetTickCount,TickType_t, -Function,-,xTaskGetTickCountFromISR,TickType_t, -Function,-,xTaskIncrementTick,BaseType_t, -Function,-,xTaskPriorityDisinherit,BaseType_t,const TaskHandle_t -Function,-,xTaskPriorityInherit,BaseType_t,const TaskHandle_t -Function,-,xTaskRemoveFromEventList,BaseType_t,const List_t* -Function,-,xTaskResumeAll,BaseType_t, -Function,-,xTaskResumeFromISR,BaseType_t,TaskHandle_t -Function,-,xTimerCreate,TimerHandle_t,"const char*, const TickType_t, const BaseType_t, void*, TimerCallbackFunction_t" -Function,-,xTimerCreateStatic,TimerHandle_t,"const char*, const TickType_t, const BaseType_t, void*, TimerCallbackFunction_t, StaticTimer_t*" -Function,-,xTimerCreateTimerTask,BaseType_t, -Function,-,xTimerGenericCommand,BaseType_t,"TimerHandle_t, const BaseType_t, const TickType_t, BaseType_t*, const TickType_t" -Function,-,xTimerGetExpiryTime,TickType_t,TimerHandle_t -Function,-,xTimerGetPeriod,TickType_t,TimerHandle_t -Function,-,xTimerGetReloadMode,BaseType_t,TimerHandle_t -Function,-,xTimerGetTimerDaemonTaskHandle,TaskHandle_t, -Function,-,xTimerIsTimerActive,BaseType_t,TimerHandle_t -Function,-,xTimerPendFunctionCall,BaseType_t,"PendedFunction_t, void*, uint32_t, TickType_t" -Function,-,xTimerPendFunctionCallFromISR,BaseType_t,"PendedFunction_t, void*, uint32_t, BaseType_t*" Function,-,y0,double,double Function,-,y0f,float,float Function,-,y1,double,double @@ -2695,6 +2672,7 @@ Variable,+,sequence_set_vibro_on,const NotificationSequence, Variable,+,sequence_single_vibro,const NotificationSequence, Variable,+,sequence_solid_yellow,const NotificationSequence, Variable,+,sequence_success,const NotificationSequence, +Variable,+,simple_array_config_uint8_t,const SimpleArrayConfig, Variable,-,suboptarg,char*, Variable,+,usb_ccid,FuriHalUsbInterface, Variable,+,usb_cdc_dual,FuriHalUsbInterface, diff --git a/firmware/targets/f18/furi_hal/furi_hal.c b/targets/f18/furi_hal/furi_hal.c similarity index 100% rename from firmware/targets/f18/furi_hal/furi_hal.c rename to targets/f18/furi_hal/furi_hal.c diff --git a/firmware/targets/f18/furi_hal/furi_hal_power_config.c b/targets/f18/furi_hal/furi_hal_power_config.c similarity index 100% rename from firmware/targets/f18/furi_hal/furi_hal_power_config.c rename to targets/f18/furi_hal/furi_hal_power_config.c diff --git a/firmware/targets/f18/furi_hal/furi_hal_resources.c b/targets/f18/furi_hal/furi_hal_resources.c similarity index 100% rename from firmware/targets/f18/furi_hal/furi_hal_resources.c rename to targets/f18/furi_hal/furi_hal_resources.c diff --git a/firmware/targets/f18/furi_hal/furi_hal_resources.h b/targets/f18/furi_hal/furi_hal_resources.h similarity index 100% rename from firmware/targets/f18/furi_hal/furi_hal_resources.h rename to targets/f18/furi_hal/furi_hal_resources.h diff --git a/firmware/targets/f18/furi_hal/furi_hal_spi_config.c b/targets/f18/furi_hal/furi_hal_spi_config.c similarity index 100% rename from firmware/targets/f18/furi_hal/furi_hal_spi_config.c rename to targets/f18/furi_hal/furi_hal_spi_config.c diff --git a/firmware/targets/f18/furi_hal/furi_hal_spi_config.h b/targets/f18/furi_hal/furi_hal_spi_config.h similarity index 100% rename from firmware/targets/f18/furi_hal/furi_hal_spi_config.h rename to targets/f18/furi_hal/furi_hal_spi_config.h diff --git a/firmware/targets/f18/furi_hal/furi_hal_target_hw.h b/targets/f18/furi_hal/furi_hal_target_hw.h similarity index 100% rename from firmware/targets/f18/furi_hal/furi_hal_target_hw.h rename to targets/f18/furi_hal/furi_hal_target_hw.h diff --git a/firmware/targets/f18/furi_hal/furi_hal_version_device.c b/targets/f18/furi_hal/furi_hal_version_device.c similarity index 100% rename from firmware/targets/f18/furi_hal/furi_hal_version_device.c rename to targets/f18/furi_hal/furi_hal_version_device.c diff --git a/firmware/targets/f18/target.json b/targets/f18/target.json similarity index 78% rename from firmware/targets/f18/target.json rename to targets/f18/target.json index 2d14813f6..19de9dd61 100644 --- a/firmware/targets/f18/target.json +++ b/targets/f18/target.json @@ -20,6 +20,8 @@ "littlefs", "flipperformat", "toolbox", + "digital_signal", + "signal_reader", "microtar", "usb_stm32", "appframe", @@ -31,10 +33,18 @@ "flipperformat", "toolbox", "flipper18" + ], "excluded_sources": [ "furi_hal_infrared.c", "furi_hal_nfc.c", + "furi_hal_nfc_timer.c", + "furi_hal_nfc_irq.c", + "furi_hal_nfc_event.c", + "furi_hal_nfc_iso15693.c", + "furi_hal_nfc_iso14443a.c", + "furi_hal_nfc_iso14443b.c", + "furi_hal_nfc_felica.c", "furi_hal_rfid.c", "furi_hal_subghz.c" ], @@ -51,7 +61,6 @@ "lfrfid", "subghz", "ibutton", - "infrared", - "st25rfal002" + "infrared" ] -} \ No newline at end of file +} diff --git a/firmware/targets/f7/api_symbols.csv b/targets/f7/api_symbols.csv similarity index 82% rename from firmware/targets/f7/api_symbols.csv rename to targets/f7/api_symbols.csv index 1da2f6e8f..63f739734 100644 --- a/firmware/targets/f7/api_symbols.csv +++ b/targets/f7/api_symbols.csv @@ -1,5 +1,5 @@ entry,status,name,type,params -Version,+,39.2,, +Version,+,44.0,, Header,+,applications/drivers/subghz/cc1101_ext/cc1101_ext_interconnect.h,, Header,+,applications/services/bt/bt_service/bt.h,, Header,+,applications/services/cli/cli.h,, @@ -37,56 +37,7 @@ Header,+,applications/services/notification/notification_messages.h,, Header,+,applications/services/power/power_service/power.h,, Header,+,applications/services/rpc/rpc_app.h,, Header,+,applications/services/storage/storage.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_bus.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_clock.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_console.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_dma.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_flash.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_gpio.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_i2c_config.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_i2c_types.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_ibutton.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_idle_timer.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_interrupt.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_nfc.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_os.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_pwm.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_resources.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_rfid.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_spi_config.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_spi_types.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_subghz.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_target_hw.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_uart.h,, -Header,+,firmware/targets/f7/furi_hal/furi_hal_usb_cdc.h,, -Header,+,firmware/targets/f7/platform_specific/intrinsic_export.h,, -Header,+,firmware/targets/f7/platform_specific/math_wrapper.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_bt.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_bt_hid.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_bt_serial.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_cortex.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_crypto.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_debug.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_i2c.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_info.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_infrared.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_light.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_memory.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_mpu.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_power.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_random.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_region.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_rtc.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_sd.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_speaker.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_spi.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_usb.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_usb_ccid.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_usb_hid.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_usb_hid_u2f.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_version.h,, -Header,+,firmware/targets/furi_hal_include/furi_hal_vibro.h,, +Header,+,lib/digital_signal/digital_sequence.h,, Header,+,lib/digital_signal/digital_signal.h,, Header,+,lib/drivers/cc1101_regs.h,, Header,+,lib/flipper_application/api_hashtable/api_hashtable.h,, @@ -150,18 +101,49 @@ Header,+,lib/mlib/m-rbtree.h,, Header,+,lib/mlib/m-tuple.h,, Header,+,lib/mlib/m-variant.h,, Header,+,lib/music_worker/music_worker.h,, -Header,+,lib/nfc/helpers/mfkey32.h,, -Header,+,lib/nfc/helpers/nfc_generators.h,, +Header,+,lib/nanopb/pb.h,, +Header,+,lib/nanopb/pb_decode.h,, +Header,+,lib/nanopb/pb_encode.h,, +Header,+,lib/nfc/helpers/iso13239_crc.h,, +Header,+,lib/nfc/helpers/iso14443_crc.h,, +Header,+,lib/nfc/helpers/nfc_data_generator.h,, +Header,+,lib/nfc/helpers/nfc_dict.h,, +Header,+,lib/nfc/helpers/nfc_util.h,, +Header,+,lib/nfc/nfc.h,, Header,+,lib/nfc/nfc_device.h,, -Header,+,lib/nfc/nfc_types.h,, -Header,+,lib/nfc/nfc_worker.h,, -Header,+,lib/nfc/parsers/nfc_supported_card.h,, -Header,+,lib/nfc/protocols/nfc_util.h,, +Header,+,lib/nfc/nfc_listener.h,, +Header,+,lib/nfc/nfc_poller.h,, +Header,+,lib/nfc/nfc_scanner.h,, +Header,+,lib/nfc/protocols/iso14443_3a/iso14443_3a.h,, +Header,+,lib/nfc/protocols/iso14443_3a/iso14443_3a_listener.h,, +Header,+,lib/nfc/protocols/iso14443_3a/iso14443_3a_poller.h,, +Header,+,lib/nfc/protocols/iso14443_3a/iso14443_3a_poller_sync_api.h,, +Header,+,lib/nfc/protocols/iso14443_3b/iso14443_3b.h,, +Header,+,lib/nfc/protocols/iso14443_3b/iso14443_3b_poller.h,, +Header,+,lib/nfc/protocols/iso14443_4a/iso14443_4a.h,, +Header,+,lib/nfc/protocols/iso14443_4a/iso14443_4a_listener.h,, +Header,+,lib/nfc/protocols/iso14443_4a/iso14443_4a_poller.h,, +Header,+,lib/nfc/protocols/iso14443_4b/iso14443_4b.h,, +Header,+,lib/nfc/protocols/iso14443_4b/iso14443_4b_poller.h,, +Header,+,lib/nfc/protocols/mf_classic/mf_classic.h,, +Header,+,lib/nfc/protocols/mf_classic/mf_classic_listener.h,, +Header,+,lib/nfc/protocols/mf_classic/mf_classic_poller.h,, +Header,+,lib/nfc/protocols/mf_classic/mf_classic_poller_sync_api.h,, +Header,+,lib/nfc/protocols/mf_desfire/mf_desfire.h,, +Header,+,lib/nfc/protocols/mf_desfire/mf_desfire_poller.h,, +Header,+,lib/nfc/protocols/mf_ultralight/mf_ultralight.h,, +Header,+,lib/nfc/protocols/mf_ultralight/mf_ultralight_listener.h,, +Header,+,lib/nfc/protocols/mf_ultralight/mf_ultralight_poller.h,, +Header,+,lib/nfc/protocols/mf_ultralight/mf_ultralight_poller_sync_api.h,, +Header,+,lib/nfc/protocols/slix/slix.h,, +Header,+,lib/nfc/protocols/st25tb/st25tb.h,, +Header,+,lib/nfc/protocols/st25tb/st25tb_poller.h,, Header,+,lib/one_wire/maxim_crc.h,, Header,+,lib/one_wire/one_wire_host.h,, Header,+,lib/one_wire/one_wire_slave.h,, Header,+,lib/print/wrappers.h,, Header,+,lib/pulse_reader/pulse_reader.h,, +Header,+,lib/signal_reader/signal_reader.h,, Header,+,lib/stm32wb_hal/Inc/stm32wbxx_ll_adc.h,, Header,+,lib/stm32wb_hal/Inc/stm32wbxx_ll_bus.h,, Header,+,lib/stm32wb_hal/Inc/stm32wbxx_ll_comp.h,, @@ -198,6 +180,7 @@ Header,+,lib/subghz/blocks/math.h,, Header,+,lib/subghz/devices/cc1101_configs.h,, Header,+,lib/subghz/devices/cc1101_int/cc1101_int_interconnect.h,, Header,+,lib/subghz/environment.h,, +Header,+,lib/subghz/protocols/public_api.h,, Header,+,lib/subghz/protocols/raw.h,, Header,+,lib/subghz/receiver.h,, Header,+,lib/subghz/registry.h,, @@ -209,6 +192,7 @@ Header,+,lib/subghz/subghz_worker.h,, Header,+,lib/subghz/transmitter.h,, Header,+,lib/toolbox/api_lock.h,, Header,+,lib/toolbox/args.h,, +Header,+,lib/toolbox/bit_buffer.h,, Header,+,lib/toolbox/compress.h,, Header,+,lib/toolbox/crc32_calc.h,, Header,+,lib/toolbox/dir_walk.h,, @@ -223,6 +207,7 @@ Header,+,lib/toolbox/pretty_format.h,, Header,+,lib/toolbox/protocols/protocol_dict.h,, Header,+,lib/toolbox/saved_struct.h,, Header,+,lib/toolbox/sha256.h,, +Header,+,lib/toolbox/simple_array.h,, Header,+,lib/toolbox/stream/buffered_file_stream.h,, Header,+,lib/toolbox/stream/file_stream.h,, Header,+,lib/toolbox/stream/stream.h,, @@ -230,6 +215,56 @@ Header,+,lib/toolbox/stream/string_stream.h,, Header,+,lib/toolbox/tar/tar_archive.h,, Header,+,lib/toolbox/value_index.h,, Header,+,lib/toolbox/version.h,, +Header,+,targets/f7/furi_hal/furi_hal_bus.h,, +Header,+,targets/f7/furi_hal/furi_hal_clock.h,, +Header,+,targets/f7/furi_hal/furi_hal_console.h,, +Header,+,targets/f7/furi_hal/furi_hal_dma.h,, +Header,+,targets/f7/furi_hal/furi_hal_flash.h,, +Header,+,targets/f7/furi_hal/furi_hal_gpio.h,, +Header,+,targets/f7/furi_hal/furi_hal_i2c_config.h,, +Header,+,targets/f7/furi_hal/furi_hal_i2c_types.h,, +Header,+,targets/f7/furi_hal/furi_hal_ibutton.h,, +Header,+,targets/f7/furi_hal/furi_hal_idle_timer.h,, +Header,+,targets/f7/furi_hal/furi_hal_interrupt.h,, +Header,+,targets/f7/furi_hal/furi_hal_os.h,, +Header,+,targets/f7/furi_hal/furi_hal_pwm.h,, +Header,+,targets/f7/furi_hal/furi_hal_resources.h,, +Header,+,targets/f7/furi_hal/furi_hal_rfid.h,, +Header,+,targets/f7/furi_hal/furi_hal_spi_config.h,, +Header,+,targets/f7/furi_hal/furi_hal_spi_types.h,, +Header,+,targets/f7/furi_hal/furi_hal_subghz.h,, +Header,+,targets/f7/furi_hal/furi_hal_target_hw.h,, +Header,+,targets/f7/furi_hal/furi_hal_uart.h,, +Header,+,targets/f7/furi_hal/furi_hal_usb_cdc.h,, +Header,+,targets/f7/platform_specific/intrinsic_export.h,, +Header,+,targets/f7/platform_specific/math_wrapper.h,, +Header,+,targets/furi_hal_include/furi_hal.h,, +Header,+,targets/furi_hal_include/furi_hal_bt.h,, +Header,+,targets/furi_hal_include/furi_hal_bt_hid.h,, +Header,+,targets/furi_hal_include/furi_hal_bt_serial.h,, +Header,+,targets/furi_hal_include/furi_hal_cortex.h,, +Header,+,targets/furi_hal_include/furi_hal_crypto.h,, +Header,+,targets/furi_hal_include/furi_hal_debug.h,, +Header,+,targets/furi_hal_include/furi_hal_i2c.h,, +Header,+,targets/furi_hal_include/furi_hal_info.h,, +Header,+,targets/furi_hal_include/furi_hal_infrared.h,, +Header,+,targets/furi_hal_include/furi_hal_light.h,, +Header,+,targets/furi_hal_include/furi_hal_memory.h,, +Header,+,targets/furi_hal_include/furi_hal_mpu.h,, +Header,+,targets/furi_hal_include/furi_hal_nfc.h,, +Header,+,targets/furi_hal_include/furi_hal_power.h,, +Header,+,targets/furi_hal_include/furi_hal_random.h,, +Header,+,targets/furi_hal_include/furi_hal_region.h,, +Header,+,targets/furi_hal_include/furi_hal_rtc.h,, +Header,+,targets/furi_hal_include/furi_hal_sd.h,, +Header,+,targets/furi_hal_include/furi_hal_speaker.h,, +Header,+,targets/furi_hal_include/furi_hal_spi.h,, +Header,+,targets/furi_hal_include/furi_hal_usb.h,, +Header,+,targets/furi_hal_include/furi_hal_usb_ccid.h,, +Header,+,targets/furi_hal_include/furi_hal_usb_hid.h,, +Header,+,targets/furi_hal_include/furi_hal_usb_hid_u2f.h,, +Header,+,targets/furi_hal_include/furi_hal_version.h,, +Header,+,targets/furi_hal_include/furi_hal_vibro.h,, Function,-,LL_ADC_CommonDeInit,ErrorStatus,ADC_Common_TypeDef* Function,-,LL_ADC_CommonInit,ErrorStatus,"ADC_Common_TypeDef*, const LL_ADC_CommonInitTypeDef*" Function,-,LL_ADC_CommonStructInit,void,LL_ADC_CommonInitTypeDef* @@ -338,10 +373,10 @@ Function,-,__eprintf,void,"const char*, const char*, unsigned int, const char*" Function,+,__errno,int*, Function,-,__fpclassifyd,int,double Function,-,__fpclassifyf,int,float -Function,+,__furi_crash,void, +Function,+,__furi_crash_implementation,void, Function,+,__furi_critical_enter,__FuriCriticalInfo, Function,+,__furi_critical_exit,void,__FuriCriticalInfo -Function,+,__furi_halt,void, +Function,+,__furi_halt_implementation,void, Function,-,__getdelim,ssize_t,"char**, size_t*, int, FILE*" Function,-,__getline,ssize_t,"char**, size_t*, FILE*" Function,-,__isinfd,int,double @@ -453,7 +488,6 @@ Function,-,_perror_r,void,"_reent*, const char*" Function,-,_printf_r,int,"_reent*, const char*, ..." Function,-,_putc_r,int,"_reent*, int, FILE*" Function,-,_putc_unlocked_r,int,"_reent*, int, FILE*" -Function,-,_putchar,void,char Function,-,_putchar_r,int,"_reent*, int" Function,-,_putchar_unlocked_r,int,"_reent*, int" Function,-,_putenv_r,int,"_reent*, char*" @@ -565,6 +599,36 @@ Function,-,atoll,long long,const char* Function,-,basename,char*,const char* Function,-,bcmp,int,"const void*, const void*, size_t" Function,-,bcopy,void,"const void*, void*, size_t" +Function,+,bit_buffer_alloc,BitBuffer*,size_t +Function,+,bit_buffer_append,void,"BitBuffer*, const BitBuffer*" +Function,+,bit_buffer_append_bit,void,"BitBuffer*, _Bool" +Function,+,bit_buffer_append_byte,void,"BitBuffer*, uint8_t" +Function,+,bit_buffer_append_bytes,void,"BitBuffer*, const uint8_t*, size_t" +Function,+,bit_buffer_append_right,void,"BitBuffer*, const BitBuffer*, size_t" +Function,+,bit_buffer_copy,void,"BitBuffer*, const BitBuffer*" +Function,+,bit_buffer_copy_bits,void,"BitBuffer*, const uint8_t*, size_t" +Function,+,bit_buffer_copy_bytes,void,"BitBuffer*, const uint8_t*, size_t" +Function,+,bit_buffer_copy_bytes_with_parity,void,"BitBuffer*, const uint8_t*, size_t" +Function,+,bit_buffer_copy_left,void,"BitBuffer*, const BitBuffer*, size_t" +Function,+,bit_buffer_copy_right,void,"BitBuffer*, const BitBuffer*, size_t" +Function,+,bit_buffer_free,void,BitBuffer* +Function,+,bit_buffer_get_byte,uint8_t,"const BitBuffer*, size_t" +Function,+,bit_buffer_get_byte_from_bit,uint8_t,"const BitBuffer*, size_t" +Function,+,bit_buffer_get_capacity_bytes,size_t,const BitBuffer* +Function,+,bit_buffer_get_data,const uint8_t*,const BitBuffer* +Function,+,bit_buffer_get_parity,const uint8_t*,const BitBuffer* +Function,+,bit_buffer_get_size,size_t,const BitBuffer* +Function,+,bit_buffer_get_size_bytes,size_t,const BitBuffer* +Function,+,bit_buffer_has_partial_byte,_Bool,const BitBuffer* +Function,+,bit_buffer_reset,void,BitBuffer* +Function,+,bit_buffer_set_byte,void,"BitBuffer*, size_t, uint8_t" +Function,+,bit_buffer_set_byte_with_parity,void,"BitBuffer*, size_t, uint8_t, _Bool" +Function,+,bit_buffer_set_size,void,"BitBuffer*, size_t" +Function,+,bit_buffer_set_size_bytes,void,"BitBuffer*, size_t" +Function,+,bit_buffer_starts_with_byte,_Bool,"const BitBuffer*, uint8_t" +Function,+,bit_buffer_write_bytes,void,"const BitBuffer*, void*, size_t" +Function,+,bit_buffer_write_bytes_mid,void,"const BitBuffer*, void*, size_t, size_t" +Function,+,bit_buffer_write_bytes_with_parity,void,"const BitBuffer*, void*, size_t, size_t*" Function,+,bit_lib_add_parity,size_t,"const uint8_t*, size_t, uint8_t*, size_t, uint8_t, uint8_t, BitLibParity" Function,+,bit_lib_copy_bits,void,"uint8_t*, size_t, size_t, const uint8_t*, size_t" Function,+,bit_lib_crc16,uint16_t,"const uint8_t*, size_t, uint16_t, uint16_t, _Bool, _Bool, uint16_t" @@ -725,14 +789,6 @@ Function,-,coshl,long double,long double Function,-,cosl,long double,long double Function,+,crc32_calc_buffer,uint32_t,"uint32_t, const void*, size_t" Function,+,crc32_calc_file,uint32_t,"File*, const FileCrcProgressCb, void*" -Function,-,crypto1_bit,uint8_t,"Crypto1*, uint8_t, int" -Function,-,crypto1_byte,uint8_t,"Crypto1*, uint8_t, int" -Function,-,crypto1_decrypt,void,"Crypto1*, uint8_t*, uint16_t, uint8_t*" -Function,-,crypto1_encrypt,void,"Crypto1*, uint8_t*, uint8_t*, uint16_t, uint8_t*, uint8_t*" -Function,-,crypto1_filter,uint32_t,uint32_t -Function,-,crypto1_init,void,"Crypto1*, uint64_t" -Function,-,crypto1_reset,void,Crypto1* -Function,-,crypto1_word,uint32_t,"Crypto1*, uint32_t, int" Function,-,ctermid,char*,char* Function,-,ctime,char*,const time_t* Function,-,ctime_r,char*,"const time_t*, char*" @@ -762,24 +818,19 @@ Function,+,dialog_message_set_text,void,"DialogMessage*, const char*, uint8_t, u Function,+,dialog_message_show,DialogMessageButton,"DialogsApp*, const DialogMessage*" Function,+,dialog_message_show_storage_error,void,"DialogsApp*, const char*" Function,-,difftime,double,"time_t, time_t" -Function,-,digital_sequence_add,void,"DigitalSequence*, uint8_t" +Function,+,digital_sequence_add_signal,void,"DigitalSequence*, uint8_t" Function,-,digital_sequence_alloc,DigitalSequence*,"uint32_t, const GpioPin*" Function,-,digital_sequence_clear,void,DigitalSequence* Function,-,digital_sequence_free,void,DigitalSequence* -Function,-,digital_sequence_send,_Bool,DigitalSequence* -Function,-,digital_sequence_set_sendtime,void,"DigitalSequence*, uint32_t" -Function,-,digital_sequence_set_signal,void,"DigitalSequence*, uint8_t, DigitalSignal*" -Function,-,digital_sequence_timebase_correction,void,"DigitalSequence*, float" -Function,-,digital_signal_add,void,"DigitalSignal*, uint32_t" -Function,-,digital_signal_add_pulse,void,"DigitalSignal*, uint32_t, _Bool" +Function,+,digital_sequence_register_signal,void,"DigitalSequence*, uint8_t, const DigitalSignal*" +Function,+,digital_sequence_transmit,void,DigitalSequence* +Function,+,digital_signal_add_period,void,"DigitalSignal*, uint32_t" +Function,+,digital_signal_add_period_with_level,void,"DigitalSignal*, uint32_t, _Bool" Function,-,digital_signal_alloc,DigitalSignal*,uint32_t -Function,-,digital_signal_append,_Bool,"DigitalSignal*, DigitalSignal*" Function,-,digital_signal_free,void,DigitalSignal* -Function,-,digital_signal_get_edge,uint32_t,"DigitalSignal*, uint32_t" -Function,-,digital_signal_get_edges_cnt,uint32_t,DigitalSignal* -Function,-,digital_signal_get_start_level,_Bool,DigitalSignal* -Function,-,digital_signal_prepare_arr,void,DigitalSignal* -Function,-,digital_signal_send,void,"DigitalSignal*, const GpioPin*" +Function,+,digital_signal_get_size,uint32_t,const DigitalSignal* +Function,+,digital_signal_get_start_level,_Bool,const DigitalSignal* +Function,+,digital_signal_set_start_level,void,"DigitalSignal*, _Bool" Function,-,diprintf,int,"int, const char*, ..." Function,+,dir_walk_alloc,DirWalk*,Storage* Function,+,dir_walk_close,void,DirWalk* @@ -802,8 +853,6 @@ Function,-,dprintf,int,"int, const char*, ..." Function,-,drand48,double, Function,-,drem,double,"double, double" Function,-,dremf,float,"float, float" -Function,-,eTaskConfirmSleepModeStatus,eSleepModeStatus, -Function,-,eTaskGetState,eTaskState,TaskHandle_t Function,+,elements_bold_rounded_frame,void,"Canvas*, uint8_t, uint8_t, uint8_t, uint8_t" Function,+,elements_bubble,void,"Canvas*, uint8_t, uint8_t, uint8_t, uint8_t" Function,+,elements_bubble_str,void,"Canvas*, uint8_t, uint8_t, const char*, Align, Align" @@ -829,8 +878,6 @@ Function,+,elf_symbolname_hash,uint32_t,const char* Function,+,empty_screen_alloc,EmptyScreen*, Function,+,empty_screen_free,void,EmptyScreen* Function,+,empty_screen_get_view,View*,EmptyScreen* -Function,-,emv_card_emulation,_Bool,FuriHalNfcTxRxContext* -Function,-,emv_read_bank_card,_Bool,"FuriHalNfcTxRxContext*, EmvApplication*" Function,-,erand48,double,unsigned short[3] Function,-,erf,double,double Function,-,erfc,double,double @@ -1264,38 +1311,44 @@ Function,-,furi_hal_mpu_init,void, Function,+,furi_hal_mpu_protect_disable,void,FuriHalMpuRegion Function,+,furi_hal_mpu_protect_no_access,void,"FuriHalMpuRegion, uint32_t, FuriHalMPURegionSize" Function,+,furi_hal_mpu_protect_read_only,void,"FuriHalMpuRegion, uint32_t, FuriHalMPURegionSize" -Function,+,furi_hal_nfc_activate_nfca,_Bool,"uint32_t, uint32_t*" -Function,+,furi_hal_nfc_deinit,void, -Function,+,furi_hal_nfc_detect,_Bool,"FuriHalNfcDevData*, uint32_t" -Function,+,furi_hal_nfc_emulate_nfca,_Bool,"uint8_t*, uint8_t, uint8_t*, uint8_t, FuriHalNfcEmulateCallback, void*, uint32_t" -Function,+,furi_hal_nfc_exit_sleep,void, -Function,+,furi_hal_nfc_field_detect_start,void, +Function,+,furi_hal_nfc_abort,FuriHalNfcError, +Function,+,furi_hal_nfc_acquire,FuriHalNfcError, +Function,+,furi_hal_nfc_event_start,FuriHalNfcError, +Function,+,furi_hal_nfc_event_stop,FuriHalNfcError, +Function,+,furi_hal_nfc_field_detect_start,FuriHalNfcError, +Function,+,furi_hal_nfc_field_detect_stop,FuriHalNfcError, Function,+,furi_hal_nfc_field_is_present,_Bool, -Function,+,furi_hal_nfc_field_off,void, -Function,+,furi_hal_nfc_field_on,void, -Function,+,furi_hal_nfc_init,void, -Function,+,furi_hal_nfc_is_busy,_Bool, -Function,+,furi_hal_nfc_is_init,_Bool, -Function,+,furi_hal_nfc_listen,_Bool,"uint8_t*, uint8_t, uint8_t*, uint8_t, _Bool, uint32_t" -Function,+,furi_hal_nfc_listen_rx,_Bool,"FuriHalNfcTxRxContext*, uint32_t" -Function,+,furi_hal_nfc_listen_sleep,void, -Function,+,furi_hal_nfc_listen_start,void,FuriHalNfcDevData* -Function,+,furi_hal_nfc_ll_poll,void, -Function,+,furi_hal_nfc_ll_set_error_handling,void,FuriHalNfcErrorHandling -Function,+,furi_hal_nfc_ll_set_fdt_listen,void,uint32_t -Function,+,furi_hal_nfc_ll_set_fdt_poll,void,uint32_t -Function,+,furi_hal_nfc_ll_set_guard_time,void,uint32_t -Function,+,furi_hal_nfc_ll_set_mode,FuriHalNfcReturn,"FuriHalNfcMode, FuriHalNfcBitrate, FuriHalNfcBitrate" -Function,+,furi_hal_nfc_ll_txrx,FuriHalNfcReturn,"uint8_t*, uint16_t, uint8_t*, uint16_t, uint16_t*, uint32_t, uint32_t" -Function,+,furi_hal_nfc_ll_txrx_bits,FuriHalNfcReturn,"uint8_t*, uint16_t, uint8_t*, uint16_t, uint16_t*, uint32_t, uint32_t" -Function,+,furi_hal_nfc_ll_txrx_off,void, -Function,+,furi_hal_nfc_ll_txrx_on,void, -Function,+,furi_hal_nfc_sleep,void, -Function,+,furi_hal_nfc_start_sleep,void, -Function,+,furi_hal_nfc_stop,void, -Function,+,furi_hal_nfc_stop_cmd,void, -Function,+,furi_hal_nfc_tx_rx,_Bool,"FuriHalNfcTxRxContext*, uint16_t" -Function,+,furi_hal_nfc_tx_rx_full,_Bool,FuriHalNfcTxRxContext* +Function,+,furi_hal_nfc_init,FuriHalNfcError, +Function,+,furi_hal_nfc_is_hal_ready,FuriHalNfcError, +Function,+,furi_hal_nfc_iso14443a_listener_set_col_res_data,FuriHalNfcError,"uint8_t*, uint8_t, uint8_t*, uint8_t" +Function,+,furi_hal_nfc_iso14443a_listener_tx_custom_parity,FuriHalNfcError,"const uint8_t*, const uint8_t*, size_t" +Function,+,furi_hal_nfc_iso14443a_poller_trx_short_frame,FuriHalNfcError,FuriHalNfcaShortFrame +Function,+,furi_hal_nfc_iso14443a_poller_tx_custom_parity,FuriHalNfcError,"const uint8_t*, size_t" +Function,+,furi_hal_nfc_iso14443a_rx_sdd_frame,FuriHalNfcError,"uint8_t*, size_t, size_t*" +Function,+,furi_hal_nfc_iso14443a_tx_sdd_frame,FuriHalNfcError,"const uint8_t*, size_t" +Function,+,furi_hal_nfc_iso15693_listener_tx_sof,FuriHalNfcError, +Function,+,furi_hal_nfc_listener_enable_rx,FuriHalNfcError, +Function,+,furi_hal_nfc_listener_idle,FuriHalNfcError, +Function,+,furi_hal_nfc_listener_rx,FuriHalNfcError,"uint8_t*, size_t, size_t*" +Function,+,furi_hal_nfc_listener_sleep,FuriHalNfcError, +Function,+,furi_hal_nfc_listener_tx,FuriHalNfcError,"const uint8_t*, size_t" +Function,+,furi_hal_nfc_listener_wait_event,FuriHalNfcEvent,uint32_t +Function,+,furi_hal_nfc_low_power_mode_start,FuriHalNfcError, +Function,+,furi_hal_nfc_low_power_mode_stop,FuriHalNfcError, +Function,+,furi_hal_nfc_poller_field_on,FuriHalNfcError, +Function,+,furi_hal_nfc_poller_rx,FuriHalNfcError,"uint8_t*, size_t, size_t*" +Function,+,furi_hal_nfc_poller_tx,FuriHalNfcError,"const uint8_t*, size_t" +Function,+,furi_hal_nfc_poller_wait_event,FuriHalNfcEvent,uint32_t +Function,+,furi_hal_nfc_release,FuriHalNfcError, +Function,+,furi_hal_nfc_reset_mode,FuriHalNfcError, +Function,+,furi_hal_nfc_set_mode,FuriHalNfcError,"FuriHalNfcMode, FuriHalNfcTech" +Function,+,furi_hal_nfc_timer_block_tx_is_running,_Bool, +Function,+,furi_hal_nfc_timer_block_tx_start,void,uint32_t +Function,+,furi_hal_nfc_timer_block_tx_start_us,void,uint32_t +Function,+,furi_hal_nfc_timer_block_tx_stop,void, +Function,+,furi_hal_nfc_timer_fwt_start,void,uint32_t +Function,+,furi_hal_nfc_timer_fwt_stop,void, +Function,+,furi_hal_nfc_trx_reset,FuriHalNfcError, Function,-,furi_hal_os_init,void, Function,+,furi_hal_os_tick,void, Function,+,furi_hal_power_check_otg_fault,_Bool, @@ -1519,6 +1572,7 @@ Function,+,furi_hal_vibro_on,void,_Bool Function,-,furi_init,void, Function,+,furi_kernel_get_tick_frequency,uint32_t, Function,+,furi_kernel_is_irq_or_masked,_Bool, +Function,+,furi_kernel_is_running,_Bool, Function,+,furi_kernel_lock,int32_t, Function,+,furi_kernel_restore_lock,int32_t,int32_t Function,+,furi_kernel_unlock,int32_t, @@ -1629,7 +1683,6 @@ Function,+,furi_string_utf8_push,void,"FuriString*, FuriStringUnicodeValue" Function,+,furi_string_vprintf,int,"FuriString*, const char[], va_list" Function,+,furi_thread_alloc,FuriThread*, Function,+,furi_thread_alloc_ex,FuriThread*,"const char*, uint32_t, FuriThreadCallback, void*" -Function,+,furi_thread_catch,void, Function,-,furi_thread_disable_heap_trace,void,FuriThread* Function,+,furi_thread_enable_heap_trace,void,FuriThread* Function,+,furi_thread_enumerate,uint32_t,"FuriThreadId*, uint32_t" @@ -1670,8 +1723,11 @@ Function,+,furi_thread_suspend,void,FuriThreadId Function,+,furi_thread_yield,void, Function,+,furi_timer_alloc,FuriTimer*,"FuriTimerCallback, FuriTimerType, void*" Function,+,furi_timer_free,void,FuriTimer* +Function,+,furi_timer_get_expire_time,uint32_t,FuriTimer* Function,+,furi_timer_is_running,uint32_t,FuriTimer* Function,+,furi_timer_pending_callback,void,"FuriTimerPendigCallback, void*, uint32_t" +Function,+,furi_timer_restart,FuriStatus,"FuriTimer*, uint32_t" +Function,+,furi_timer_set_thread_priority,void,FuriTimerThreadPriority Function,+,furi_timer_start,FuriStatus,"FuriTimer*, uint32_t" Function,+,furi_timer_stop,FuriStatus,FuriTimer* Function,-,fwrite,size_t,"const void*, size_t, size_t, FILE*" @@ -1830,6 +1886,97 @@ Function,-,islower,int,int Function,-,islower_l,int,"int, locale_t" Function,-,isnan,int,double Function,-,isnanf,int,float +Function,+,iso13239_crc_append,void,"Iso13239CrcType, BitBuffer*" +Function,+,iso13239_crc_check,_Bool,"Iso13239CrcType, const BitBuffer*" +Function,+,iso13239_crc_trim,void,BitBuffer* +Function,+,iso14443_3a_alloc,Iso14443_3aData*, +Function,+,iso14443_3a_copy,void,"Iso14443_3aData*, const Iso14443_3aData*" +Function,+,iso14443_3a_free,void,Iso14443_3aData* +Function,+,iso14443_3a_get_atqa,void,"const Iso14443_3aData*, uint8_t[2]" +Function,+,iso14443_3a_get_base_data,Iso14443_3aData*,const Iso14443_3aData* +Function,+,iso14443_3a_get_cuid,uint32_t,const Iso14443_3aData* +Function,+,iso14443_3a_get_device_name,const char*,"const Iso14443_3aData*, NfcDeviceNameType" +Function,+,iso14443_3a_get_sak,uint8_t,const Iso14443_3aData* +Function,+,iso14443_3a_get_uid,const uint8_t*,"const Iso14443_3aData*, size_t*" +Function,+,iso14443_3a_is_equal,_Bool,"const Iso14443_3aData*, const Iso14443_3aData*" +Function,+,iso14443_3a_load,_Bool,"Iso14443_3aData*, FlipperFormat*, uint32_t" +Function,+,iso14443_3a_poller_read,Iso14443_3aError,"Nfc*, Iso14443_3aData*" +Function,+,iso14443_3a_poller_send_standard_frame,Iso14443_3aError,"Iso14443_3aPoller*, const BitBuffer*, BitBuffer*, uint32_t" +Function,+,iso14443_3a_poller_txrx,Iso14443_3aError,"Iso14443_3aPoller*, const BitBuffer*, BitBuffer*, uint32_t" +Function,+,iso14443_3a_reset,void,Iso14443_3aData* +Function,+,iso14443_3a_save,_Bool,"const Iso14443_3aData*, FlipperFormat*" +Function,+,iso14443_3a_set_atqa,void,"Iso14443_3aData*, const uint8_t[2]" +Function,+,iso14443_3a_set_sak,void,"Iso14443_3aData*, uint8_t" +Function,+,iso14443_3a_set_uid,_Bool,"Iso14443_3aData*, const uint8_t*, size_t" +Function,+,iso14443_3a_supports_iso14443_4,_Bool,const Iso14443_3aData* +Function,+,iso14443_3a_verify,_Bool,"Iso14443_3aData*, const FuriString*" +Function,+,iso14443_3b_alloc,Iso14443_3bData*, +Function,+,iso14443_3b_copy,void,"Iso14443_3bData*, const Iso14443_3bData*" +Function,+,iso14443_3b_free,void,Iso14443_3bData* +Function,+,iso14443_3b_get_application_data,const uint8_t*,"const Iso14443_3bData*, size_t*" +Function,+,iso14443_3b_get_base_data,Iso14443_3bData*,const Iso14443_3bData* +Function,+,iso14443_3b_get_device_name,const char*,"const Iso14443_3bData*, NfcDeviceNameType" +Function,+,iso14443_3b_get_frame_size_max,uint16_t,const Iso14443_3bData* +Function,+,iso14443_3b_get_fwt_fc_max,uint32_t,const Iso14443_3bData* +Function,+,iso14443_3b_get_uid,const uint8_t*,"const Iso14443_3bData*, size_t*" +Function,+,iso14443_3b_is_equal,_Bool,"const Iso14443_3bData*, const Iso14443_3bData*" +Function,+,iso14443_3b_load,_Bool,"Iso14443_3bData*, FlipperFormat*, uint32_t" +Function,+,iso14443_3b_reset,void,Iso14443_3bData* +Function,+,iso14443_3b_save,_Bool,"const Iso14443_3bData*, FlipperFormat*" +Function,+,iso14443_3b_set_uid,_Bool,"Iso14443_3bData*, const uint8_t*, size_t" +Function,+,iso14443_3b_supports_bit_rate,_Bool,"const Iso14443_3bData*, Iso14443_3bBitRate" +Function,+,iso14443_3b_supports_frame_option,_Bool,"const Iso14443_3bData*, Iso14443_3bFrameOption" +Function,+,iso14443_3b_supports_iso14443_4,_Bool,const Iso14443_3bData* +Function,+,iso14443_3b_verify,_Bool,"Iso14443_3bData*, const FuriString*" +Function,+,iso14443_4a_alloc,Iso14443_4aData*, +Function,+,iso14443_4a_copy,void,"Iso14443_4aData*, const Iso14443_4aData*" +Function,+,iso14443_4a_free,void,Iso14443_4aData* +Function,+,iso14443_4a_get_base_data,Iso14443_3aData*,const Iso14443_4aData* +Function,+,iso14443_4a_get_device_name,const char*,"const Iso14443_4aData*, NfcDeviceNameType" +Function,+,iso14443_4a_get_frame_size_max,uint16_t,const Iso14443_4aData* +Function,+,iso14443_4a_get_fwt_fc_max,uint32_t,const Iso14443_4aData* +Function,+,iso14443_4a_get_historical_bytes,const uint8_t*,"const Iso14443_4aData*, uint32_t*" +Function,+,iso14443_4a_get_uid,const uint8_t*,"const Iso14443_4aData*, size_t*" +Function,+,iso14443_4a_is_equal,_Bool,"const Iso14443_4aData*, const Iso14443_4aData*" +Function,+,iso14443_4a_load,_Bool,"Iso14443_4aData*, FlipperFormat*, uint32_t" +Function,+,iso14443_4a_reset,void,Iso14443_4aData* +Function,+,iso14443_4a_save,_Bool,"const Iso14443_4aData*, FlipperFormat*" +Function,+,iso14443_4a_set_uid,_Bool,"Iso14443_4aData*, const uint8_t*, size_t" +Function,+,iso14443_4a_supports_bit_rate,_Bool,"const Iso14443_4aData*, Iso14443_4aBitRate" +Function,+,iso14443_4a_supports_frame_option,_Bool,"const Iso14443_4aData*, Iso14443_4aFrameOption" +Function,+,iso14443_4a_verify,_Bool,"Iso14443_4aData*, const FuriString*" +Function,+,iso14443_4b_alloc,Iso14443_4bData*, +Function,+,iso14443_4b_copy,void,"Iso14443_4bData*, const Iso14443_4bData*" +Function,+,iso14443_4b_free,void,Iso14443_4bData* +Function,+,iso14443_4b_get_base_data,Iso14443_3bData*,const Iso14443_4bData* +Function,+,iso14443_4b_get_device_name,const char*,"const Iso14443_4bData*, NfcDeviceNameType" +Function,+,iso14443_4b_get_uid,const uint8_t*,"const Iso14443_4bData*, size_t*" +Function,+,iso14443_4b_is_equal,_Bool,"const Iso14443_4bData*, const Iso14443_4bData*" +Function,+,iso14443_4b_load,_Bool,"Iso14443_4bData*, FlipperFormat*, uint32_t" +Function,+,iso14443_4b_reset,void,Iso14443_4bData* +Function,+,iso14443_4b_save,_Bool,"const Iso14443_4bData*, FlipperFormat*" +Function,+,iso14443_4b_set_uid,_Bool,"Iso14443_4bData*, const uint8_t*, size_t" +Function,+,iso14443_4b_verify,_Bool,"Iso14443_4bData*, const FuriString*" +Function,+,iso14443_crc_append,void,"Iso14443CrcType, BitBuffer*" +Function,+,iso14443_crc_check,_Bool,"Iso14443CrcType, const BitBuffer*" +Function,+,iso14443_crc_trim,void,BitBuffer* +Function,+,iso15693_3_alloc,Iso15693_3Data*, +Function,+,iso15693_3_copy,void,"Iso15693_3Data*, const Iso15693_3Data*" +Function,+,iso15693_3_free,void,Iso15693_3Data* +Function,+,iso15693_3_get_base_data,Iso15693_3Data*,const Iso15693_3Data* +Function,+,iso15693_3_get_block_count,uint16_t,const Iso15693_3Data* +Function,+,iso15693_3_get_block_data,const uint8_t*,"const Iso15693_3Data*, uint8_t" +Function,+,iso15693_3_get_block_size,uint8_t,const Iso15693_3Data* +Function,+,iso15693_3_get_device_name,const char*,"const Iso15693_3Data*, NfcDeviceNameType" +Function,+,iso15693_3_get_manufacturer_id,uint8_t,const Iso15693_3Data* +Function,+,iso15693_3_get_uid,const uint8_t*,"const Iso15693_3Data*, size_t*" +Function,+,iso15693_3_is_block_locked,_Bool,"const Iso15693_3Data*, uint8_t" +Function,+,iso15693_3_is_equal,_Bool,"const Iso15693_3Data*, const Iso15693_3Data*" +Function,+,iso15693_3_load,_Bool,"Iso15693_3Data*, FlipperFormat*, uint32_t" +Function,+,iso15693_3_reset,void,Iso15693_3Data* +Function,+,iso15693_3_save,_Bool,"const Iso15693_3Data*, FlipperFormat*" +Function,+,iso15693_3_set_uid,_Bool,"Iso15693_3Data*, const uint8_t*, size_t" +Function,+,iso15693_3_verify,_Bool,"Iso15693_3Data*, const FuriString*" Function,-,isprint,int,int Function,-,isprint_l,int,"int, locale_t" Function,-,ispunct,int,int @@ -1965,7 +2112,7 @@ Function,-,mbedtls_des_setkey_enc,int,"mbedtls_des_context*, const unsigned char Function,-,mbedtls_internal_sha1_process,int,"mbedtls_sha1_context*, const unsigned char[64]" Function,-,mbedtls_platform_gmtime_r,tm*,"const mbedtls_time_t*, tm*" Function,-,mbedtls_platform_zeroize,void,"void*, size_t" -Function,-,mbedtls_sha1,int,"const unsigned char*, size_t, unsigned char[20]" +Function,+,mbedtls_sha1,int,"const unsigned char*, size_t, unsigned char[20]" Function,-,mbedtls_sha1_clone,void,"mbedtls_sha1_context*, const mbedtls_sha1_context*" Function,-,mbedtls_sha1_finish,int,"mbedtls_sha1_context*, unsigned char[20]" Function,-,mbedtls_sha1_free,void,mbedtls_sha1_context* @@ -2007,120 +2154,93 @@ Function,+,menu_free,void,Menu* Function,+,menu_get_view,View*,Menu* Function,+,menu_reset,void,Menu* Function,+,menu_set_selected_item,void,"Menu*, uint32_t" -Function,-,mf_classic_auth_attempt,_Bool,"FuriHalNfcTxRxContext*, Crypto1*, MfClassicAuthContext*, uint64_t" -Function,-,mf_classic_auth_init_context,void,"MfClassicAuthContext*, uint8_t" -Function,-,mf_classic_auth_write_block,_Bool,"FuriHalNfcTxRxContext*, MfClassicBlock*, uint8_t, MfClassicKey, uint64_t" -Function,-,mf_classic_authenticate,_Bool,"FuriHalNfcTxRxContext*, uint8_t, uint64_t, MfClassicKey" -Function,-,mf_classic_authenticate_skip_activate,_Bool,"FuriHalNfcTxRxContext*, uint8_t, uint64_t, MfClassicKey, _Bool, uint32_t" -Function,-,mf_classic_block_to_value,_Bool,"const uint8_t*, int32_t*, uint8_t*" -Function,-,mf_classic_check_card_type,_Bool,"uint8_t, uint8_t, uint8_t" -Function,+,mf_classic_dict_add_key,_Bool,"MfClassicDict*, uint8_t*" -Function,-,mf_classic_dict_add_key_str,_Bool,"MfClassicDict*, FuriString*" -Function,+,mf_classic_dict_alloc,MfClassicDict*,MfClassicDictType -Function,+,mf_classic_dict_check_presence,_Bool,MfClassicDictType -Function,+,mf_classic_dict_delete_index,_Bool,"MfClassicDict*, uint32_t" -Function,-,mf_classic_dict_find_index,_Bool,"MfClassicDict*, uint8_t*, uint32_t*" -Function,-,mf_classic_dict_find_index_str,_Bool,"MfClassicDict*, FuriString*, uint32_t*" -Function,+,mf_classic_dict_free,void,MfClassicDict* -Function,-,mf_classic_dict_get_key_at_index,_Bool,"MfClassicDict*, uint64_t*, uint32_t" -Function,+,mf_classic_dict_get_key_at_index_str,_Bool,"MfClassicDict*, FuriString*, uint32_t" -Function,-,mf_classic_dict_get_next_key,_Bool,"MfClassicDict*, uint64_t*" -Function,+,mf_classic_dict_get_next_key_str,_Bool,"MfClassicDict*, FuriString*" -Function,+,mf_classic_dict_get_total_keys,uint32_t,MfClassicDict* -Function,+,mf_classic_dict_is_key_present,_Bool,"MfClassicDict*, uint8_t*" -Function,-,mf_classic_dict_is_key_present_str,_Bool,"MfClassicDict*, FuriString*" -Function,-,mf_classic_dict_rewind,_Bool,MfClassicDict* -Function,-,mf_classic_emulator,_Bool,"MfClassicEmulator*, FuriHalNfcTxRxContext*, _Bool" -Function,-,mf_classic_get_classic_type,MfClassicType,"uint8_t, uint8_t, uint8_t" -Function,+,mf_classic_get_read_sectors_and_keys,void,"MfClassicData*, uint8_t*, uint8_t*" +Function,+,mf_classic_alloc,MfClassicData*, +Function,+,mf_classic_block_to_value,_Bool,"const MfClassicBlock*, int32_t*, uint8_t*" +Function,+,mf_classic_copy,void,"MfClassicData*, const MfClassicData*" +Function,+,mf_classic_free,void,MfClassicData* +Function,+,mf_classic_get_base_data,Iso14443_3aData*,const MfClassicData* +Function,+,mf_classic_get_blocks_num_in_sector,uint8_t,uint8_t +Function,+,mf_classic_get_device_name,const char*,"const MfClassicData*, NfcDeviceNameType" +Function,+,mf_classic_get_first_block_num_of_sector,uint8_t,uint8_t +Function,+,mf_classic_get_read_sectors_and_keys,void,"const MfClassicData*, uint8_t*, uint8_t*" Function,+,mf_classic_get_sector_by_block,uint8_t,uint8_t -Function,-,mf_classic_get_sector_trailer_block_num_by_sector,uint8_t,uint8_t -Function,+,mf_classic_get_sector_trailer_by_sector,MfClassicSectorTrailer*,"MfClassicData*, uint8_t" -Function,-,mf_classic_get_total_block_num,uint16_t,MfClassicType +Function,+,mf_classic_get_sector_trailer_by_sector,MfClassicSectorTrailer*,"const MfClassicData*, uint8_t" +Function,+,mf_classic_get_sector_trailer_num_by_block,uint8_t,uint8_t +Function,+,mf_classic_get_sector_trailer_num_by_sector,uint8_t,uint8_t +Function,+,mf_classic_get_total_block_num,uint16_t,MfClassicType Function,+,mf_classic_get_total_sectors_num,uint8_t,MfClassicType -Function,-,mf_classic_get_type_str,const char*,MfClassicType -Function,-,mf_classic_halt,void,"FuriHalNfcTxRxContext*, Crypto1*" -Function,-,mf_classic_is_allowed_access_data_block,_Bool,"MfClassicData*, uint8_t, MfClassicKey, MfClassicAction" -Function,-,mf_classic_is_allowed_access_sector_trailer,_Bool,"MfClassicData*, uint8_t, MfClassicKey, MfClassicAction" -Function,+,mf_classic_is_block_read,_Bool,"MfClassicData*, uint8_t" -Function,+,mf_classic_is_card_read,_Bool,MfClassicData* -Function,+,mf_classic_is_key_found,_Bool,"MfClassicData*, uint8_t, MfClassicKey" -Function,-,mf_classic_is_sector_data_read,_Bool,"MfClassicData*, uint8_t" -Function,-,mf_classic_is_sector_read,_Bool,"MfClassicData*, uint8_t" +Function,+,mf_classic_get_uid,const uint8_t*,"const MfClassicData*, size_t*" +Function,+,mf_classic_is_allowed_access,_Bool,"MfClassicData*, uint8_t, MfClassicKeyType, MfClassicAction" +Function,+,mf_classic_is_allowed_access_data_block,_Bool,"MfClassicSectorTrailer*, uint8_t, MfClassicKeyType, MfClassicAction" +Function,+,mf_classic_is_block_read,_Bool,"const MfClassicData*, uint8_t" +Function,+,mf_classic_is_card_read,_Bool,const MfClassicData* +Function,+,mf_classic_is_equal,_Bool,"const MfClassicData*, const MfClassicData*" +Function,+,mf_classic_is_key_found,_Bool,"const MfClassicData*, uint8_t, MfClassicKeyType" +Function,+,mf_classic_is_sector_read,_Bool,"const MfClassicData*, uint8_t" Function,+,mf_classic_is_sector_trailer,_Bool,uint8_t -Function,-,mf_classic_is_value_block,_Bool,"MfClassicData*, uint8_t" -Function,-,mf_classic_read_block,_Bool,"FuriHalNfcTxRxContext*, Crypto1*, uint8_t, MfClassicBlock*" -Function,-,mf_classic_read_card,uint8_t,"FuriHalNfcTxRxContext*, MfClassicReader*, MfClassicData*" -Function,-,mf_classic_read_sector,void,"FuriHalNfcTxRxContext*, MfClassicData*, uint8_t" -Function,-,mf_classic_reader_add_sector,void,"MfClassicReader*, uint8_t, uint64_t, uint64_t" -Function,-,mf_classic_set_block_read,void,"MfClassicData*, uint8_t, MfClassicBlock*" -Function,-,mf_classic_set_key_found,void,"MfClassicData*, uint8_t, MfClassicKey, uint64_t" -Function,-,mf_classic_set_key_not_found,void,"MfClassicData*, uint8_t, MfClassicKey" -Function,-,mf_classic_set_sector_data_not_read,void,MfClassicData* -Function,-,mf_classic_transfer,_Bool,"FuriHalNfcTxRxContext*, Crypto1*, uint8_t" -Function,-,mf_classic_update_card,uint8_t,"FuriHalNfcTxRxContext*, MfClassicData*" -Function,-,mf_classic_value_cmd,_Bool,"FuriHalNfcTxRxContext*, Crypto1*, uint8_t, uint8_t, int32_t" -Function,-,mf_classic_value_cmd_full,_Bool,"FuriHalNfcTxRxContext*, MfClassicBlock*, uint8_t, MfClassicKey, uint64_t, int32_t" -Function,-,mf_classic_value_to_block,void,"int32_t, uint8_t, uint8_t*" -Function,-,mf_classic_write_block,_Bool,"FuriHalNfcTxRxContext*, Crypto1*, uint8_t, MfClassicBlock*" -Function,-,mf_classic_write_sector,_Bool,"FuriHalNfcTxRxContext*, MfClassicData*, MfClassicData*, uint8_t" -Function,-,mf_df_cat_application,void,"MifareDesfireApplication*, FuriString*" -Function,+,mf_df_cat_application_info,void,"MifareDesfireApplication*, FuriString*" -Function,+,mf_df_cat_card_info,void,"MifareDesfireData*, FuriString*" -Function,-,mf_df_cat_data,void,"MifareDesfireData*, FuriString*" -Function,+,mf_df_cat_file,void,"MifareDesfireFile*, FuriString*" -Function,-,mf_df_cat_free_mem,void,"MifareDesfireFreeMemory*, FuriString*" -Function,-,mf_df_cat_key_settings,void,"MifareDesfireKeySettings*, FuriString*" -Function,-,mf_df_cat_version,void,"MifareDesfireVersion*, FuriString*" -Function,-,mf_df_check_card_type,_Bool,"uint8_t, uint8_t, uint8_t" -Function,-,mf_df_clear,void,MifareDesfireData* -Function,-,mf_df_get_application,MifareDesfireApplication*,"MifareDesfireData*, const uint8_t[3]*" -Function,-,mf_df_get_file,MifareDesfireFile*,"MifareDesfireApplication*, uint8_t" -Function,-,mf_df_parse_get_application_ids_response,_Bool,"uint8_t*, uint16_t, MifareDesfireApplication**" -Function,-,mf_df_parse_get_file_ids_response,_Bool,"uint8_t*, uint16_t, MifareDesfireFile**" -Function,-,mf_df_parse_get_file_settings_response,_Bool,"uint8_t*, uint16_t, MifareDesfireFile*" -Function,-,mf_df_parse_get_free_memory_response,_Bool,"uint8_t*, uint16_t, MifareDesfireFreeMemory*" -Function,-,mf_df_parse_get_key_settings_response,_Bool,"uint8_t*, uint16_t, MifareDesfireKeySettings*" -Function,-,mf_df_parse_get_key_version_response,_Bool,"uint8_t*, uint16_t, MifareDesfireKeyVersion*" -Function,-,mf_df_parse_get_version_response,_Bool,"uint8_t*, uint16_t, MifareDesfireVersion*" -Function,-,mf_df_parse_read_data_response,_Bool,"uint8_t*, uint16_t, MifareDesfireFile*" -Function,-,mf_df_parse_select_application_response,_Bool,"uint8_t*, uint16_t" -Function,-,mf_df_prepare_get_application_ids,uint16_t,uint8_t* -Function,-,mf_df_prepare_get_file_ids,uint16_t,uint8_t* -Function,-,mf_df_prepare_get_file_settings,uint16_t,"uint8_t*, uint8_t" -Function,-,mf_df_prepare_get_free_memory,uint16_t,uint8_t* -Function,-,mf_df_prepare_get_key_settings,uint16_t,uint8_t* -Function,-,mf_df_prepare_get_key_version,uint16_t,"uint8_t*, uint8_t" -Function,-,mf_df_prepare_get_value,uint16_t,"uint8_t*, uint8_t" -Function,-,mf_df_prepare_get_version,uint16_t,uint8_t* -Function,-,mf_df_prepare_read_data,uint16_t,"uint8_t*, uint8_t, uint32_t, uint32_t" -Function,-,mf_df_prepare_read_records,uint16_t,"uint8_t*, uint8_t, uint32_t, uint32_t" -Function,-,mf_df_prepare_select_application,uint16_t,"uint8_t*, uint8_t[3]" -Function,-,mf_df_read_card,_Bool,"FuriHalNfcTxRxContext*, MifareDesfireData*" -Function,-,mf_ul_check_card_type,_Bool,"uint8_t, uint8_t, uint8_t" -Function,+,mf_ul_emulation_supported,_Bool,MfUltralightData* -Function,+,mf_ul_is_full_capture,_Bool,MfUltralightData* -Function,-,mf_ul_prepare_emulation,void,"MfUltralightEmulator*, MfUltralightData*" -Function,-,mf_ul_prepare_emulation_response,_Bool,"uint8_t*, uint16_t, uint8_t*, uint16_t*, uint32_t*, void*" -Function,-,mf_ul_pwdgen_amiibo,uint32_t,FuriHalNfcDevData* -Function,-,mf_ul_pwdgen_xiaomi,uint32_t,FuriHalNfcDevData* -Function,-,mf_ul_read_card,_Bool,"FuriHalNfcTxRxContext*, MfUltralightReader*, MfUltralightData*" -Function,-,mf_ul_reset,void,MfUltralightData* -Function,-,mf_ul_reset_emulation,void,"MfUltralightEmulator*, _Bool" -Function,-,mf_ultralight_authenticate,_Bool,"FuriHalNfcTxRxContext*, uint32_t, uint16_t*" -Function,-,mf_ultralight_fast_read_pages,_Bool,"FuriHalNfcTxRxContext*, MfUltralightReader*, MfUltralightData*" -Function,+,mf_ultralight_get_config_pages,MfUltralightConfigPages*,MfUltralightData* -Function,-,mf_ultralight_read_counters,_Bool,"FuriHalNfcTxRxContext*, MfUltralightData*" -Function,-,mf_ultralight_read_pages,_Bool,"FuriHalNfcTxRxContext*, MfUltralightReader*, MfUltralightData*" -Function,-,mf_ultralight_read_pages_direct,_Bool,"FuriHalNfcTxRxContext*, uint8_t, uint8_t*" -Function,-,mf_ultralight_read_signature,_Bool,"FuriHalNfcTxRxContext*, MfUltralightData*" -Function,-,mf_ultralight_read_tearing_flags,_Bool,"FuriHalNfcTxRxContext*, MfUltralightData*" -Function,-,mf_ultralight_read_version,_Bool,"FuriHalNfcTxRxContext*, MfUltralightReader*, MfUltralightData*" -Function,-,mfkey32_alloc,Mfkey32*,uint32_t -Function,-,mfkey32_free,void,Mfkey32* -Function,+,mfkey32_get_auth_sectors,uint16_t,FuriString* -Function,-,mfkey32_process_data,void,"Mfkey32*, uint8_t*, uint16_t, _Bool, _Bool" -Function,-,mfkey32_set_callback,void,"Mfkey32*, Mfkey32ParseDataCallback, void*" +Function,+,mf_classic_is_value_block,_Bool,"MfClassicSectorTrailer*, uint8_t" +Function,+,mf_classic_load,_Bool,"MfClassicData*, FlipperFormat*, uint32_t" +Function,+,mf_classic_poller_auth,MfClassicError,"Nfc*, uint8_t, MfClassicKey*, MfClassicKeyType, MfClassicAuthContext*" +Function,+,mf_classic_poller_change_value,MfClassicError,"Nfc*, uint8_t, MfClassicKey*, MfClassicKeyType, int32_t, int32_t*" +Function,+,mf_classic_poller_collect_nt,MfClassicError,"Nfc*, uint8_t, MfClassicKeyType, MfClassicNt*" +Function,+,mf_classic_poller_detect_type,MfClassicError,"Nfc*, MfClassicType*" +Function,+,mf_classic_poller_read,MfClassicError,"Nfc*, const MfClassicDeviceKeys*, MfClassicData*" +Function,+,mf_classic_poller_read_block,MfClassicError,"Nfc*, uint8_t, MfClassicKey*, MfClassicKeyType, MfClassicBlock*" +Function,+,mf_classic_poller_read_value,MfClassicError,"Nfc*, uint8_t, MfClassicKey*, MfClassicKeyType, int32_t*" +Function,+,mf_classic_poller_write_block,MfClassicError,"Nfc*, uint8_t, MfClassicKey*, MfClassicKeyType, MfClassicBlock*" +Function,+,mf_classic_reset,void,MfClassicData* +Function,+,mf_classic_save,_Bool,"const MfClassicData*, FlipperFormat*" +Function,+,mf_classic_set_block_read,void,"MfClassicData*, uint8_t, MfClassicBlock*" +Function,+,mf_classic_set_key_found,void,"MfClassicData*, uint8_t, MfClassicKeyType, uint64_t" +Function,+,mf_classic_set_key_not_found,void,"MfClassicData*, uint8_t, MfClassicKeyType" +Function,+,mf_classic_set_uid,_Bool,"MfClassicData*, const uint8_t*, size_t" +Function,+,mf_classic_value_to_block,void,"int32_t, uint8_t, MfClassicBlock*" +Function,+,mf_classic_verify,_Bool,"MfClassicData*, const FuriString*" +Function,+,mf_desfire_alloc,MfDesfireData*, +Function,+,mf_desfire_copy,void,"MfDesfireData*, const MfDesfireData*" +Function,+,mf_desfire_free,void,MfDesfireData* +Function,+,mf_desfire_get_application,const MfDesfireApplication*,"const MfDesfireData*, const MfDesfireApplicationId*" +Function,+,mf_desfire_get_base_data,Iso14443_4aData*,const MfDesfireData* +Function,+,mf_desfire_get_device_name,const char*,"const MfDesfireData*, NfcDeviceNameType" +Function,+,mf_desfire_get_file_data,const MfDesfireFileData*,"const MfDesfireApplication*, const MfDesfireFileId*" +Function,+,mf_desfire_get_file_settings,const MfDesfireFileSettings*,"const MfDesfireApplication*, const MfDesfireFileId*" +Function,+,mf_desfire_get_uid,const uint8_t*,"const MfDesfireData*, size_t*" +Function,+,mf_desfire_is_equal,_Bool,"const MfDesfireData*, const MfDesfireData*" +Function,+,mf_desfire_load,_Bool,"MfDesfireData*, FlipperFormat*, uint32_t" +Function,+,mf_desfire_reset,void,MfDesfireData* +Function,+,mf_desfire_save,_Bool,"const MfDesfireData*, FlipperFormat*" +Function,+,mf_desfire_set_uid,_Bool,"MfDesfireData*, const uint8_t*, size_t" +Function,+,mf_desfire_verify,_Bool,"MfDesfireData*, const FuriString*" +Function,+,mf_ultralight_alloc,MfUltralightData*, +Function,+,mf_ultralight_copy,void,"MfUltralightData*, const MfUltralightData*" +Function,+,mf_ultralight_detect_protocol,_Bool,const Iso14443_3aData* +Function,+,mf_ultralight_free,void,MfUltralightData* +Function,+,mf_ultralight_get_base_data,Iso14443_3aData*,const MfUltralightData* +Function,+,mf_ultralight_get_config_page,_Bool,"const MfUltralightData*, MfUltralightConfigPages**" +Function,+,mf_ultralight_get_config_page_num,uint16_t,MfUltralightType +Function,+,mf_ultralight_get_device_name,const char*,"const MfUltralightData*, NfcDeviceNameType" +Function,+,mf_ultralight_get_feature_support_set,uint32_t,MfUltralightType +Function,+,mf_ultralight_get_pages_total,uint16_t,MfUltralightType +Function,+,mf_ultralight_get_pwd_page_num,uint8_t,MfUltralightType +Function,+,mf_ultralight_get_type_by_version,MfUltralightType,MfUltralightVersion* +Function,+,mf_ultralight_get_uid,const uint8_t*,"const MfUltralightData*, size_t*" +Function,+,mf_ultralight_is_all_data_read,_Bool,const MfUltralightData* +Function,+,mf_ultralight_is_counter_configured,_Bool,const MfUltralightData* +Function,+,mf_ultralight_is_equal,_Bool,"const MfUltralightData*, const MfUltralightData*" +Function,+,mf_ultralight_is_page_pwd_or_pack,_Bool,"MfUltralightType, uint16_t" +Function,+,mf_ultralight_load,_Bool,"MfUltralightData*, FlipperFormat*, uint32_t" +Function,+,mf_ultralight_poller_read_card,MfUltralightError,"Nfc*, MfUltralightData*" +Function,+,mf_ultralight_poller_read_counter,MfUltralightError,"Nfc*, uint8_t, MfUltralightCounter*" +Function,+,mf_ultralight_poller_read_page,MfUltralightError,"Nfc*, uint16_t, MfUltralightPage*" +Function,+,mf_ultralight_poller_read_signature,MfUltralightError,"Nfc*, MfUltralightSignature*" +Function,+,mf_ultralight_poller_read_tearing_flag,MfUltralightError,"Nfc*, uint8_t, MfUltralightTearingFlag*" +Function,+,mf_ultralight_poller_read_version,MfUltralightError,"Nfc*, MfUltralightVersion*" +Function,+,mf_ultralight_poller_write_page,MfUltralightError,"Nfc*, uint16_t, MfUltralightPage*" +Function,+,mf_ultralight_reset,void,MfUltralightData* +Function,+,mf_ultralight_save,_Bool,"const MfUltralightData*, FlipperFormat*" +Function,+,mf_ultralight_set_uid,_Bool,"MfUltralightData*, const uint8_t*, size_t" +Function,+,mf_ultralight_support_feature,_Bool,"const uint32_t, const uint32_t" +Function,+,mf_ultralight_verify,_Bool,"MfUltralightData*, const FuriString*" Function,-,mkdtemp,char*,char* Function,-,mkostemp,int,"char*, int" Function,-,mkostemps,int,"char*, int, int" @@ -2159,53 +2279,76 @@ Function,-,nextafterl,long double,"long double, long double" Function,-,nexttoward,double,"double, long double" Function,-,nexttowardf,float,"float, long double" Function,-,nexttowardl,long double,"long double, long double" +Function,+,nfc_alloc,Nfc*, +Function,+,nfc_config,void,"Nfc*, NfcMode, NfcTech" +Function,+,nfc_data_generator_fill_data,void,"NfcDataGeneratorType, NfcDevice*" +Function,+,nfc_data_generator_get_name,const char*,NfcDataGeneratorType Function,+,nfc_device_alloc,NfcDevice*, Function,+,nfc_device_clear,void,NfcDevice* -Function,+,nfc_device_data_clear,void,NfcDeviceData* -Function,+,nfc_device_delete,_Bool,"NfcDevice*, _Bool" +Function,+,nfc_device_copy_data,void,"const NfcDevice*, NfcProtocol, NfcDeviceData*" Function,+,nfc_device_free,void,NfcDevice* -Function,+,nfc_device_load,_Bool,"NfcDevice*, const char*, _Bool" -Function,+,nfc_device_load_key_cache,_Bool,NfcDevice* -Function,+,nfc_device_restore,_Bool,"NfcDevice*, _Bool" +Function,+,nfc_device_get_data,const NfcDeviceData*,"const NfcDevice*, NfcProtocol" +Function,+,nfc_device_get_name,const char*,"const NfcDevice*, NfcDeviceNameType" +Function,+,nfc_device_get_protocol,NfcProtocol,const NfcDevice* +Function,+,nfc_device_get_protocol_name,const char*,NfcProtocol +Function,+,nfc_device_get_uid,const uint8_t*,"const NfcDevice*, size_t*" +Function,+,nfc_device_is_equal,_Bool,"const NfcDevice*, const NfcDevice*" +Function,+,nfc_device_is_equal_data,_Bool,"const NfcDevice*, NfcProtocol, const NfcDeviceData*" +Function,+,nfc_device_load,_Bool,"NfcDevice*, const char*" +Function,+,nfc_device_reset,void,NfcDevice* Function,+,nfc_device_save,_Bool,"NfcDevice*, const char*" -Function,+,nfc_device_save_shadow,_Bool,"NfcDevice*, const char*" +Function,+,nfc_device_set_data,void,"NfcDevice*, NfcProtocol, const NfcDeviceData*" Function,+,nfc_device_set_loading_callback,void,"NfcDevice*, NfcLoadingCallback, void*" -Function,+,nfc_device_set_name,void,"NfcDevice*, const char*" -Function,+,nfc_file_select,_Bool,NfcDevice* -Function,-,nfc_generate_mf_classic,void,"NfcDeviceData*, uint8_t, MfClassicType" -Function,+,nfc_generate_mf_classic_ext,void,"NfcDeviceData*, uint8_t, MfClassicType, _Bool, uint8_t*" -Function,+,nfc_get_dev_type,const char*,FuriHalNfcType -Function,-,nfc_guess_protocol,const char*,NfcProtocol -Function,+,nfc_mf_classic_type,const char*,MfClassicType -Function,+,nfc_mf_ul_type,const char*,"MfUltralightType, _Bool" -Function,+,nfc_supported_card_verify_and_parse,_Bool,NfcDeviceData* +Function,+,nfc_device_set_uid,_Bool,"NfcDevice*, const uint8_t*, size_t" +Function,+,nfc_dict_add_key,_Bool,"NfcDict*, const uint8_t*, size_t" +Function,+,nfc_dict_alloc,NfcDict*,"const char*, NfcDictMode, size_t" +Function,+,nfc_dict_check_presence,_Bool,const char* +Function,+,nfc_dict_delete_key,_Bool,"NfcDict*, const uint8_t*, size_t" +Function,+,nfc_dict_free,void,NfcDict* +Function,+,nfc_dict_get_next_key,_Bool,"NfcDict*, uint8_t*, size_t" +Function,+,nfc_dict_get_total_keys,uint32_t,NfcDict* +Function,+,nfc_dict_is_key_present,_Bool,"NfcDict*, const uint8_t*, size_t" +Function,+,nfc_dict_rewind,_Bool,NfcDict* +Function,+,nfc_free,void,Nfc* +Function,+,nfc_iso14443a_listener_set_col_res_data,NfcError,"Nfc*, uint8_t*, uint8_t, uint8_t*, uint8_t" +Function,+,nfc_iso14443a_listener_tx_custom_parity,NfcError,"Nfc*, const BitBuffer*" +Function,+,nfc_iso14443a_poller_trx_custom_parity,NfcError,"Nfc*, const BitBuffer*, BitBuffer*, uint32_t" +Function,+,nfc_iso14443a_poller_trx_sdd_frame,NfcError,"Nfc*, const BitBuffer*, BitBuffer*, uint32_t" +Function,+,nfc_iso14443a_poller_trx_short_frame,NfcError,"Nfc*, NfcIso14443aShortFrame, BitBuffer*, uint32_t" +Function,+,nfc_iso15693_listener_tx_sof,NfcError,Nfc* +Function,+,nfc_listener_alloc,NfcListener*,"Nfc*, NfcProtocol, const NfcDeviceData*" +Function,+,nfc_listener_free,void,NfcListener* +Function,+,nfc_listener_get_data,const NfcDeviceData*,"const NfcListener*, NfcProtocol" +Function,+,nfc_listener_get_protocol,NfcProtocol,const NfcListener* +Function,+,nfc_listener_start,void,"NfcListener*, NfcGenericCallback, void*" +Function,+,nfc_listener_stop,void,NfcListener* +Function,+,nfc_listener_tx,NfcError,"Nfc*, const BitBuffer*" +Function,+,nfc_poller_alloc,NfcPoller*,"Nfc*, NfcProtocol" +Function,+,nfc_poller_detect,_Bool,NfcPoller* +Function,+,nfc_poller_free,void,NfcPoller* +Function,+,nfc_poller_get_data,const NfcDeviceData*,const NfcPoller* +Function,+,nfc_poller_get_protocol,NfcProtocol,const NfcPoller* +Function,+,nfc_poller_start,void,"NfcPoller*, NfcGenericCallback, void*" +Function,+,nfc_poller_stop,void,NfcPoller* +Function,+,nfc_poller_trx,NfcError,"Nfc*, const BitBuffer*, BitBuffer*, uint32_t" +Function,+,nfc_protocol_get_parent,NfcProtocol,NfcProtocol +Function,+,nfc_protocol_has_parent,_Bool,"NfcProtocol, NfcProtocol" +Function,+,nfc_scanner_alloc,NfcScanner*,Nfc* +Function,+,nfc_scanner_free,void,NfcScanner* +Function,+,nfc_scanner_start,void,"NfcScanner*, NfcScannerCallback, void*" +Function,+,nfc_scanner_stop,void,NfcScanner* +Function,+,nfc_set_fdt_listen_fc,void,"Nfc*, uint32_t" +Function,+,nfc_set_fdt_poll_fc,void,"Nfc*, uint32_t" +Function,+,nfc_set_fdt_poll_poll_us,void,"Nfc*, uint32_t" +Function,+,nfc_set_guard_time_us,void,"Nfc*, uint32_t" +Function,+,nfc_set_mask_receive_time_fc,void,"Nfc*, uint32_t" +Function,+,nfc_start,void,"Nfc*, NfcEventCallback, void*" +Function,+,nfc_stop,void,Nfc* Function,+,nfc_util_bytes2num,uint64_t,"const uint8_t*, uint8_t" Function,+,nfc_util_even_parity32,uint8_t,uint32_t Function,+,nfc_util_num2bytes,void,"uint64_t, uint8_t, uint8_t*" Function,+,nfc_util_odd_parity,void,"const uint8_t*, uint8_t*, uint8_t" Function,+,nfc_util_odd_parity8,uint8_t,uint8_t -Function,+,nfc_worker_alloc,NfcWorker*, -Function,+,nfc_worker_free,void,NfcWorker* -Function,+,nfc_worker_get_state,NfcWorkerState,NfcWorker* -Function,-,nfc_worker_nfcv_emulate,void,NfcWorker* -Function,-,nfc_worker_nfcv_sniff,void,NfcWorker* -Function,-,nfc_worker_nfcv_unlock,void,NfcWorker* -Function,+,nfc_worker_start,void,"NfcWorker*, NfcWorkerState, NfcDeviceData*, NfcWorkerCallback, void*" -Function,+,nfc_worker_stop,void,NfcWorker* -Function,-,nfca_append_crc16,void,"uint8_t*, uint16_t" -Function,-,nfca_emulation_handler,_Bool,"uint8_t*, uint16_t, uint8_t*, uint16_t*" -Function,-,nfca_get_crc16,uint16_t,"uint8_t*, uint16_t" -Function,-,nfca_signal_alloc,NfcaSignal*, -Function,-,nfca_signal_encode,void,"NfcaSignal*, uint8_t*, uint16_t, uint8_t*" -Function,-,nfca_signal_free,void,NfcaSignal* -Function,+,nfcv_emu_deinit,void,NfcVData* -Function,+,nfcv_emu_init,void,"FuriHalNfcDevData*, NfcVData*" -Function,+,nfcv_emu_loop,_Bool,"FuriHalNfcTxRxContext*, FuriHalNfcDevData*, NfcVData*, uint32_t" -Function,+,nfcv_emu_send,void,"FuriHalNfcTxRxContext*, NfcVData*, uint8_t*, uint8_t, NfcVSendFlags, uint32_t" -Function,-,nfcv_inventory,ReturnCode,uint8_t* -Function,-,nfcv_read_blocks,ReturnCode,"NfcVReader*, NfcVData*" -Function,-,nfcv_read_card,_Bool,"NfcVReader*, FuriHalNfcDevData*, NfcVData*" -Function,-,nfcv_read_sysinfo,ReturnCode,"FuriHalNfcDevData*, NfcVData*" Function,+,notification_internal_message,void,"NotificationApp*, const NotificationSequence*" Function,+,notification_internal_message_block,void,"NotificationApp*, const NotificationSequence*" Function,+,notification_message,void,"NotificationApp*, const NotificationSequence*" @@ -2248,16 +2391,37 @@ Function,+,path_extract_dirname,void,"const char*, FuriString*" Function,+,path_extract_extension,void,"FuriString*, char*, size_t" Function,+,path_extract_filename,void,"FuriString*, FuriString*, _Bool" Function,+,path_extract_filename_no_ext,void,"const char*, FuriString*" -Function,-,pcTaskGetName,char*,TaskHandle_t -Function,-,pcTimerGetName,const char*,TimerHandle_t +Function,+,pb_close_string_substream,_Bool,"pb_istream_t*, pb_istream_t*" +Function,+,pb_decode,_Bool,"pb_istream_t*, const pb_msgdesc_t*, void*" +Function,+,pb_decode_bool,_Bool,"pb_istream_t*, _Bool*" +Function,+,pb_decode_ex,_Bool,"pb_istream_t*, const pb_msgdesc_t*, void*, unsigned int" +Function,+,pb_decode_fixed32,_Bool,"pb_istream_t*, void*" +Function,+,pb_decode_fixed64,_Bool,"pb_istream_t*, void*" +Function,+,pb_decode_svarint,_Bool,"pb_istream_t*, int64_t*" +Function,+,pb_decode_tag,_Bool,"pb_istream_t*, pb_wire_type_t*, uint32_t*, _Bool*" +Function,+,pb_decode_varint,_Bool,"pb_istream_t*, uint64_t*" +Function,+,pb_decode_varint32,_Bool,"pb_istream_t*, uint32_t*" +Function,+,pb_default_field_callback,_Bool,"pb_istream_t*, pb_ostream_t*, const pb_field_t*" +Function,+,pb_encode,_Bool,"pb_ostream_t*, const pb_msgdesc_t*, const void*" +Function,+,pb_encode_ex,_Bool,"pb_ostream_t*, const pb_msgdesc_t*, const void*, unsigned int" +Function,+,pb_encode_fixed32,_Bool,"pb_ostream_t*, const void*" +Function,+,pb_encode_fixed64,_Bool,"pb_ostream_t*, const void*" +Function,+,pb_encode_string,_Bool,"pb_ostream_t*, const pb_byte_t*, size_t" +Function,+,pb_encode_submessage,_Bool,"pb_ostream_t*, const pb_msgdesc_t*, const void*" +Function,+,pb_encode_svarint,_Bool,"pb_ostream_t*, int64_t" +Function,+,pb_encode_tag,_Bool,"pb_ostream_t*, pb_wire_type_t, uint32_t" +Function,+,pb_encode_tag_for_field,_Bool,"pb_ostream_t*, const pb_field_iter_t*" +Function,+,pb_encode_varint,_Bool,"pb_ostream_t*, uint64_t" +Function,+,pb_get_encoded_size,_Bool,"size_t*, const pb_msgdesc_t*, const void*" +Function,+,pb_istream_from_buffer,pb_istream_t,"const pb_byte_t*, size_t" +Function,+,pb_make_string_substream,_Bool,"pb_istream_t*, pb_istream_t*" +Function,+,pb_ostream_from_buffer,pb_ostream_t,"pb_byte_t*, size_t" +Function,+,pb_read,_Bool,"pb_istream_t*, pb_byte_t*, size_t" +Function,+,pb_release,void,"const pb_msgdesc_t*, void*" +Function,+,pb_skip_field,_Bool,"pb_istream_t*, pb_wire_type_t" +Function,+,pb_write,_Bool,"pb_ostream_t*, const pb_byte_t*, size_t" Function,-,pclose,int,FILE* Function,-,perror,void,const char* -Function,-,platformDisableIrqCallback,void, -Function,-,platformEnableIrqCallback,void, -Function,-,platformProtectST25RComm,void, -Function,-,platformSetIrqCallback,void,PlatformIrqCallback -Function,-,platformSpiTxRx,_Bool,"const uint8_t*, uint8_t*, uint16_t" -Function,-,platformUnprotectST25RComm,void, Function,+,plugin_manager_alloc,PluginManager*,"const char*, uint32_t, const ElfApiInterface*" Function,+,plugin_manager_free,void,PluginManager* Function,+,plugin_manager_get,const FlipperAppPluginDescriptor*,"PluginManager*, uint32_t" @@ -2293,7 +2457,6 @@ Function,+,powf,float,"float, float" Function,-,powl,long double,"long double, long double" Function,+,pretty_format_bytes_hex_canonical,void,"FuriString*, size_t, const char*, const uint8_t*, size_t" Function,-,printf,int,"const char*, ..." -Function,-,prng_successor,uint32_t,"uint32_t, uint32_t" Function,+,property_value_out,void,"PropertyValueContext*, const char*, unsigned int, ..." Function,+,protocol_dict_alloc,ProtocolDict*,"const ProtocolBase**, size_t" Function,+,protocol_dict_decoders_feed,ProtocolId,"ProtocolDict*, _Bool, uint32_t" @@ -2332,12 +2495,6 @@ Function,-,putchar_unlocked,int,int Function,-,putenv,int,char* Function,-,puts,int,const char* Function,-,putw,int,"int, FILE*" -Function,-,pvPortCalloc,void*,"size_t, size_t" -Function,-,pvPortMalloc,void*,size_t -Function,-,pvTaskGetThreadLocalStoragePointer,void*,"TaskHandle_t, BaseType_t" -Function,-,pvTaskIncrementMutexHeldCount,TaskHandle_t, -Function,-,pvTimerGetTimerID,void*,const TimerHandle_t -Function,-,pxPortInitialiseStack,StackType_t*,"StackType_t*, TaskFunction_t, void*" Function,-,qsort,void,"void*, size_t, size_t, __compar_fn_t" Function,-,qsort_r,void,"void*, size_t, size_t, int (*)(const void*, const void*, void*), void*" Function,-,quick_exit,void,int @@ -2359,178 +2516,6 @@ Function,-,remquol,long double,"long double, long double, int*" Function,-,rename,int,"const char*, const char*" Function,-,renameat,int,"int, const char*, int, const char*" Function,-,rewind,void,FILE* -Function,-,rfalAdjustRegulators,ReturnCode,uint16_t* -Function,-,rfalCalibrate,ReturnCode, -Function,-,rfalDeinitialize,ReturnCode, -Function,-,rfalDisableObsvMode,void, -Function,-,rfalFeliCaPoll,ReturnCode,"rfalFeliCaPollSlots, uint16_t, uint8_t, rfalFeliCaPollRes*, uint8_t, uint8_t*, uint8_t*" -Function,-,rfalFieldOff,ReturnCode, -Function,+,rfalFieldOnAndStartGT,ReturnCode, -Function,-,rfalGetBitRate,ReturnCode,"rfalBitRate*, rfalBitRate*" -Function,-,rfalGetErrorHandling,rfalEHandling, -Function,-,rfalGetFDTListen,uint32_t, -Function,-,rfalGetFDTPoll,uint32_t, -Function,-,rfalGetGT,uint32_t, -Function,-,rfalGetMode,rfalMode, -Function,-,rfalGetObsvMode,void,"uint8_t*, uint8_t*" -Function,-,rfalGetTransceiveRSSI,ReturnCode,uint16_t* -Function,-,rfalGetTransceiveState,rfalTransceiveState, -Function,-,rfalGetTransceiveStatus,ReturnCode, -Function,-,rfalISO14443ATransceiveAnticollisionFrame,ReturnCode,"uint8_t*, uint8_t*, uint8_t*, uint16_t*, uint32_t" -Function,-,rfalISO14443ATransceiveShortFrame,ReturnCode,"rfal14443AShortFrameCmd, uint8_t*, uint8_t, uint16_t*, uint32_t" -Function,-,rfalISO15693TransceiveAnticollisionFrame,ReturnCode,"uint8_t*, uint8_t, uint8_t*, uint8_t, uint16_t*" -Function,-,rfalISO15693TransceiveEOF,ReturnCode,"uint8_t*, uint8_t, uint16_t*" -Function,-,rfalISO15693TransceiveEOFAnticollision,ReturnCode,"uint8_t*, uint8_t, uint16_t*" -Function,-,rfalInitialize,ReturnCode, -Function,-,rfalIsExtFieldOn,_Bool, -Function,-,rfalIsGTExpired,_Bool, -Function,-,rfalIsTransceiveInRx,_Bool, -Function,-,rfalIsTransceiveInTx,_Bool, -Function,-,rfalIsoDepATTRIB,ReturnCode,"const uint8_t*, uint8_t, rfalBitRate, rfalBitRate, rfalIsoDepFSxI, uint8_t, uint8_t, const uint8_t*, uint8_t, uint32_t, rfalIsoDepAttribRes*, uint8_t*" -Function,-,rfalIsoDepDeselect,ReturnCode, -Function,-,rfalIsoDepFSxI2FSx,uint16_t,uint8_t -Function,-,rfalIsoDepFWI2FWT,uint32_t,uint8_t -Function,-,rfalIsoDepGetApduTransceiveStatus,ReturnCode, -Function,-,rfalIsoDepGetMaxInfLen,uint16_t, -Function,-,rfalIsoDepGetTransceiveStatus,ReturnCode, -Function,-,rfalIsoDepInitialize,void, -Function,-,rfalIsoDepInitializeWithParams,void,"rfalComplianceMode, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t" -Function,-,rfalIsoDepIsAttrib,_Bool,"const uint8_t*, uint8_t" -Function,-,rfalIsoDepIsRats,_Bool,"const uint8_t*, uint8_t" -Function,-,rfalIsoDepListenGetActivationStatus,ReturnCode, -Function,-,rfalIsoDepListenStartActivation,ReturnCode,"rfalIsoDepAtsParam*, const rfalIsoDepAttribResParam*, const uint8_t*, uint16_t, rfalIsoDepListenActvParam" -Function,-,rfalIsoDepPPS,ReturnCode,"uint8_t, rfalBitRate, rfalBitRate, rfalIsoDepPpsRes*" -Function,-,rfalIsoDepPollAGetActivationStatus,ReturnCode, -Function,-,rfalIsoDepPollAHandleActivation,ReturnCode,"rfalIsoDepFSxI, uint8_t, rfalBitRate, rfalIsoDepDevice*" -Function,-,rfalIsoDepPollAStartActivation,ReturnCode,"rfalIsoDepFSxI, uint8_t, rfalBitRate, rfalIsoDepDevice*" -Function,-,rfalIsoDepPollBGetActivationStatus,ReturnCode, -Function,-,rfalIsoDepPollBHandleActivation,ReturnCode,"rfalIsoDepFSxI, uint8_t, rfalBitRate, uint8_t, const rfalNfcbListenDevice*, const uint8_t*, uint8_t, rfalIsoDepDevice*" -Function,-,rfalIsoDepPollBStartActivation,ReturnCode,"rfalIsoDepFSxI, uint8_t, rfalBitRate, uint8_t, const rfalNfcbListenDevice*, const uint8_t*, uint8_t, rfalIsoDepDevice*" -Function,-,rfalIsoDepPollHandleSParameters,ReturnCode,"rfalIsoDepDevice*, rfalBitRate, rfalBitRate" -Function,-,rfalIsoDepRATS,ReturnCode,"rfalIsoDepFSxI, uint8_t, rfalIsoDepAts*, uint8_t*" -Function,-,rfalIsoDepStartApduTransceive,ReturnCode,rfalIsoDepApduTxRxParam -Function,-,rfalIsoDepStartTransceive,ReturnCode,rfalIsoDepTxRxParam -Function,-,rfalListenGetState,rfalLmState,"_Bool*, rfalBitRate*" -Function,-,rfalListenSetState,ReturnCode,rfalLmState -Function,-,rfalListenSleepStart,ReturnCode,"rfalLmState, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalListenStart,ReturnCode,"uint32_t, const rfalLmConfPA*, const rfalLmConfPB*, const rfalLmConfPF*, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalListenStop,ReturnCode, -Function,+,rfalLowPowerModeStart,ReturnCode, -Function,+,rfalLowPowerModeStop,ReturnCode, -Function,-,rfalNfcDataExchangeCustomStart,ReturnCode,"uint8_t*, uint16_t, uint8_t**, uint16_t**, uint32_t, uint32_t" -Function,-,rfalNfcDataExchangeGetStatus,ReturnCode, -Function,-,rfalNfcDataExchangeStart,ReturnCode,"uint8_t*, uint16_t, uint8_t**, uint16_t**, uint32_t, uint32_t" -Function,-,rfalNfcDeactivate,ReturnCode,_Bool -Function,-,rfalNfcDepATR,ReturnCode,"const rfalNfcDepAtrParam*, rfalNfcDepAtrRes*, uint8_t*" -Function,-,rfalNfcDepCalculateRWT,uint32_t,uint8_t -Function,-,rfalNfcDepDSL,ReturnCode, -Function,-,rfalNfcDepGetPduTransceiveStatus,ReturnCode, -Function,-,rfalNfcDepGetTransceiveStatus,ReturnCode, -Function,-,rfalNfcDepInitialize,void, -Function,-,rfalNfcDepInitiatorHandleActivation,ReturnCode,"rfalNfcDepAtrParam*, rfalBitRate, rfalNfcDepDevice*" -Function,-,rfalNfcDepIsAtrReq,_Bool,"const uint8_t*, uint16_t, uint8_t*" -Function,-,rfalNfcDepListenGetActivationStatus,ReturnCode, -Function,-,rfalNfcDepListenStartActivation,ReturnCode,"const rfalNfcDepTargetParam*, const uint8_t*, uint16_t, rfalNfcDepListenActvParam" -Function,-,rfalNfcDepPSL,ReturnCode,"uint8_t, uint8_t" -Function,-,rfalNfcDepRLS,ReturnCode, -Function,-,rfalNfcDepSetDeactivatingCallback,void,rfalNfcDepDeactCallback -Function,-,rfalNfcDepStartPduTransceive,ReturnCode,rfalNfcDepPduTxRxParam -Function,-,rfalNfcDepStartTransceive,ReturnCode,const rfalNfcDepTxRxParam* -Function,-,rfalNfcDepTargetRcvdATR,_Bool, -Function,-,rfalNfcDiscover,ReturnCode,const rfalNfcDiscoverParam* -Function,-,rfalNfcGetActiveDevice,ReturnCode,rfalNfcDevice** -Function,-,rfalNfcGetDevicesFound,ReturnCode,"rfalNfcDevice**, uint8_t*" -Function,-,rfalNfcGetState,rfalNfcState, -Function,-,rfalNfcInitialize,ReturnCode, -Function,-,rfalNfcSelect,ReturnCode,uint8_t -Function,-,rfalNfcWorker,void, -Function,-,rfalNfcaListenerIsSleepReq,_Bool,"const uint8_t*, uint16_t" -Function,-,rfalNfcaPollerCheckPresence,ReturnCode,"rfal14443AShortFrameCmd, rfalNfcaSensRes*" -Function,-,rfalNfcaPollerFullCollisionResolution,ReturnCode,"rfalComplianceMode, uint8_t, rfalNfcaListenDevice*, uint8_t*" -Function,-,rfalNfcaPollerGetFullCollisionResolutionStatus,ReturnCode, -Function,-,rfalNfcaPollerInitialize,ReturnCode, -Function,-,rfalNfcaPollerSelect,ReturnCode,"const uint8_t*, uint8_t, rfalNfcaSelRes*" -Function,-,rfalNfcaPollerSingleCollisionResolution,ReturnCode,"uint8_t, _Bool*, rfalNfcaSelRes*, uint8_t*, uint8_t*" -Function,-,rfalNfcaPollerSleep,ReturnCode, -Function,-,rfalNfcaPollerSleepFullCollisionResolution,ReturnCode,"uint8_t, rfalNfcaListenDevice*, uint8_t*" -Function,-,rfalNfcaPollerStartFullCollisionResolution,ReturnCode,"rfalComplianceMode, uint8_t, rfalNfcaListenDevice*, uint8_t*" -Function,-,rfalNfcaPollerTechnologyDetection,ReturnCode,"rfalComplianceMode, rfalNfcaSensRes*" -Function,-,rfalNfcbPollerCheckPresence,ReturnCode,"rfalNfcbSensCmd, rfalNfcbSlots, rfalNfcbSensbRes*, uint8_t*" -Function,-,rfalNfcbPollerCollisionResolution,ReturnCode,"rfalComplianceMode, uint8_t, rfalNfcbListenDevice*, uint8_t*" -Function,-,rfalNfcbPollerInitialize,ReturnCode, -Function,-,rfalNfcbPollerInitializeWithParams,ReturnCode,"uint8_t, uint8_t" -Function,-,rfalNfcbPollerSleep,ReturnCode,const uint8_t* -Function,-,rfalNfcbPollerSlotMarker,ReturnCode,"uint8_t, rfalNfcbSensbRes*, uint8_t*" -Function,-,rfalNfcbPollerSlottedCollisionResolution,ReturnCode,"rfalComplianceMode, uint8_t, rfalNfcbSlots, rfalNfcbSlots, rfalNfcbListenDevice*, uint8_t*, _Bool*" -Function,-,rfalNfcbPollerTechnologyDetection,ReturnCode,"rfalComplianceMode, rfalNfcbSensbRes*, uint8_t*" -Function,-,rfalNfcbTR2ToFDT,uint32_t,uint8_t -Function,-,rfalNfcfListenerIsT3TReq,_Bool,"const uint8_t*, uint16_t, uint8_t*" -Function,-,rfalNfcfPollerCheck,ReturnCode,"const uint8_t*, const rfalNfcfServBlockListParam*, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalNfcfPollerCheckPresence,ReturnCode, -Function,-,rfalNfcfPollerCollisionResolution,ReturnCode,"rfalComplianceMode, uint8_t, rfalNfcfListenDevice*, uint8_t*" -Function,-,rfalNfcfPollerInitialize,ReturnCode,rfalBitRate -Function,-,rfalNfcfPollerPoll,ReturnCode,"rfalFeliCaPollSlots, uint16_t, uint8_t, rfalFeliCaPollRes*, uint8_t*, uint8_t*" -Function,-,rfalNfcfPollerUpdate,ReturnCode,"const uint8_t*, const rfalNfcfServBlockListParam*, uint8_t*, uint16_t, const uint8_t*, uint8_t*, uint16_t" -Function,-,rfalNfcvPollerCheckPresence,ReturnCode,rfalNfcvInventoryRes* -Function,-,rfalNfcvPollerCollisionResolution,ReturnCode,"rfalComplianceMode, uint8_t, rfalNfcvListenDevice*, uint8_t*" -Function,-,rfalNfcvPollerExtendedGetSystemInformation,ReturnCode,"uint8_t, const uint8_t*, uint8_t, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalNfcvPollerExtendedLockSingleBlock,ReturnCode,"uint8_t, const uint8_t*, uint16_t" -Function,-,rfalNfcvPollerExtendedReadMultipleBlocks,ReturnCode,"uint8_t, const uint8_t*, uint16_t, uint16_t, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalNfcvPollerExtendedReadSingleBlock,ReturnCode,"uint8_t, const uint8_t*, uint16_t, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalNfcvPollerExtendedWriteMultipleBlocks,ReturnCode,"uint8_t, const uint8_t*, uint16_t, uint16_t, uint8_t*, uint16_t, uint8_t, const uint8_t*, uint16_t" -Function,-,rfalNfcvPollerExtendedWriteSingleBlock,ReturnCode,"uint8_t, const uint8_t*, uint16_t, const uint8_t*, uint8_t" -Function,-,rfalNfcvPollerGetSystemInformation,ReturnCode,"uint8_t, const uint8_t*, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalNfcvPollerInitialize,ReturnCode, -Function,-,rfalNfcvPollerInventory,ReturnCode,"rfalNfcvNumSlots, uint8_t, const uint8_t*, rfalNfcvInventoryRes*, uint16_t*" -Function,-,rfalNfcvPollerLockBlock,ReturnCode,"uint8_t, const uint8_t*, uint8_t" -Function,-,rfalNfcvPollerReadMultipleBlocks,ReturnCode,"uint8_t, const uint8_t*, uint8_t, uint8_t, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalNfcvPollerReadSingleBlock,ReturnCode,"uint8_t, const uint8_t*, uint8_t, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalNfcvPollerSelect,ReturnCode,"uint8_t, const uint8_t*" -Function,-,rfalNfcvPollerSleep,ReturnCode,"uint8_t, const uint8_t*" -Function,-,rfalNfcvPollerSleepCollisionResolution,ReturnCode,"uint8_t, rfalNfcvListenDevice*, uint8_t*" -Function,-,rfalNfcvPollerTransceiveReq,ReturnCode,"uint8_t, uint8_t, uint8_t, const uint8_t*, const uint8_t*, uint16_t, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalNfcvPollerWriteMultipleBlocks,ReturnCode,"uint8_t, const uint8_t*, uint8_t, uint8_t, uint8_t*, uint16_t, uint8_t, const uint8_t*, uint16_t" -Function,-,rfalNfcvPollerWriteSingleBlock,ReturnCode,"uint8_t, const uint8_t*, uint8_t, const uint8_t*, uint8_t" -Function,-,rfalSetBitRate,ReturnCode,"rfalBitRate, rfalBitRate" -Function,-,rfalSetErrorHandling,void,rfalEHandling -Function,-,rfalSetFDTListen,void,uint32_t -Function,-,rfalSetFDTPoll,void,uint32_t -Function,-,rfalSetGT,void,uint32_t -Function,-,rfalSetMode,ReturnCode,"rfalMode, rfalBitRate, rfalBitRate" -Function,-,rfalSetObsvMode,void,"uint8_t, uint8_t" -Function,-,rfalSetPostTxRxCallback,void,rfalPostTxRxCallback -Function,-,rfalSetPreTxRxCallback,void,rfalPreTxRxCallback -Function,-,rfalSetUpperLayerCallback,void,rfalUpperLayerCallback -Function,-,rfalSt25tbPollerCheckPresence,ReturnCode,uint8_t* -Function,-,rfalSt25tbPollerCollisionResolution,ReturnCode,"uint8_t, rfalSt25tbListenDevice*, uint8_t*" -Function,-,rfalSt25tbPollerCompletion,ReturnCode, -Function,-,rfalSt25tbPollerGetUID,ReturnCode,rfalSt25tbUID* -Function,-,rfalSt25tbPollerInitialize,ReturnCode, -Function,-,rfalSt25tbPollerInitiate,ReturnCode,uint8_t* -Function,-,rfalSt25tbPollerPcall,ReturnCode,uint8_t* -Function,-,rfalSt25tbPollerReadBlock,ReturnCode,"uint8_t, rfalSt25tbBlock*" -Function,-,rfalSt25tbPollerResetToInventory,ReturnCode, -Function,-,rfalSt25tbPollerSelect,ReturnCode,uint8_t -Function,-,rfalSt25tbPollerSlotMarker,ReturnCode,"uint8_t, uint8_t*" -Function,-,rfalSt25tbPollerWriteBlock,ReturnCode,"uint8_t, const rfalSt25tbBlock*" -Function,-,rfalStartTransceive,ReturnCode,const rfalTransceiveContext* -Function,-,rfalT1TPollerInitialize,ReturnCode, -Function,-,rfalT1TPollerRall,ReturnCode,"const uint8_t*, uint8_t*, uint16_t, uint16_t*" -Function,-,rfalT1TPollerRid,ReturnCode,rfalT1TRidRes* -Function,-,rfalT1TPollerWrite,ReturnCode,"const uint8_t*, uint8_t, uint8_t" -Function,-,rfalTransceiveBitsBlockingTx,ReturnCode,"uint8_t*, uint16_t, uint8_t*, uint16_t, uint16_t*, uint32_t, uint32_t" -Function,-,rfalTransceiveBitsBlockingTxRx,ReturnCode,"uint8_t*, uint16_t, uint8_t*, uint16_t, uint16_t*, uint32_t, uint32_t" -Function,-,rfalTransceiveBlockingRx,ReturnCode, -Function,-,rfalTransceiveBlockingTx,ReturnCode,"uint8_t*, uint16_t, uint8_t*, uint16_t, uint16_t*, uint32_t, uint32_t" -Function,-,rfalTransceiveBlockingTxRx,ReturnCode,"uint8_t*, uint16_t, uint8_t*, uint16_t, uint16_t*, uint32_t, uint32_t" -Function,-,rfalWakeUpModeHasWoke,_Bool, -Function,-,rfalWakeUpModeStart,ReturnCode,const rfalWakeUpConfig* -Function,-,rfalWakeUpModeStop,ReturnCode, -Function,+,rfalWorker,void, -Function,-,rfal_platform_spi_acquire,void, -Function,-,rfal_platform_spi_release,void, -Function,-,rfal_set_callback_context,void,void* -Function,-,rfal_set_state_changed_callback,void,RfalStateChangedCallback Function,-,rindex,char*,"const char*, int" Function,-,rint,double,double Function,-,rintf,float,float @@ -2539,7 +2524,7 @@ Function,-,round,double,double Function,+,roundf,float,float Function,-,roundl,long double,long double Function,+,rpc_session_close,void,RpcSession* -Function,+,rpc_session_feed,size_t,"RpcSession*, uint8_t*, size_t, TickType_t" +Function,+,rpc_session_feed,size_t,"RpcSession*, uint8_t*, size_t, uint32_t" Function,+,rpc_session_get_available_size,size_t,RpcSession* Function,+,rpc_session_get_owner,RpcOwner,RpcSession* Function,+,rpc_session_open,RpcSession*,"Rpc*, RpcOwner" @@ -2548,14 +2533,12 @@ Function,+,rpc_session_set_close_callback,void,"RpcSession*, RpcSessionClosedCal Function,+,rpc_session_set_context,void,"RpcSession*, void*" Function,+,rpc_session_set_send_bytes_callback,void,"RpcSession*, RpcSendBytesCallback" Function,+,rpc_session_set_terminated_callback,void,"RpcSession*, RpcSessionTerminatedCallback" -Function,+,rpc_system_app_confirm,void,"RpcAppSystem*, RpcAppSystemEvent, _Bool" +Function,+,rpc_system_app_confirm,void,"RpcAppSystem*, _Bool" Function,+,rpc_system_app_error_reset,void,RpcAppSystem* Function,+,rpc_system_app_exchange_data,void,"RpcAppSystem*, const uint8_t*, size_t" -Function,+,rpc_system_app_get_data,const char*,RpcAppSystem* Function,+,rpc_system_app_send_exited,void,RpcAppSystem* Function,+,rpc_system_app_send_started,void,RpcAppSystem* Function,+,rpc_system_app_set_callback,void,"RpcAppSystem*, RpcAppSystemCallback, void*" -Function,+,rpc_system_app_set_data_exchange_callback,void,"RpcAppSystem*, RpcAppSystemDataExchangeCallback, void*" Function,+,rpc_system_app_set_error_code,void,"RpcAppSystem*, uint32_t" Function,+,rpc_system_app_set_error_text,void,"RpcAppSystem*, const char*" Function,-,rpmatch,int,const char* @@ -2606,6 +2589,25 @@ Function,+,sha256_finish,void,"sha256_context*, unsigned char[32]" Function,+,sha256_process,void,sha256_context* Function,+,sha256_start,void,sha256_context* Function,+,sha256_update,void,"sha256_context*, const unsigned char*, unsigned int" +Function,+,signal_reader_alloc,SignalReader*,"const GpioPin*, uint32_t" +Function,+,signal_reader_free,void,SignalReader* +Function,+,signal_reader_set_polarity,void,"SignalReader*, SignalReaderPolarity" +Function,+,signal_reader_set_pull,void,"SignalReader*, GpioPull" +Function,+,signal_reader_set_sample_rate,void,"SignalReader*, SignalReaderTimeUnit, uint32_t" +Function,+,signal_reader_set_trigger,void,"SignalReader*, SignalReaderTrigger" +Function,+,signal_reader_start,void,"SignalReader*, SignalReaderCallback, void*" +Function,+,signal_reader_stop,void,SignalReader* +Function,+,simple_array_alloc,SimpleArray*,const SimpleArrayConfig* +Function,+,simple_array_cget,const SimpleArrayElement*,"const SimpleArray*, uint32_t" +Function,+,simple_array_cget_data,const SimpleArrayData*,const SimpleArray* +Function,+,simple_array_copy,void,"SimpleArray*, const SimpleArray*" +Function,+,simple_array_free,void,SimpleArray* +Function,+,simple_array_get,SimpleArrayElement*,"SimpleArray*, uint32_t" +Function,+,simple_array_get_count,uint32_t,const SimpleArray* +Function,+,simple_array_get_data,SimpleArrayData*,SimpleArray* +Function,+,simple_array_init,void,"SimpleArray*, uint32_t" +Function,+,simple_array_is_equal,_Bool,"const SimpleArray*, const SimpleArray*" +Function,+,simple_array_reset,void,SimpleArray* Function,-,sin,double,double Function,-,sincos,void,"double, double*, double*" Function,-,sincosf,void,"float, float*, float*" @@ -2616,6 +2618,26 @@ Function,-,sinhl,long double,long double Function,-,sinl,long double,long double Function,-,siprintf,int,"char*, const char*, ..." Function,-,siscanf,int,"const char*, const char*, ..." +Function,+,slix_alloc,SlixData*, +Function,+,slix_copy,void,"SlixData*, const SlixData*" +Function,+,slix_free,void,SlixData* +Function,+,slix_get_base_data,const Iso15693_3Data*,const SlixData* +Function,+,slix_get_counter,uint16_t,const SlixData* +Function,+,slix_get_device_name,const char*,"const SlixData*, NfcDeviceNameType" +Function,+,slix_get_password,SlixPassword,"const SlixData*, SlixPasswordType" +Function,+,slix_get_type,SlixType,const SlixData* +Function,+,slix_get_uid,const uint8_t*,"const SlixData*, size_t*" +Function,+,slix_is_block_protected,_Bool,"const SlixData*, SlixPasswordType, uint8_t" +Function,+,slix_is_counter_increment_protected,_Bool,const SlixData* +Function,+,slix_is_equal,_Bool,"const SlixData*, const SlixData*" +Function,+,slix_is_privacy_mode,_Bool,const SlixData* +Function,+,slix_load,_Bool,"SlixData*, FlipperFormat*, uint32_t" +Function,+,slix_reset,void,SlixData* +Function,+,slix_save,_Bool,"const SlixData*, FlipperFormat*" +Function,+,slix_set_uid,_Bool,"SlixData*, const uint8_t*, size_t" +Function,+,slix_type_has_features,_Bool,"SlixType, SlixTypeFeatures" +Function,+,slix_type_supports_password,_Bool,"SlixType, SlixPasswordType" +Function,+,slix_verify,_Bool,"SlixData*, const FuriString*" Function,-,sniprintf,int,"char*, size_t, const char*, ..." Function,+,snprintf,int,"char*, size_t, const char*, ..." Function,-,sprintf,int,"char*, const char*, ..." @@ -2626,6 +2648,19 @@ Function,+,srand,void,unsigned Function,-,srand48,void,long Function,-,srandom,void,unsigned Function,+,sscanf,int,"const char*, const char*, ..." +Function,+,st25tb_alloc,St25tbData*, +Function,+,st25tb_copy,void,"St25tbData*, const St25tbData*" +Function,+,st25tb_free,void,St25tbData* +Function,+,st25tb_get_base_data,St25tbData*,const St25tbData* +Function,+,st25tb_get_block_count,uint8_t,St25tbType +Function,+,st25tb_get_device_name,const char*,"const St25tbData*, NfcDeviceNameType" +Function,+,st25tb_get_uid,const uint8_t*,"const St25tbData*, size_t*" +Function,+,st25tb_is_equal,_Bool,"const St25tbData*, const St25tbData*" +Function,+,st25tb_load,_Bool,"St25tbData*, FlipperFormat*, uint32_t" +Function,+,st25tb_reset,void,St25tbData* +Function,+,st25tb_save,_Bool,"const St25tbData*, FlipperFormat*" +Function,+,st25tb_set_uid,_Bool,"St25tbData*, const uint8_t*, size_t" +Function,+,st25tb_verify,_Bool,"St25tbData*, const FuriString*" Function,+,storage_common_copy,FS_Error,"Storage*, const char*, const char*" Function,+,storage_common_exists,_Bool,"Storage*, const char*" Function,+,storage_common_fs_info,FS_Error,"Storage*, const char*, uint64_t*, uint64_t*" @@ -2769,7 +2804,6 @@ Function,-,strupr,char*,char* Function,-,strverscmp,int,"const char*, const char*" Function,-,strxfrm,size_t,"char*, const char*, size_t" Function,-,strxfrm_l,size_t,"char*, const char*, size_t, locale_t" -Function,-,stub_parser_verify_read,_Bool,"NfcWorker*, FuriHalNfcTxRxContext*" Function,+,subghz_block_generic_deserialize,SubGhzProtocolStatus,"SubGhzBlockGeneric*, FlipperFormat*" Function,+,subghz_block_generic_deserialize_check_count_bit,SubGhzProtocolStatus,"SubGhzBlockGeneric*, FlipperFormat*, uint16_t" Function,+,subghz_block_generic_get_preset_name,void,"const char*, FuriString*" @@ -2895,7 +2929,9 @@ Function,+,subghz_protocol_registry_get_by_index,const SubGhzProtocol*,"const Su Function,+,subghz_protocol_registry_get_by_name,const SubGhzProtocol*,"const SubGhzProtocolRegistry*, const char*" Function,+,subghz_protocol_secplus_v1_check_fixed,_Bool,uint32_t Function,+,subghz_protocol_secplus_v2_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint32_t, SubGhzRadioPreset*" +Function,+,subghz_protocol_somfy_keytis_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, SubGhzRadioPreset*" Function,+,subghz_protocol_somfy_telis_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, SubGhzRadioPreset*" +Function,+,subghz_protocol_star_line_create_data,_Bool,"void*, FlipperFormat*, uint32_t, uint8_t, uint16_t, const char*, SubGhzRadioPreset*" Function,+,subghz_receiver_alloc_init,SubGhzReceiver*,SubGhzEnvironment* Function,+,subghz_receiver_decode,void,"SubGhzReceiver*, _Bool, uint32_t" Function,+,subghz_receiver_free,void,SubGhzReceiver* @@ -3002,11 +3038,6 @@ Function,-,tgamma,double,double Function,-,tgammaf,float,float Function,-,tgammal,long double,long double Function,-,time,time_t,time_t* -Function,+,timerCalculateTimer,uint32_t,uint16_t -Function,-,timerDelay,void,uint16_t -Function,+,timerIsExpired,_Bool,uint32_t -Function,-,timerStopwatchMeasure,uint32_t, -Function,-,timerStopwatchStart,void, Function,-,timingsafe_bcmp,int,"const void*, const void*, size_t" Function,-,timingsafe_memcmp,int,"const void*, const void*, size_t" Function,-,tmpfile,FILE*, @@ -3040,67 +3071,10 @@ Function,-,uECC_sign_deterministic,int,"const uint8_t*, const uint8_t*, unsigned Function,-,uECC_valid_public_key,int,"const uint8_t*, uECC_Curve" Function,-,uECC_verify,int,"const uint8_t*, const uint8_t*, unsigned, const uint8_t*, uECC_Curve" Function,+,uint8_to_hex_chars,void,"const uint8_t*, uint8_t*, int" -Function,-,ulTaskGenericNotifyTake,uint32_t,"UBaseType_t, BaseType_t, TickType_t" -Function,-,ulTaskGenericNotifyValueClear,uint32_t,"TaskHandle_t, UBaseType_t, uint32_t" -Function,-,ulTaskGetIdleRunTimeCounter,uint32_t, -Function,-,ulTaskGetIdleRunTimePercent,uint32_t, Function,-,ungetc,int,"int, FILE*" Function,-,unsetenv,int,const char* Function,-,usbd_poll,void,usbd_device* Function,-,utoa,char*,"unsigned, char*, int" -Function,-,uxListRemove,UBaseType_t,ListItem_t* -Function,-,uxTaskGetNumberOfTasks,UBaseType_t, -Function,-,uxTaskGetStackHighWaterMark,UBaseType_t,TaskHandle_t -Function,-,uxTaskGetStackHighWaterMark2,uint16_t,TaskHandle_t -Function,-,uxTaskGetSystemState,UBaseType_t,"TaskStatus_t*, const UBaseType_t, uint32_t*" -Function,-,uxTaskGetTaskNumber,UBaseType_t,TaskHandle_t -Function,-,uxTaskPriorityGet,UBaseType_t,const TaskHandle_t -Function,-,uxTaskPriorityGetFromISR,UBaseType_t,const TaskHandle_t -Function,-,uxTaskResetEventItemValue,TickType_t, -Function,-,uxTimerGetReloadMode,UBaseType_t,TimerHandle_t -Function,-,uxTimerGetTimerNumber,UBaseType_t,TimerHandle_t -Function,-,vApplicationGetIdleTaskMemory,void,"StaticTask_t**, StackType_t**, uint32_t*" -Function,-,vApplicationGetTimerTaskMemory,void,"StaticTask_t**, StackType_t**, uint32_t*" -Function,-,vListInitialise,void,List_t* -Function,-,vListInitialiseItem,void,ListItem_t* -Function,-,vListInsert,void,"List_t*, ListItem_t*" -Function,-,vListInsertEnd,void,"List_t*, ListItem_t*" -Function,-,vPortDefineHeapRegions,void,const HeapRegion_t* -Function,-,vPortEndScheduler,void, -Function,+,vPortEnterCritical,void, -Function,+,vPortExitCritical,void, -Function,-,vPortFree,void,void* -Function,-,vPortGetHeapStats,void,HeapStats_t* -Function,-,vPortInitialiseBlocks,void, -Function,-,vPortSuppressTicksAndSleep,void,TickType_t -Function,-,vTaskAllocateMPURegions,void,"TaskHandle_t, const MemoryRegion_t*" -Function,-,vTaskDelay,void,const TickType_t -Function,-,vTaskDelete,void,TaskHandle_t -Function,-,vTaskEndScheduler,void, -Function,-,vTaskGenericNotifyGiveFromISR,void,"TaskHandle_t, UBaseType_t, BaseType_t*" -Function,-,vTaskGetInfo,void,"TaskHandle_t, TaskStatus_t*, BaseType_t, eTaskState" -Function,-,vTaskGetRunTimeStats,void,char* -Function,-,vTaskInternalSetTimeOutState,void,TimeOut_t* -Function,-,vTaskList,void,char* -Function,-,vTaskMissedYield,void, -Function,-,vTaskPlaceOnEventList,void,"List_t*, const TickType_t" -Function,-,vTaskPlaceOnEventListRestricted,void,"List_t*, TickType_t, const BaseType_t" -Function,-,vTaskPlaceOnUnorderedEventList,void,"List_t*, const TickType_t, const TickType_t" -Function,-,vTaskPriorityDisinheritAfterTimeout,void,"const TaskHandle_t, UBaseType_t" -Function,+,vTaskPrioritySet,void,"TaskHandle_t, UBaseType_t" -Function,-,vTaskRemoveFromUnorderedEventList,void,"ListItem_t*, const TickType_t" -Function,-,vTaskResume,void,TaskHandle_t -Function,-,vTaskSetTaskNumber,void,"TaskHandle_t, const UBaseType_t" -Function,-,vTaskSetThreadLocalStoragePointer,void,"TaskHandle_t, BaseType_t, void*" -Function,-,vTaskSetTimeOutState,void,TimeOut_t* -Function,-,vTaskStartScheduler,void, -Function,-,vTaskStepTick,void,TickType_t -Function,-,vTaskSuspend,void,TaskHandle_t -Function,-,vTaskSuspendAll,void, -Function,-,vTaskSwitchContext,void, -Function,-,vTimerSetReloadMode,void,"TimerHandle_t, const BaseType_t" -Function,-,vTimerSetTimerID,void,"TimerHandle_t, void*" -Function,-,vTimerSetTimerNumber,void,"TimerHandle_t, UBaseType_t" Function,+,validator_is_file_alloc_init,ValidatorIsFile*,"const char*, const char*, const char*" Function,+,validator_is_file_callback,_Bool,"const char*, FuriString*, void*" Function,+,validator_is_file_free,void,ValidatorIsFile* @@ -3218,43 +3192,6 @@ Function,+,widget_alloc,Widget*, Function,+,widget_free,void,Widget* Function,+,widget_get_view,View*,Widget* Function,+,widget_reset,void,Widget* -Function,-,xPortGetFreeHeapSize,size_t, -Function,-,xPortGetMinimumEverFreeHeapSize,size_t, -Function,-,xPortStartScheduler,BaseType_t, -Function,-,xTaskAbortDelay,BaseType_t,TaskHandle_t -Function,-,xTaskCallApplicationTaskHook,BaseType_t,"TaskHandle_t, void*" -Function,-,xTaskCatchUpTicks,BaseType_t,TickType_t -Function,-,xTaskCheckForTimeOut,BaseType_t,"TimeOut_t*, TickType_t*" -Function,-,xTaskCreate,BaseType_t,"TaskFunction_t, const char*, const uint16_t, void*, UBaseType_t, TaskHandle_t*" -Function,-,xTaskCreateStatic,TaskHandle_t,"TaskFunction_t, const char*, const uint32_t, void*, UBaseType_t, StackType_t*, StaticTask_t*" -Function,-,xTaskDelayUntil,BaseType_t,"TickType_t*, const TickType_t" -Function,-,xTaskGenericNotify,BaseType_t,"TaskHandle_t, UBaseType_t, uint32_t, eNotifyAction, uint32_t*" -Function,-,xTaskGenericNotifyFromISR,BaseType_t,"TaskHandle_t, UBaseType_t, uint32_t, eNotifyAction, uint32_t*, BaseType_t*" -Function,-,xTaskGenericNotifyStateClear,BaseType_t,"TaskHandle_t, UBaseType_t" -Function,-,xTaskGenericNotifyWait,BaseType_t,"UBaseType_t, uint32_t, uint32_t, uint32_t*, TickType_t" -Function,-,xTaskGetCurrentTaskHandle,TaskHandle_t, -Function,+,xTaskGetHandle,TaskHandle_t,const char* -Function,-,xTaskGetIdleTaskHandle,TaskHandle_t, -Function,+,xTaskGetSchedulerState,BaseType_t, -Function,+,xTaskGetTickCount,TickType_t, -Function,-,xTaskGetTickCountFromISR,TickType_t, -Function,-,xTaskIncrementTick,BaseType_t, -Function,-,xTaskPriorityDisinherit,BaseType_t,const TaskHandle_t -Function,-,xTaskPriorityInherit,BaseType_t,const TaskHandle_t -Function,-,xTaskRemoveFromEventList,BaseType_t,const List_t* -Function,-,xTaskResumeAll,BaseType_t, -Function,-,xTaskResumeFromISR,BaseType_t,TaskHandle_t -Function,-,xTimerCreate,TimerHandle_t,"const char*, const TickType_t, const BaseType_t, void*, TimerCallbackFunction_t" -Function,-,xTimerCreateStatic,TimerHandle_t,"const char*, const TickType_t, const BaseType_t, void*, TimerCallbackFunction_t, StaticTimer_t*" -Function,-,xTimerCreateTimerTask,BaseType_t, -Function,-,xTimerGenericCommand,BaseType_t,"TimerHandle_t, const BaseType_t, const TickType_t, BaseType_t*, const TickType_t" -Function,-,xTimerGetExpiryTime,TickType_t,TimerHandle_t -Function,-,xTimerGetPeriod,TickType_t,TimerHandle_t -Function,-,xTimerGetReloadMode,BaseType_t,TimerHandle_t -Function,-,xTimerGetTimerDaemonTaskHandle,TaskHandle_t, -Function,-,xTimerIsTimerActive,BaseType_t,TimerHandle_t -Function,-,xTimerPendFunctionCall,BaseType_t,"PendedFunction_t, void*, uint32_t, TickType_t" -Function,-,xTimerPendFunctionCallFromISR,BaseType_t,"PendedFunction_t, void*, uint32_t, BaseType_t*" Function,-,y0,double,double Function,-,y0f,float,float Function,-,y1,double,double @@ -3492,8 +3429,10 @@ Variable,+,message_red_255,const NotificationMessage, Variable,+,message_sound_off,const NotificationMessage, Variable,+,message_vibro_off,const NotificationMessage, Variable,+,message_vibro_on,const NotificationMessage, -Variable,+,nfc_generators,const NfcGenerator*[], -Variable,-,nfc_supported_card,NfcSupportedCard[NfcSupportedCardTypeEnd], +Variable,-,nfc_device_mf_classic,const NfcDeviceBase, +Variable,-,nfc_device_mf_desfire,const NfcDeviceBase, +Variable,-,nfc_device_mf_ultralight,const NfcDeviceBase, +Variable,-,nfc_device_st25tb,const NfcDeviceBase, Variable,+,sequence_audiovisual_alert,const NotificationSequence, Variable,+,sequence_blink_blue_10,const NotificationSequence, Variable,+,sequence_blink_blue_100,const NotificationSequence, @@ -3543,6 +3482,7 @@ Variable,+,sequence_set_vibro_on,const NotificationSequence, Variable,+,sequence_single_vibro,const NotificationSequence, Variable,+,sequence_solid_yellow,const NotificationSequence, Variable,+,sequence_success,const NotificationSequence, +Variable,+,simple_array_config_uint8_t,const SimpleArrayConfig, Variable,-,subghz_device_cc1101_int,const SubGhzDevice, Variable,+,subghz_device_cc1101_preset_2fsk_dev2_38khz_async_regs,const uint8_t[], Variable,+,subghz_device_cc1101_preset_2fsk_dev47_6khz_async_regs,const uint8_t[], diff --git a/firmware/targets/f7/application_ext.ld b/targets/f7/application_ext.ld similarity index 100% rename from firmware/targets/f7/application_ext.ld rename to targets/f7/application_ext.ld diff --git a/firmware/targets/f7/ble_glue/app_common.h b/targets/f7/ble_glue/app_common.h similarity index 100% rename from firmware/targets/f7/ble_glue/app_common.h rename to targets/f7/ble_glue/app_common.h diff --git a/firmware/targets/f7/ble_glue/app_conf.h b/targets/f7/ble_glue/app_conf.h similarity index 100% rename from firmware/targets/f7/ble_glue/app_conf.h rename to targets/f7/ble_glue/app_conf.h diff --git a/firmware/targets/f7/ble_glue/app_debug.c b/targets/f7/ble_glue/app_debug.c similarity index 100% rename from firmware/targets/f7/ble_glue/app_debug.c rename to targets/f7/ble_glue/app_debug.c diff --git a/firmware/targets/f7/ble_glue/app_debug.h b/targets/f7/ble_glue/app_debug.h similarity index 100% rename from firmware/targets/f7/ble_glue/app_debug.h rename to targets/f7/ble_glue/app_debug.h diff --git a/firmware/targets/f7/ble_glue/ble_app.c b/targets/f7/ble_glue/ble_app.c similarity index 100% rename from firmware/targets/f7/ble_glue/ble_app.c rename to targets/f7/ble_glue/ble_app.c diff --git a/firmware/targets/f7/ble_glue/ble_app.h b/targets/f7/ble_glue/ble_app.h similarity index 100% rename from firmware/targets/f7/ble_glue/ble_app.h rename to targets/f7/ble_glue/ble_app.h diff --git a/firmware/targets/f7/ble_glue/ble_conf.h b/targets/f7/ble_glue/ble_conf.h similarity index 100% rename from firmware/targets/f7/ble_glue/ble_conf.h rename to targets/f7/ble_glue/ble_conf.h diff --git a/firmware/targets/f7/ble_glue/ble_const.h b/targets/f7/ble_glue/ble_const.h similarity index 100% rename from firmware/targets/f7/ble_glue/ble_const.h rename to targets/f7/ble_glue/ble_const.h diff --git a/firmware/targets/f7/ble_glue/ble_dbg_conf.h b/targets/f7/ble_glue/ble_dbg_conf.h similarity index 100% rename from firmware/targets/f7/ble_glue/ble_dbg_conf.h rename to targets/f7/ble_glue/ble_dbg_conf.h diff --git a/firmware/targets/f7/ble_glue/ble_glue.c b/targets/f7/ble_glue/ble_glue.c similarity index 100% rename from firmware/targets/f7/ble_glue/ble_glue.c rename to targets/f7/ble_glue/ble_glue.c diff --git a/firmware/targets/f7/ble_glue/ble_glue.h b/targets/f7/ble_glue/ble_glue.h similarity index 100% rename from firmware/targets/f7/ble_glue/ble_glue.h rename to targets/f7/ble_glue/ble_glue.h diff --git a/firmware/targets/f7/ble_glue/compiler.h b/targets/f7/ble_glue/compiler.h similarity index 100% rename from firmware/targets/f7/ble_glue/compiler.h rename to targets/f7/ble_glue/compiler.h diff --git a/firmware/targets/f7/ble_glue/gap.c b/targets/f7/ble_glue/gap.c similarity index 99% rename from firmware/targets/f7/ble_glue/gap.c rename to targets/f7/ble_glue/gap.c index ab7b9d16c..0ada37048 100644 --- a/firmware/targets/f7/ble_glue/gap.c +++ b/targets/f7/ble_glue/gap.c @@ -583,8 +583,6 @@ void gap_thread_stop() { // Free resources furi_mutex_free(gap->state_mutex); furi_message_queue_free(gap->command_queue); - furi_timer_stop(gap->advertise_timer); - while(xTimerIsTimerActive(gap->advertise_timer) == pdTRUE) furi_delay_tick(1); furi_timer_free(gap->advertise_timer); free(gap); gap = NULL; diff --git a/firmware/targets/f7/ble_glue/gap.h b/targets/f7/ble_glue/gap.h similarity index 100% rename from firmware/targets/f7/ble_glue/gap.h rename to targets/f7/ble_glue/gap.h diff --git a/firmware/targets/f7/ble_glue/hsem_map.h b/targets/f7/ble_glue/hsem_map.h similarity index 100% rename from firmware/targets/f7/ble_glue/hsem_map.h rename to targets/f7/ble_glue/hsem_map.h diff --git a/firmware/targets/f7/ble_glue/hw_ipcc.c b/targets/f7/ble_glue/hw_ipcc.c similarity index 100% rename from firmware/targets/f7/ble_glue/hw_ipcc.c rename to targets/f7/ble_glue/hw_ipcc.c diff --git a/firmware/targets/f7/ble_glue/osal.h b/targets/f7/ble_glue/osal.h similarity index 100% rename from firmware/targets/f7/ble_glue/osal.h rename to targets/f7/ble_glue/osal.h diff --git a/firmware/targets/f7/ble_glue/services/battery_service.c b/targets/f7/ble_glue/services/battery_service.c similarity index 100% rename from firmware/targets/f7/ble_glue/services/battery_service.c rename to targets/f7/ble_glue/services/battery_service.c diff --git a/firmware/targets/f7/ble_glue/services/battery_service.h b/targets/f7/ble_glue/services/battery_service.h similarity index 100% rename from firmware/targets/f7/ble_glue/services/battery_service.h rename to targets/f7/ble_glue/services/battery_service.h diff --git a/firmware/targets/f7/ble_glue/services/dev_info_service.c b/targets/f7/ble_glue/services/dev_info_service.c similarity index 100% rename from firmware/targets/f7/ble_glue/services/dev_info_service.c rename to targets/f7/ble_glue/services/dev_info_service.c diff --git a/firmware/targets/f7/ble_glue/services/dev_info_service.h b/targets/f7/ble_glue/services/dev_info_service.h similarity index 100% rename from firmware/targets/f7/ble_glue/services/dev_info_service.h rename to targets/f7/ble_glue/services/dev_info_service.h diff --git a/firmware/targets/f7/ble_glue/services/dev_info_service_uuid.inc b/targets/f7/ble_glue/services/dev_info_service_uuid.inc similarity index 100% rename from firmware/targets/f7/ble_glue/services/dev_info_service_uuid.inc rename to targets/f7/ble_glue/services/dev_info_service_uuid.inc diff --git a/firmware/targets/f7/ble_glue/services/gatt_char.c b/targets/f7/ble_glue/services/gatt_char.c similarity index 100% rename from firmware/targets/f7/ble_glue/services/gatt_char.c rename to targets/f7/ble_glue/services/gatt_char.c diff --git a/firmware/targets/f7/ble_glue/services/gatt_char.h b/targets/f7/ble_glue/services/gatt_char.h similarity index 100% rename from firmware/targets/f7/ble_glue/services/gatt_char.h rename to targets/f7/ble_glue/services/gatt_char.h diff --git a/firmware/targets/f7/ble_glue/services/hid_service.c b/targets/f7/ble_glue/services/hid_service.c similarity index 100% rename from firmware/targets/f7/ble_glue/services/hid_service.c rename to targets/f7/ble_glue/services/hid_service.c diff --git a/firmware/targets/f7/ble_glue/services/hid_service.h b/targets/f7/ble_glue/services/hid_service.h similarity index 100% rename from firmware/targets/f7/ble_glue/services/hid_service.h rename to targets/f7/ble_glue/services/hid_service.h diff --git a/firmware/targets/f7/ble_glue/services/serial_service.c b/targets/f7/ble_glue/services/serial_service.c similarity index 100% rename from firmware/targets/f7/ble_glue/services/serial_service.c rename to targets/f7/ble_glue/services/serial_service.c diff --git a/firmware/targets/f7/ble_glue/services/serial_service.h b/targets/f7/ble_glue/services/serial_service.h similarity index 100% rename from firmware/targets/f7/ble_glue/services/serial_service.h rename to targets/f7/ble_glue/services/serial_service.h diff --git a/firmware/targets/f7/ble_glue/services/serial_service_uuid.inc b/targets/f7/ble_glue/services/serial_service_uuid.inc similarity index 100% rename from firmware/targets/f7/ble_glue/services/serial_service_uuid.inc rename to targets/f7/ble_glue/services/serial_service_uuid.inc diff --git a/firmware/targets/f7/ble_glue/tl_dbg_conf.h b/targets/f7/ble_glue/tl_dbg_conf.h similarity index 100% rename from firmware/targets/f7/ble_glue/tl_dbg_conf.h rename to targets/f7/ble_glue/tl_dbg_conf.h diff --git a/firmware/targets/f7/fatfs/fatfs.c b/targets/f7/fatfs/fatfs.c similarity index 100% rename from firmware/targets/f7/fatfs/fatfs.c rename to targets/f7/fatfs/fatfs.c diff --git a/firmware/targets/f7/fatfs/fatfs.h b/targets/f7/fatfs/fatfs.h similarity index 100% rename from firmware/targets/f7/fatfs/fatfs.h rename to targets/f7/fatfs/fatfs.h diff --git a/firmware/targets/f7/fatfs/ffconf.h b/targets/f7/fatfs/ffconf.h similarity index 100% rename from firmware/targets/f7/fatfs/ffconf.h rename to targets/f7/fatfs/ffconf.h diff --git a/firmware/targets/f7/fatfs/sector_cache.c b/targets/f7/fatfs/sector_cache.c similarity index 100% rename from firmware/targets/f7/fatfs/sector_cache.c rename to targets/f7/fatfs/sector_cache.c diff --git a/firmware/targets/f7/fatfs/sector_cache.h b/targets/f7/fatfs/sector_cache.h similarity index 100% rename from firmware/targets/f7/fatfs/sector_cache.h rename to targets/f7/fatfs/sector_cache.h diff --git a/firmware/targets/f7/fatfs/user_diskio.c b/targets/f7/fatfs/user_diskio.c similarity index 100% rename from firmware/targets/f7/fatfs/user_diskio.c rename to targets/f7/fatfs/user_diskio.c diff --git a/firmware/targets/f7/fatfs/user_diskio.h b/targets/f7/fatfs/user_diskio.h similarity index 100% rename from firmware/targets/f7/fatfs/user_diskio.h rename to targets/f7/fatfs/user_diskio.h diff --git a/firmware/targets/f7/furi_hal/furi_hal.c b/targets/f7/furi_hal/furi_hal.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal.c rename to targets/f7/furi_hal/furi_hal.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_bt.c b/targets/f7/furi_hal/furi_hal_bt.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_bt.c rename to targets/f7/furi_hal/furi_hal_bt.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_bt_hid.c b/targets/f7/furi_hal/furi_hal_bt_hid.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_bt_hid.c rename to targets/f7/furi_hal/furi_hal_bt_hid.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_bt_serial.c b/targets/f7/furi_hal/furi_hal_bt_serial.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_bt_serial.c rename to targets/f7/furi_hal/furi_hal_bt_serial.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_bus.c b/targets/f7/furi_hal/furi_hal_bus.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_bus.c rename to targets/f7/furi_hal/furi_hal_bus.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_bus.h b/targets/f7/furi_hal/furi_hal_bus.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_bus.h rename to targets/f7/furi_hal/furi_hal_bus.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_clock.c b/targets/f7/furi_hal/furi_hal_clock.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_clock.c rename to targets/f7/furi_hal/furi_hal_clock.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_clock.h b/targets/f7/furi_hal/furi_hal_clock.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_clock.h rename to targets/f7/furi_hal/furi_hal_clock.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_console.c b/targets/f7/furi_hal/furi_hal_console.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_console.c rename to targets/f7/furi_hal/furi_hal_console.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_console.h b/targets/f7/furi_hal/furi_hal_console.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_console.h rename to targets/f7/furi_hal/furi_hal_console.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_cortex.c b/targets/f7/furi_hal/furi_hal_cortex.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_cortex.c rename to targets/f7/furi_hal/furi_hal_cortex.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_crypto.c b/targets/f7/furi_hal/furi_hal_crypto.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_crypto.c rename to targets/f7/furi_hal/furi_hal_crypto.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_debug.c b/targets/f7/furi_hal/furi_hal_debug.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_debug.c rename to targets/f7/furi_hal/furi_hal_debug.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_dma.c b/targets/f7/furi_hal/furi_hal_dma.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_dma.c rename to targets/f7/furi_hal/furi_hal_dma.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_dma.h b/targets/f7/furi_hal/furi_hal_dma.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_dma.h rename to targets/f7/furi_hal/furi_hal_dma.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_flash.c b/targets/f7/furi_hal/furi_hal_flash.c similarity index 99% rename from firmware/targets/f7/furi_hal/furi_hal_flash.c rename to targets/f7/furi_hal/furi_hal_flash.c index bc65b29eb..284d48bf5 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_flash.c +++ b/targets/f7/furi_hal/furi_hal_flash.c @@ -11,6 +11,9 @@ #include +#include +#include + #define TAG "FuriHalFlash" #define FURI_HAL_CRITICAL_MSG "Critical flash operation fail" diff --git a/firmware/targets/f7/furi_hal/furi_hal_flash.h b/targets/f7/furi_hal/furi_hal_flash.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_flash.h rename to targets/f7/furi_hal/furi_hal_flash.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_gpio.c b/targets/f7/furi_hal/furi_hal_gpio.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_gpio.c rename to targets/f7/furi_hal/furi_hal_gpio.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_gpio.h b/targets/f7/furi_hal/furi_hal_gpio.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_gpio.h rename to targets/f7/furi_hal/furi_hal_gpio.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_i2c.c b/targets/f7/furi_hal/furi_hal_i2c.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_i2c.c rename to targets/f7/furi_hal/furi_hal_i2c.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_i2c_config.c b/targets/f7/furi_hal/furi_hal_i2c_config.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_i2c_config.c rename to targets/f7/furi_hal/furi_hal_i2c_config.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_i2c_config.h b/targets/f7/furi_hal/furi_hal_i2c_config.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_i2c_config.h rename to targets/f7/furi_hal/furi_hal_i2c_config.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_i2c_types.h b/targets/f7/furi_hal/furi_hal_i2c_types.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_i2c_types.h rename to targets/f7/furi_hal/furi_hal_i2c_types.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_ibutton.c b/targets/f7/furi_hal/furi_hal_ibutton.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_ibutton.c rename to targets/f7/furi_hal/furi_hal_ibutton.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_ibutton.h b/targets/f7/furi_hal/furi_hal_ibutton.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_ibutton.h rename to targets/f7/furi_hal/furi_hal_ibutton.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_idle_timer.h b/targets/f7/furi_hal/furi_hal_idle_timer.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_idle_timer.h rename to targets/f7/furi_hal/furi_hal_idle_timer.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_info.c b/targets/f7/furi_hal/furi_hal_info.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_info.c rename to targets/f7/furi_hal/furi_hal_info.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_infrared.c b/targets/f7/furi_hal/furi_hal_infrared.c similarity index 99% rename from firmware/targets/f7/furi_hal/furi_hal_infrared.c rename to targets/f7/furi_hal/furi_hal_infrared.c index e76582dac..9c0d84c55 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_infrared.c +++ b/targets/f7/furi_hal/furi_hal_infrared.c @@ -128,7 +128,7 @@ static void furi_hal_infrared_tim_rx_isr() { if(infrared_tim_rx.capture_callback) infrared_tim_rx.capture_callback(infrared_tim_rx.capture_context, 1, duration); } else { - furi_assert(0); + furi_crash(); } } @@ -144,7 +144,7 @@ static void furi_hal_infrared_tim_rx_isr() { if(infrared_tim_rx.capture_callback) infrared_tim_rx.capture_callback(infrared_tim_rx.capture_context, 0, duration); } else { - furi_assert(0); + furi_crash(); } } } @@ -257,7 +257,7 @@ static uint8_t furi_hal_infrared_get_current_dma_tx_buffer(void) { } else if(buffer_adr == (uint32_t)infrared_tim_tx.buffer[1].data) { buf_num = 1; } else { - furi_assert(0); + furi_crash(); } return buf_num; } @@ -266,7 +266,7 @@ static void furi_hal_infrared_tx_dma_polarity_isr() { #if INFRARED_DMA_CH1_CHANNEL == LL_DMA_CHANNEL_1 if(LL_DMA_IsActiveFlag_TE1(INFRARED_DMA)) { LL_DMA_ClearFlag_TE1(INFRARED_DMA); - furi_crash(NULL); + furi_crash(); } if(LL_DMA_IsActiveFlag_TC1(INFRARED_DMA) && LL_DMA_IsEnabledIT_TC(INFRARED_DMA_CH1_DEF)) { LL_DMA_ClearFlag_TC1(INFRARED_DMA); @@ -288,7 +288,7 @@ static void furi_hal_infrared_tx_dma_isr() { #if INFRARED_DMA_CH2_CHANNEL == LL_DMA_CHANNEL_2 if(LL_DMA_IsActiveFlag_TE2(INFRARED_DMA)) { LL_DMA_ClearFlag_TE2(INFRARED_DMA); - furi_crash(NULL); + furi_crash(); } if(LL_DMA_IsActiveFlag_HT2(INFRARED_DMA) && LL_DMA_IsEnabledIT_HT(INFRARED_DMA_CH2_DEF)) { LL_DMA_ClearFlag_HT2(INFRARED_DMA); @@ -306,7 +306,7 @@ static void furi_hal_infrared_tx_dma_isr() { } else if(furi_hal_infrared_state == InfraredStateAsyncTxStopReq) { /* fallthrough */ } else { - furi_crash(NULL); + furi_crash(); } } if(LL_DMA_IsActiveFlag_TC2(INFRARED_DMA) && LL_DMA_IsEnabledIT_TC(INFRARED_DMA_CH2_DEF)) { @@ -605,7 +605,7 @@ static void furi_hal_infrared_async_tx_free_resources(void) { void furi_hal_infrared_async_tx_start(uint32_t freq, float duty_cycle) { if((duty_cycle > 1) || (duty_cycle <= 0) || (freq > INFRARED_MAX_FREQUENCY) || (freq < INFRARED_MIN_FREQUENCY) || (infrared_tim_tx.data_callback == NULL)) { - furi_crash(NULL); + furi_crash(); } furi_assert(furi_hal_infrared_state == InfraredStateIdle); diff --git a/firmware/targets/f7/furi_hal/furi_hal_interrupt.c b/targets/f7/furi_hal/furi_hal_interrupt.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_interrupt.c rename to targets/f7/furi_hal/furi_hal_interrupt.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_interrupt.h b/targets/f7/furi_hal/furi_hal_interrupt.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_interrupt.h rename to targets/f7/furi_hal/furi_hal_interrupt.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_light.c b/targets/f7/furi_hal/furi_hal_light.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_light.c rename to targets/f7/furi_hal/furi_hal_light.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_memory.c b/targets/f7/furi_hal/furi_hal_memory.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_memory.c rename to targets/f7/furi_hal/furi_hal_memory.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_mpu.c b/targets/f7/furi_hal/furi_hal_mpu.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_mpu.c rename to targets/f7/furi_hal/furi_hal_mpu.c diff --git a/targets/f7/furi_hal/furi_hal_nfc.c b/targets/f7/furi_hal/furi_hal_nfc.c new file mode 100644 index 000000000..e8a1033d5 --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc.c @@ -0,0 +1,621 @@ +#include "furi_hal_nfc_i.h" +#include "furi_hal_nfc_tech_i.h" + +#include + +#include +#include + +#define TAG "FuriHalNfc" + +const FuriHalNfcTechBase* furi_hal_nfc_tech[FuriHalNfcTechNum] = { + [FuriHalNfcTechIso14443a] = &furi_hal_nfc_iso14443a, + [FuriHalNfcTechIso14443b] = &furi_hal_nfc_iso14443b, + [FuriHalNfcTechIso15693] = &furi_hal_nfc_iso15693, + [FuriHalNfcTechFelica] = &furi_hal_nfc_felica, + // Add new technologies here +}; + +FuriHalNfc furi_hal_nfc; + +static FuriHalNfcError furi_hal_nfc_turn_on_osc(FuriHalSpiBusHandle* handle) { + FuriHalNfcError error = FuriHalNfcErrorNone; + furi_hal_nfc_event_start(); + + if(!st25r3916_check_reg( + handle, + ST25R3916_REG_OP_CONTROL, + ST25R3916_REG_OP_CONTROL_en, + ST25R3916_REG_OP_CONTROL_en)) { + st25r3916_mask_irq(handle, ~ST25R3916_IRQ_MASK_OSC); + st25r3916_set_reg_bits(handle, ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_en); + furi_hal_nfc_event_wait_for_specific_irq(handle, ST25R3916_IRQ_MASK_OSC, 10); + } + // Disable IRQs + st25r3916_mask_irq(handle, ST25R3916_IRQ_MASK_ALL); + + bool osc_on = st25r3916_check_reg( + handle, + ST25R3916_REG_AUX_DISPLAY, + ST25R3916_REG_AUX_DISPLAY_osc_ok, + ST25R3916_REG_AUX_DISPLAY_osc_ok); + if(!osc_on) { + error = FuriHalNfcErrorOscillator; + } + + return error; +} + +FuriHalNfcError furi_hal_nfc_is_hal_ready() { + FuriHalNfcError error = FuriHalNfcErrorNone; + + do { + error = furi_hal_nfc_acquire(); + if(error != FuriHalNfcErrorNone) break; + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + uint8_t chip_id = 0; + st25r3916_read_reg(handle, ST25R3916_REG_IC_IDENTITY, &chip_id); + if((chip_id & ST25R3916_REG_IC_IDENTITY_ic_type_mask) != + ST25R3916_REG_IC_IDENTITY_ic_type_st25r3916) { + FURI_LOG_E(TAG, "Wrong chip id"); + error = FuriHalNfcErrorCommunication; + } + + furi_hal_nfc_release(); + } while(false); + + return error; +} + +FuriHalNfcError furi_hal_nfc_init() { + furi_assert(furi_hal_nfc.mutex == NULL); + + furi_hal_nfc.mutex = furi_mutex_alloc(FuriMutexTypeNormal); + FuriHalNfcError error = FuriHalNfcErrorNone; + + furi_hal_nfc_event_init(); + furi_hal_nfc_event_start(); + + do { + error = furi_hal_nfc_acquire(); + if(error != FuriHalNfcErrorNone) { + furi_hal_nfc_low_power_mode_start(); + } + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + // Set default state + st25r3916_direct_cmd(handle, ST25R3916_CMD_SET_DEFAULT); + // Increase IO driver strength of MISO and IRQ + st25r3916_write_reg(handle, ST25R3916_REG_IO_CONF2, ST25R3916_REG_IO_CONF2_io_drv_lvl); + // Check chip ID + uint8_t chip_id = 0; + st25r3916_read_reg(handle, ST25R3916_REG_IC_IDENTITY, &chip_id); + if((chip_id & ST25R3916_REG_IC_IDENTITY_ic_type_mask) != + ST25R3916_REG_IC_IDENTITY_ic_type_st25r3916) { + FURI_LOG_E(TAG, "Wrong chip id"); + error = FuriHalNfcErrorCommunication; + furi_hal_nfc_low_power_mode_start(); + furi_hal_nfc_release(); + break; + } + // Clear interrupts + st25r3916_get_irq(handle); + // Mask all interrupts + st25r3916_mask_irq(handle, ST25R3916_IRQ_MASK_ALL); + // Enable interrupts + furi_hal_nfc_init_gpio_isr(); + // Disable internal overheat protection + st25r3916_change_test_reg_bits(handle, 0x04, 0x10, 0x10); + + error = furi_hal_nfc_turn_on_osc(handle); + if(error != FuriHalNfcErrorNone) { + furi_hal_nfc_low_power_mode_start(); + furi_hal_nfc_release(); + break; + } + + // Measure voltage + // Set measure power supply voltage source + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_REGULATOR_CONTROL, + ST25R3916_REG_REGULATOR_CONTROL_mpsv_mask, + ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd); + // Enable timer and interrupt register + st25r3916_mask_irq(handle, ~ST25R3916_IRQ_MASK_DCT); + st25r3916_direct_cmd(handle, ST25R3916_CMD_MEASURE_VDD); + furi_hal_nfc_event_wait_for_specific_irq(handle, ST25R3916_IRQ_MASK_DCT, 100); + st25r3916_mask_irq(handle, ST25R3916_IRQ_MASK_ALL); + uint8_t ad_res = 0; + st25r3916_read_reg(handle, ST25R3916_REG_AD_RESULT, &ad_res); + uint16_t mV = ((uint16_t)ad_res) * 23U; + mV += (((((uint16_t)ad_res) * 4U) + 5U) / 10U); + + if(mV < 3600) { + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_IO_CONF2, + ST25R3916_REG_IO_CONF2_sup3V, + ST25R3916_REG_IO_CONF2_sup3V_3V); + } else { + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_IO_CONF2, + ST25R3916_REG_IO_CONF2_sup3V, + ST25R3916_REG_IO_CONF2_sup3V_5V); + } + + // Disable MCU CLK + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_IO_CONF1, + ST25R3916_REG_IO_CONF1_out_cl_mask | ST25R3916_REG_IO_CONF1_lf_clk_off, + 0x07); + // Disable MISO pull-down + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_IO_CONF2, + ST25R3916_REG_IO_CONF2_miso_pd1 | ST25R3916_REG_IO_CONF2_miso_pd2, + 0x00); + // Set tx driver resistance to 1 Om + st25r3916_change_reg_bits( + handle, ST25R3916_REG_TX_DRIVER, ST25R3916_REG_TX_DRIVER_d_res_mask, 0x00); + // Use minimum non-overlap + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_RES_AM_MOD, + ST25R3916_REG_RES_AM_MOD_fa3_f, + ST25R3916_REG_RES_AM_MOD_fa3_f); + + // Set activation threashold + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_FIELD_THRESHOLD_ACTV, + ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_mask, + ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_105mV); + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_FIELD_THRESHOLD_ACTV, + ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_mask, + ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_105mV); + // Set deactivation threashold + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_FIELD_THRESHOLD_DEACTV, + ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_mask, + ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_75mV); + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_FIELD_THRESHOLD_DEACTV, + ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_mask, + ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_75mV); + // Enable external load modulation + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_AUX_MOD, + ST25R3916_REG_AUX_MOD_lm_ext, + ST25R3916_REG_AUX_MOD_lm_ext); + // Enable internal load modulation + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_AUX_MOD, + ST25R3916_REG_AUX_MOD_lm_dri, + ST25R3916_REG_AUX_MOD_lm_dri); + // Adjust FDT + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_PASSIVE_TARGET, + ST25R3916_REG_PASSIVE_TARGET_fdel_mask, + (5U << ST25R3916_REG_PASSIVE_TARGET_fdel_shift)); + // Reduce RFO resistance in Modulated state + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_PT_MOD, + ST25R3916_REG_PT_MOD_ptm_res_mask | ST25R3916_REG_PT_MOD_pt_res_mask, + 0x0f); + // Enable RX start on first 4 bits + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_EMD_SUP_CONF, + ST25R3916_REG_EMD_SUP_CONF_rx_start_emv, + ST25R3916_REG_EMD_SUP_CONF_rx_start_emv_on); + // Set antena tunning + st25r3916_change_reg_bits(handle, ST25R3916_REG_ANT_TUNE_A, 0xff, 0x82); + st25r3916_change_reg_bits(handle, ST25R3916_REG_ANT_TUNE_B, 0xff, 0x82); + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_OP_CONTROL, + ST25R3916_REG_OP_CONTROL_en_fd_mask, + ST25R3916_REG_OP_CONTROL_en_fd_auto_efd); + + // Perform calibration + if(st25r3916_check_reg( + handle, + ST25R3916_REG_REGULATOR_CONTROL, + ST25R3916_REG_REGULATOR_CONTROL_reg_s, + 0x00)) { + FURI_LOG_I(TAG, "Adjusting regulators"); + // Reset logic + st25r3916_set_reg_bits( + handle, ST25R3916_REG_REGULATOR_CONTROL, ST25R3916_REG_REGULATOR_CONTROL_reg_s); + st25r3916_clear_reg_bits( + handle, ST25R3916_REG_REGULATOR_CONTROL, ST25R3916_REG_REGULATOR_CONTROL_reg_s); + st25r3916_direct_cmd(handle, ST25R3916_CMD_ADJUST_REGULATORS); + furi_delay_ms(6); + } + + furi_hal_nfc_low_power_mode_start(); + furi_hal_nfc_release(); + } while(false); + + return error; +} + +static bool furi_hal_nfc_is_mine() { + return (furi_mutex_get_owner(furi_hal_nfc.mutex) == furi_thread_get_current_id()); +} + +FuriHalNfcError furi_hal_nfc_acquire() { + furi_check(furi_hal_nfc.mutex); + + furi_hal_spi_acquire(&furi_hal_spi_bus_handle_nfc); + + FuriHalNfcError error = FuriHalNfcErrorNone; + if(furi_mutex_acquire(furi_hal_nfc.mutex, 100) != FuriStatusOk) { + furi_hal_spi_release(&furi_hal_spi_bus_handle_nfc); + error = FuriHalNfcErrorBusy; + } + + return error; +} + +FuriHalNfcError furi_hal_nfc_release() { + furi_check(furi_hal_nfc.mutex); + furi_check(furi_hal_nfc_is_mine()); + furi_check(furi_mutex_release(furi_hal_nfc.mutex) == FuriStatusOk); + + furi_hal_spi_release(&furi_hal_spi_bus_handle_nfc); + + return FuriHalNfcErrorNone; +} + +FuriHalNfcError furi_hal_nfc_low_power_mode_start() { + FuriHalNfcError error = FuriHalNfcErrorNone; + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + st25r3916_direct_cmd(handle, ST25R3916_CMD_STOP); + st25r3916_clear_reg_bits( + handle, + ST25R3916_REG_OP_CONTROL, + (ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_rx_en | + ST25R3916_REG_OP_CONTROL_wu | ST25R3916_REG_OP_CONTROL_tx_en | + ST25R3916_REG_OP_CONTROL_en_fd_mask)); + furi_hal_nfc_deinit_gpio_isr(); + furi_hal_nfc_timers_deinit(); + furi_hal_nfc_event_stop(); + + return error; +} + +FuriHalNfcError furi_hal_nfc_low_power_mode_stop() { + FuriHalNfcError error = FuriHalNfcErrorNone; + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + do { + furi_hal_nfc_init_gpio_isr(); + furi_hal_nfc_timers_init(); + error = furi_hal_nfc_turn_on_osc(handle); + if(error != FuriHalNfcErrorNone) break; + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_OP_CONTROL, + ST25R3916_REG_OP_CONTROL_en_fd_mask, + ST25R3916_REG_OP_CONTROL_en_fd_auto_efd); + + } while(false); + + return error; +} + +static FuriHalNfcError furi_hal_nfc_poller_init_common(FuriHalSpiBusHandle* handle) { + // Disable wake up + st25r3916_clear_reg_bits(handle, ST25R3916_REG_OP_CONTROL, ST25R3916_REG_OP_CONTROL_wu); + // Enable correlator + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_AUX, + ST25R3916_REG_AUX_dis_corr, + ST25R3916_REG_AUX_dis_corr_correlator); + + st25r3916_change_reg_bits(handle, ST25R3916_REG_ANT_TUNE_A, 0xff, 0x82); + st25r3916_change_reg_bits(handle, ST25R3916_REG_ANT_TUNE_B, 0xFF, 0x82); + + st25r3916_write_reg(handle, ST25R3916_REG_OVERSHOOT_CONF1, 0x00); + st25r3916_write_reg(handle, ST25R3916_REG_OVERSHOOT_CONF2, 0x00); + st25r3916_write_reg(handle, ST25R3916_REG_UNDERSHOOT_CONF1, 0x00); + st25r3916_write_reg(handle, ST25R3916_REG_UNDERSHOOT_CONF2, 0x00); + + return FuriHalNfcErrorNone; +} + +static FuriHalNfcError furi_hal_nfc_listener_init_common(FuriHalSpiBusHandle* handle) { + UNUSED(handle); + // No common listener configuration + return FuriHalNfcErrorNone; +} + +FuriHalNfcError furi_hal_nfc_set_mode(FuriHalNfcMode mode, FuriHalNfcTech tech) { + furi_assert(mode < FuriHalNfcModeNum); + furi_assert(tech < FuriHalNfcTechNum); + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + FuriHalNfcError error = FuriHalNfcErrorNone; + + if(mode == FuriHalNfcModePoller) { + do { + error = furi_hal_nfc_poller_init_common(handle); + if(error != FuriHalNfcErrorNone) break; + error = furi_hal_nfc_tech[tech]->poller.init(handle); + } while(false); + + } else if(mode == FuriHalNfcModeListener) { + do { + error = furi_hal_nfc_listener_init_common(handle); + if(error != FuriHalNfcErrorNone) break; + error = furi_hal_nfc_tech[tech]->listener.init(handle); + } while(false); + } + + furi_hal_nfc.mode = mode; + furi_hal_nfc.tech = tech; + return error; +} + +FuriHalNfcError furi_hal_nfc_reset_mode() { + FuriHalNfcError error = FuriHalNfcErrorNone; + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + st25r3916_direct_cmd(handle, ST25R3916_CMD_STOP); + + const FuriHalNfcMode mode = furi_hal_nfc.mode; + const FuriHalNfcTech tech = furi_hal_nfc.tech; + if(mode == FuriHalNfcModePoller) { + error = furi_hal_nfc_tech[tech]->poller.deinit(handle); + } else if(mode == FuriHalNfcModeListener) { + error = furi_hal_nfc_tech[tech]->listener.deinit(handle); + } + // Set default value in mode register + st25r3916_write_reg(handle, ST25R3916_REG_MODE, ST25R3916_REG_MODE_om0); + st25r3916_write_reg(handle, ST25R3916_REG_STREAM_MODE, 0); + st25r3916_clear_reg_bits(handle, ST25R3916_REG_AUX, ST25R3916_REG_AUX_no_crc_rx); + st25r3916_clear_reg_bits( + handle, + ST25R3916_REG_BIT_RATE, + ST25R3916_REG_BIT_RATE_txrate_mask | ST25R3916_REG_BIT_RATE_rxrate_mask); + + // Write default values + st25r3916_write_reg(handle, ST25R3916_REG_RX_CONF1, 0); + st25r3916_write_reg( + handle, + ST25R3916_REG_RX_CONF2, + ST25R3916_REG_RX_CONF2_sqm_dyn | ST25R3916_REG_RX_CONF2_agc_en | + ST25R3916_REG_RX_CONF2_agc_m); + + st25r3916_write_reg( + handle, + ST25R3916_REG_CORR_CONF1, + ST25R3916_REG_CORR_CONF1_corr_s7 | ST25R3916_REG_CORR_CONF1_corr_s4 | + ST25R3916_REG_CORR_CONF1_corr_s1 | ST25R3916_REG_CORR_CONF1_corr_s0); + st25r3916_write_reg(handle, ST25R3916_REG_CORR_CONF2, 0); + + return error; +} + +FuriHalNfcError furi_hal_nfc_field_detect_start() { + FuriHalNfcError error = FuriHalNfcErrorNone; + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + st25r3916_write_reg( + handle, + ST25R3916_REG_OP_CONTROL, + ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_en_fd_mask); + st25r3916_write_reg( + handle, ST25R3916_REG_MODE, ST25R3916_REG_MODE_targ | ST25R3916_REG_MODE_om0); + + return error; +} + +FuriHalNfcError furi_hal_nfc_field_detect_stop() { + FuriHalNfcError error = FuriHalNfcErrorNone; + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + st25r3916_clear_reg_bits( + handle, + ST25R3916_REG_OP_CONTROL, + (ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_en_fd_mask)); + + return error; +} + +bool furi_hal_nfc_field_is_present() { + bool is_present = false; + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + if(st25r3916_check_reg( + handle, + ST25R3916_REG_AUX_DISPLAY, + ST25R3916_REG_AUX_DISPLAY_efd_o, + ST25R3916_REG_AUX_DISPLAY_efd_o)) { + is_present = true; + } + + return is_present; +} + +FuriHalNfcError furi_hal_nfc_poller_field_on() { + FuriHalNfcError error = FuriHalNfcErrorNone; + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + if(!st25r3916_check_reg( + handle, + ST25R3916_REG_OP_CONTROL, + ST25R3916_REG_OP_CONTROL_tx_en, + ST25R3916_REG_OP_CONTROL_tx_en)) { + // Set min guard time + st25r3916_write_reg(handle, ST25R3916_REG_FIELD_ON_GT, 0); + // Enable tx rx + st25r3916_set_reg_bits( + handle, + ST25R3916_REG_OP_CONTROL, + (ST25R3916_REG_OP_CONTROL_rx_en | ST25R3916_REG_OP_CONTROL_tx_en)); + } + + return error; +} + +FuriHalNfcError furi_hal_nfc_poller_tx_common( + FuriHalSpiBusHandle* handle, + const uint8_t* tx_data, + size_t tx_bits) { + furi_assert(tx_data); + + FuriHalNfcError err = FuriHalNfcErrorNone; + + // Prepare tx + st25r3916_direct_cmd(handle, ST25R3916_CMD_CLEAR_FIFO); + st25r3916_clear_reg_bits( + handle, ST25R3916_REG_TIMER_EMV_CONTROL, ST25R3916_REG_TIMER_EMV_CONTROL_nrt_emv); + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_ISO14443A_NFC, + (ST25R3916_REG_ISO14443A_NFC_no_tx_par | ST25R3916_REG_ISO14443A_NFC_no_rx_par), + (ST25R3916_REG_ISO14443A_NFC_no_tx_par_off | ST25R3916_REG_ISO14443A_NFC_no_rx_par_off)); + uint32_t interrupts = + (ST25R3916_IRQ_MASK_FWL | ST25R3916_IRQ_MASK_TXE | ST25R3916_IRQ_MASK_RXS | + ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_CRC | + ST25R3916_IRQ_MASK_ERR1 | ST25R3916_IRQ_MASK_ERR2 | ST25R3916_IRQ_MASK_NRE); + // Clear interrupts + st25r3916_get_irq(handle); + // Enable interrupts + st25r3916_mask_irq(handle, ~interrupts); + + st25r3916_write_fifo(handle, tx_data, tx_bits); + st25r3916_direct_cmd(handle, ST25R3916_CMD_TRANSMIT_WITHOUT_CRC); + + return err; +} + +FuriHalNfcError furi_hal_nfc_common_fifo_tx( + FuriHalSpiBusHandle* handle, + const uint8_t* tx_data, + size_t tx_bits) { + FuriHalNfcError err = FuriHalNfcErrorNone; + + st25r3916_direct_cmd(handle, ST25R3916_CMD_CLEAR_FIFO); + st25r3916_write_fifo(handle, tx_data, tx_bits); + st25r3916_direct_cmd(handle, ST25R3916_CMD_TRANSMIT_WITHOUT_CRC); + + return err; +} + +FuriHalNfcError furi_hal_nfc_poller_tx(const uint8_t* tx_data, size_t tx_bits) { + furi_assert(furi_hal_nfc.mode == FuriHalNfcModePoller); + furi_assert(furi_hal_nfc.tech < FuriHalNfcTechNum); + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + return furi_hal_nfc_tech[furi_hal_nfc.tech]->poller.tx(handle, tx_data, tx_bits); +} + +FuriHalNfcError furi_hal_nfc_poller_rx(uint8_t* rx_data, size_t rx_data_size, size_t* rx_bits) { + furi_assert(furi_hal_nfc.mode == FuriHalNfcModePoller); + furi_assert(furi_hal_nfc.tech < FuriHalNfcTechNum); + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + return furi_hal_nfc_tech[furi_hal_nfc.tech]->poller.rx(handle, rx_data, rx_data_size, rx_bits); +} + +FuriHalNfcEvent furi_hal_nfc_poller_wait_event(uint32_t timeout_ms) { + furi_assert(furi_hal_nfc.mode == FuriHalNfcModePoller); + furi_assert(furi_hal_nfc.tech < FuriHalNfcTechNum); + + return furi_hal_nfc_tech[furi_hal_nfc.tech]->poller.wait_event(timeout_ms); +} + +FuriHalNfcEvent furi_hal_nfc_listener_wait_event(uint32_t timeout_ms) { + furi_assert(furi_hal_nfc.mode == FuriHalNfcModeListener); + furi_assert(furi_hal_nfc.tech < FuriHalNfcTechNum); + + return furi_hal_nfc_tech[furi_hal_nfc.tech]->listener.wait_event(timeout_ms); +} + +FuriHalNfcError furi_hal_nfc_listener_tx(const uint8_t* tx_data, size_t tx_bits) { + furi_assert(tx_data); + + furi_assert(furi_hal_nfc.mode == FuriHalNfcModeListener); + furi_assert(furi_hal_nfc.tech < FuriHalNfcTechNum); + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + return furi_hal_nfc_tech[furi_hal_nfc.tech]->listener.tx(handle, tx_data, tx_bits); +} + +FuriHalNfcError furi_hal_nfc_common_fifo_rx( + FuriHalSpiBusHandle* handle, + uint8_t* rx_data, + size_t rx_data_size, + size_t* rx_bits) { + FuriHalNfcError error = FuriHalNfcErrorNone; + + if(!st25r3916_read_fifo(handle, rx_data, rx_data_size, rx_bits)) { + error = FuriHalNfcErrorBufferOverflow; + } + + return error; +} + +FuriHalNfcError furi_hal_nfc_listener_rx(uint8_t* rx_data, size_t rx_data_size, size_t* rx_bits) { + furi_assert(rx_data); + furi_assert(rx_bits); + + furi_assert(furi_hal_nfc.mode == FuriHalNfcModeListener); + furi_assert(furi_hal_nfc.tech < FuriHalNfcTechNum); + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + return furi_hal_nfc_tech[furi_hal_nfc.tech]->listener.rx( + handle, rx_data, rx_data_size, rx_bits); +} + +FuriHalNfcError furi_hal_nfc_trx_reset() { + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + st25r3916_direct_cmd(handle, ST25R3916_CMD_STOP); + + return FuriHalNfcErrorNone; +} + +FuriHalNfcError furi_hal_nfc_listener_sleep() { + furi_assert(furi_hal_nfc.mode == FuriHalNfcModeListener); + furi_assert(furi_hal_nfc.tech < FuriHalNfcTechNum); + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + return furi_hal_nfc_tech[furi_hal_nfc.tech]->listener.sleep(handle); +} + +FuriHalNfcError furi_hal_nfc_listener_idle() { + furi_assert(furi_hal_nfc.mode == FuriHalNfcModeListener); + furi_assert(furi_hal_nfc.tech < FuriHalNfcTechNum); + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + return furi_hal_nfc_tech[furi_hal_nfc.tech]->listener.idle(handle); +} + +FuriHalNfcError furi_hal_nfc_listener_enable_rx() { + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + st25r3916_direct_cmd(handle, ST25R3916_CMD_UNMASK_RECEIVE_DATA); + + return FuriHalNfcErrorNone; +} diff --git a/targets/f7/furi_hal/furi_hal_nfc_event.c b/targets/f7/furi_hal/furi_hal_nfc_event.c new file mode 100644 index 000000000..266b606fd --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc_event.c @@ -0,0 +1,117 @@ +#include + +FuriHalNfcEventInternal* furi_hal_nfc_event = NULL; + +void furi_hal_nfc_event_init() { + furi_hal_nfc_event = malloc(sizeof(FuriHalNfcEventInternal)); +} + +FuriHalNfcError furi_hal_nfc_event_start() { + furi_assert(furi_hal_nfc_event); + + furi_hal_nfc_event->thread = furi_thread_get_current_id(); + furi_thread_flags_clear(FURI_HAL_NFC_EVENT_INTERNAL_ALL); + + return FuriHalNfcErrorNone; +} + +FuriHalNfcError furi_hal_nfc_event_stop() { + furi_assert(furi_hal_nfc_event); + + furi_hal_nfc_event->thread = NULL; + + return FuriHalNfcErrorNone; +} + +void furi_hal_nfc_event_set(FuriHalNfcEventInternalType event) { + furi_assert(furi_hal_nfc_event); + + if(furi_hal_nfc_event->thread) { + furi_thread_flags_set(furi_hal_nfc_event->thread, event); + } +} + +FuriHalNfcError furi_hal_nfc_abort() { + furi_hal_nfc_event_set(FuriHalNfcEventInternalTypeAbort); + return FuriHalNfcErrorNone; +} + +FuriHalNfcEvent furi_hal_nfc_wait_event_common(uint32_t timeout_ms) { + furi_assert(furi_hal_nfc_event); + furi_assert(furi_hal_nfc_event->thread); + + FuriHalNfcEvent event = 0; + uint32_t event_timeout = timeout_ms == FURI_HAL_NFC_EVENT_WAIT_FOREVER ? FuriWaitForever : + timeout_ms; + uint32_t event_flag = + furi_thread_flags_wait(FURI_HAL_NFC_EVENT_INTERNAL_ALL, FuriFlagWaitAny, event_timeout); + if(event_flag != (unsigned)FuriFlagErrorTimeout) { + if(event_flag & FuriHalNfcEventInternalTypeIrq) { + furi_thread_flags_clear(FuriHalNfcEventInternalTypeIrq); + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + uint32_t irq = furi_hal_nfc_get_irq(handle); + if(irq & ST25R3916_IRQ_MASK_OSC) { + event |= FuriHalNfcEventOscOn; + } + if(irq & ST25R3916_IRQ_MASK_TXE) { + event |= FuriHalNfcEventTxEnd; + } + if(irq & ST25R3916_IRQ_MASK_RXS) { + event |= FuriHalNfcEventRxStart; + } + if(irq & ST25R3916_IRQ_MASK_RXE) { + event |= FuriHalNfcEventRxEnd; + } + if(irq & ST25R3916_IRQ_MASK_COL) { + event |= FuriHalNfcEventCollision; + } + if(irq & ST25R3916_IRQ_MASK_EON) { + event |= FuriHalNfcEventFieldOn; + } + if(irq & ST25R3916_IRQ_MASK_EOF) { + event |= FuriHalNfcEventFieldOff; + } + if(irq & ST25R3916_IRQ_MASK_WU_A) { + event |= FuriHalNfcEventListenerActive; + } + if(irq & ST25R3916_IRQ_MASK_WU_A_X) { + event |= FuriHalNfcEventListenerActive; + } + } + if(event_flag & FuriHalNfcEventInternalTypeTimerFwtExpired) { + event |= FuriHalNfcEventTimerFwtExpired; + furi_thread_flags_clear(FuriHalNfcEventInternalTypeTimerFwtExpired); + } + if(event_flag & FuriHalNfcEventInternalTypeTimerBlockTxExpired) { + event |= FuriHalNfcEventTimerBlockTxExpired; + furi_thread_flags_clear(FuriHalNfcEventInternalTypeTimerBlockTxExpired); + } + if(event_flag & FuriHalNfcEventInternalTypeAbort) { + event |= FuriHalNfcEventAbortRequest; + furi_thread_flags_clear(FuriHalNfcEventInternalTypeAbort); + } + } else { + event = FuriHalNfcEventTimeout; + } + + return event; +} + +bool furi_hal_nfc_event_wait_for_specific_irq( + FuriHalSpiBusHandle* handle, + uint32_t mask, + uint32_t timeout_ms) { + furi_assert(furi_hal_nfc_event); + furi_assert(furi_hal_nfc_event->thread); + + bool irq_received = false; + uint32_t event_flag = + furi_thread_flags_wait(FuriHalNfcEventInternalTypeIrq, FuriFlagWaitAny, timeout_ms); + if(event_flag == FuriHalNfcEventInternalTypeIrq) { + uint32_t irq = furi_hal_nfc_get_irq(handle); + irq_received = ((irq & mask) == mask); + furi_thread_flags_clear(FuriHalNfcEventInternalTypeIrq); + } + + return irq_received; +} diff --git a/targets/f7/furi_hal/furi_hal_nfc_felica.c b/targets/f7/furi_hal/furi_hal_nfc_felica.c new file mode 100644 index 000000000..e4b8ac0ee --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc_felica.c @@ -0,0 +1,69 @@ +#include "furi_hal_nfc_i.h" +#include "furi_hal_nfc_tech_i.h" + +static FuriHalNfcError furi_hal_nfc_felica_poller_init(FuriHalSpiBusHandle* handle) { + // Enable Felica mode, AM modulation + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_MODE, + ST25R3916_REG_MODE_om_mask | ST25R3916_REG_MODE_tr_am, + ST25R3916_REG_MODE_om_felica | ST25R3916_REG_MODE_tr_am_am); + + // 10% ASK modulation + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_TX_DRIVER, + ST25R3916_REG_TX_DRIVER_am_mod_mask, + ST25R3916_REG_TX_DRIVER_am_mod_10percent); + + // Use regulator AM, resistive AM disabled + st25r3916_clear_reg_bits( + handle, + ST25R3916_REG_AUX_MOD, + ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am); + + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_BIT_RATE, + ST25R3916_REG_BIT_RATE_txrate_mask | ST25R3916_REG_BIT_RATE_rxrate_mask, + ST25R3916_REG_BIT_RATE_txrate_212 | ST25R3916_REG_BIT_RATE_rxrate_212); + + // Receive configuration + st25r3916_write_reg( + handle, + ST25R3916_REG_RX_CONF1, + ST25R3916_REG_RX_CONF1_lp0 | ST25R3916_REG_RX_CONF1_hz_12_80khz); + + // Correlator setup + st25r3916_write_reg( + handle, + ST25R3916_REG_CORR_CONF1, + ST25R3916_REG_CORR_CONF1_corr_s6 | ST25R3916_REG_CORR_CONF1_corr_s4 | + ST25R3916_REG_CORR_CONF1_corr_s3); + + return FuriHalNfcErrorNone; +} + +static FuriHalNfcError furi_hal_nfc_felica_poller_deinit(FuriHalSpiBusHandle* handle) { + UNUSED(handle); + + return FuriHalNfcErrorNone; +} + +const FuriHalNfcTechBase furi_hal_nfc_felica = { + .poller = + { + .compensation = + { + .fdt = FURI_HAL_NFC_POLLER_FDT_COMP_FC, + .fwt = FURI_HAL_NFC_POLLER_FWT_COMP_FC, + }, + .init = furi_hal_nfc_felica_poller_init, + .deinit = furi_hal_nfc_felica_poller_deinit, + .wait_event = furi_hal_nfc_wait_event_common, + .tx = furi_hal_nfc_poller_tx_common, + .rx = furi_hal_nfc_common_fifo_rx, + }, + + .listener = {}, +}; diff --git a/targets/f7/furi_hal/furi_hal_nfc_i.h b/targets/f7/furi_hal/furi_hal_nfc_i.h new file mode 100644 index 000000000..53a25644d --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc_i.h @@ -0,0 +1,191 @@ +/** + * @file furi_hal_nfc_i.h + * @brief NFC HAL library (private definitions). + * + * This file is an implementation detail. It must not be included in + * any public API-related headers. + */ +#pragma once + +#include +#include +#include + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** @brief Common frame delay time compensation for pollers. */ +#define FURI_HAL_NFC_POLLER_FDT_COMP_FC (-500) +/** @brief Common frame wait time compensation for pollers. */ +#define FURI_HAL_NFC_POLLER_FWT_COMP_FC (FURI_HAL_NFC_POLLER_FDT_COMP_FC) + +/** + * @brief Enumeration containing bitmask values for NFC HAL internal events. + */ +typedef enum { + FuriHalNfcEventInternalTypeAbort = (1U << 0), /**< Abort waiting for hardware events. */ + FuriHalNfcEventInternalTypeIrq = (1U << 1), /**< NFC hardware interrupt has occurred. */ + FuriHalNfcEventInternalTypeTimerFwtExpired = + (1U << 2), /**< Frame wait time timeout has expired. */ + FuriHalNfcEventInternalTypeTimerBlockTxExpired = + (1U << 3), /**< Transmission block timeout has expired. */ + FuriHalNfcEventInternalTypeTransparentDataReceived = + (1U << 4), /**< Data was received in transparent mode. */ +} FuriHalNfcEventInternalType; + +/** @brief Special bitmask value of all internal events. */ +#define FURI_HAL_NFC_EVENT_INTERNAL_ALL \ + ((FuriHalNfcEventInternalTypeAbort | FuriHalNfcEventInternalTypeIrq | \ + FuriHalNfcEventInternalTypeTimerFwtExpired | \ + FuriHalNfcEventInternalTypeTimerBlockTxExpired | \ + FuriHalNfcEventInternalTypeTransparentDataReceived)) + +/** + * @brief NFC HAL internal event structure. + */ +typedef struct { + FuriThreadId thread; /**< Identifier of the thread that will be receiving events. */ + void* context; /**< Pointer to the user-provided context (will be passed to the event callback). */ +} FuriHalNfcEventInternal; + +/** + * @brief NFC HAL global state structure. + */ +typedef struct { + FuriMutex* mutex; /**< Pointer to the mutex serving as global NFC HAL lock. */ + FuriHalNfcMode mode; /**< Currently selected operating mode. */ + FuriHalNfcTech tech; /**< Currently selected NFC technology. */ +} FuriHalNfc; + +/** + * @brief NFC HAL global state object declaration. + */ +extern FuriHalNfc furi_hal_nfc; + +/** + * @brief Initialise NFC HAL event system. + */ +void furi_hal_nfc_event_init(); + +/** + * @brief Forcibly emit (a) particular internal event(s). + * + * @param[in] event bitmask of one or more events to be emitted. + */ +void furi_hal_nfc_event_set(FuriHalNfcEventInternalType event); + +/** + * @brief Initialise GPIO to generate an interrupt from the NFC hardware. + */ +void furi_hal_nfc_init_gpio_isr(); + +/** + * @brief Disable interrupts from the NFC hardware. + */ +void furi_hal_nfc_deinit_gpio_isr(); + +/** + * @brief Initialise all NFC timers. + */ +void furi_hal_nfc_timers_init(); + +/** + * @brief Disable all NFC timers. + */ +void furi_hal_nfc_timers_deinit(); + +/** + * @brief Get the interrupt bitmask from the NFC hardware. + * + * @param[in,out] handle pointer to the SPI handle associated with the NFC chip. + * @returns bitmask of zero or more occurred interrupts. + */ +uint32_t furi_hal_nfc_get_irq(FuriHalSpiBusHandle* handle); + +/** + * @brief Wait until a specified type of interrupt occurs. + * + * @param[in,out] handle pointer to the SPI handle associated with the NFC chip. + * @param[in] mask bitmask of one or more interrupts to wait for. + * @param[in] timeout_ms maximum time to wait for an interrupt, in milliseconds. + * @returns true if specified interrupt(s) have occured within timeout, false otherwise. + */ +bool furi_hal_nfc_event_wait_for_specific_irq( + FuriHalSpiBusHandle* handle, + uint32_t mask, + uint32_t timeout_ms); + +/** + * @brief Wait for any event to occur. + * + * This function is common to all technologies. + * + * @param[in] timeout_ms maximum time to wait for an event, in milliseconds. + * @returns bitmask of zero or more occurred events. + */ +FuriHalNfcEvent furi_hal_nfc_wait_event_common(uint32_t timeout_ms); + +/** + * @brief Start reception in listener mode. + * + * This function is common to all technologies. + * + * @param[in,out] handle pointer to the SPI handle associated with the NFC chip. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_common_listener_rx_start(FuriHalSpiBusHandle* handle); + +/** + * @brief Transmit data using on-chip FIFO. + * + * This function is common to all technologies. + * + * @param[in,out] handle pointer to the SPI handle associated with the NFC chip. + * @param[in] tx_data pointer to a byte array containing the data to be transmitted. + * @param[in] tx_bits transmit data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_common_fifo_tx( + FuriHalSpiBusHandle* handle, + const uint8_t* tx_data, + size_t tx_bits); + +/** + * @brief Receive data using on-chip FIFO. + * + * This function is common to all technologies. + * + * @param[in,out] handle pointer to the SPI handle associated with the NFC chip. + * @param[out] rx_data pointer to a byte array to be filled with received data. + * @param[in] rx_data_size maximum received data size, in bytes. + * @param[out] rx_bits pointer to the variable to contain the received data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_common_fifo_rx( + FuriHalSpiBusHandle* handle, + uint8_t* rx_data, + size_t rx_data_size, + size_t* rx_bits); + +/** + * @brief Transmit data in poller mode. + * + * This function is common to all technologies. + * + * @param[in,out] handle pointer to the SPI handle associated with the NFC chip. + * @param[in] tx_data pointer to a byte array containing the data to be transmitted. + * @param[in] tx_bits transmit data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_poller_tx_common( + FuriHalSpiBusHandle* handle, + const uint8_t* tx_data, + size_t tx_bits); + +#ifdef __cplusplus +} +#endif diff --git a/targets/f7/furi_hal/furi_hal_nfc_irq.c b/targets/f7/furi_hal/furi_hal_nfc_irq.c new file mode 100644 index 000000000..170d8dee6 --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc_irq.c @@ -0,0 +1,28 @@ +#include "furi_hal_nfc_i.h" + +#include +#include + +static void furi_hal_nfc_int_callback() { + furi_hal_nfc_event_set(FuriHalNfcEventInternalTypeIrq); +} + +uint32_t furi_hal_nfc_get_irq(FuriHalSpiBusHandle* handle) { + uint32_t irq = 0; + while(furi_hal_gpio_read_port_pin(gpio_nfc_irq_rfid_pull.port, gpio_nfc_irq_rfid_pull.pin)) { + irq |= st25r3916_get_irq(handle); + } + return irq; +} + +void furi_hal_nfc_init_gpio_isr() { + furi_hal_gpio_init( + &gpio_nfc_irq_rfid_pull, GpioModeInterruptRise, GpioPullDown, GpioSpeedVeryHigh); + furi_hal_gpio_add_int_callback(&gpio_nfc_irq_rfid_pull, furi_hal_nfc_int_callback, NULL); + furi_hal_gpio_enable_int_callback(&gpio_nfc_irq_rfid_pull); +} + +void furi_hal_nfc_deinit_gpio_isr() { + furi_hal_gpio_remove_int_callback(&gpio_nfc_irq_rfid_pull); + furi_hal_gpio_init(&gpio_nfc_irq_rfid_pull, GpioModeAnalog, GpioPullNo, GpioSpeedLow); +} diff --git a/targets/f7/furi_hal/furi_hal_nfc_iso14443a.c b/targets/f7/furi_hal/furi_hal_nfc_iso14443a.c new file mode 100644 index 000000000..278ecf384 --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc_iso14443a.c @@ -0,0 +1,356 @@ +#include "furi_hal_nfc_i.h" +#include "furi_hal_nfc_tech_i.h" + +#include +#include + +#include + +#define TAG "FuriHalIso14443a" + +// Prevent FDT timer from starting +#define FURI_HAL_NFC_ISO14443A_LISTENER_FDT_COMP_FC (INT32_MAX) + +static Iso14443_3aSignal* iso14443_3a_signal = NULL; + +static FuriHalNfcError furi_hal_nfc_iso14443a_common_init(FuriHalSpiBusHandle* handle) { + // Common NFC-A settings, 106 kbps + + // 1st stage zero = 600kHz, 3rd stage zero = 200 kHz + st25r3916_write_reg(handle, ST25R3916_REG_RX_CONF1, ST25R3916_REG_RX_CONF1_z600k); + // AGC enabled, ratio 3:1, squelch after TX + st25r3916_write_reg( + handle, + ST25R3916_REG_RX_CONF2, + ST25R3916_REG_RX_CONF2_agc6_3 | ST25R3916_REG_RX_CONF2_agc_m | + ST25R3916_REG_RX_CONF2_agc_en | ST25R3916_REG_RX_CONF2_sqm_dyn); + // HF operation, full gain on AM and PM channels + st25r3916_write_reg(handle, ST25R3916_REG_RX_CONF3, 0x00); + // No gain reduction on AM and PM channels + st25r3916_write_reg(handle, ST25R3916_REG_RX_CONF4, 0x00); + // Correlator config + st25r3916_write_reg( + handle, + ST25R3916_REG_CORR_CONF1, + ST25R3916_REG_CORR_CONF1_corr_s0 | ST25R3916_REG_CORR_CONF1_corr_s4 | + ST25R3916_REG_CORR_CONF1_corr_s6); + // Sleep mode disable, 424kHz mode off + st25r3916_write_reg(handle, ST25R3916_REG_CORR_CONF2, 0x00); + + return FuriHalNfcErrorNone; +} + +static FuriHalNfcError furi_hal_nfc_iso14443a_poller_init(FuriHalSpiBusHandle* handle) { + // Enable ISO14443A mode, OOK modulation + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_MODE, + ST25R3916_REG_MODE_om_mask | ST25R3916_REG_MODE_tr_am, + ST25R3916_REG_MODE_om_iso14443a | ST25R3916_REG_MODE_tr_am_ook); + + // Overshoot protection - is this necessary here? + st25r3916_change_reg_bits(handle, ST25R3916_REG_OVERSHOOT_CONF1, 0xff, 0x40); + st25r3916_change_reg_bits(handle, ST25R3916_REG_OVERSHOOT_CONF2, 0xff, 0x03); + st25r3916_change_reg_bits(handle, ST25R3916_REG_UNDERSHOOT_CONF1, 0xff, 0x40); + st25r3916_change_reg_bits(handle, ST25R3916_REG_UNDERSHOOT_CONF2, 0xff, 0x03); + + return furi_hal_nfc_iso14443a_common_init(handle); +} + +static FuriHalNfcError furi_hal_nfc_iso14443a_poller_deinit(FuriHalSpiBusHandle* handle) { + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_ISO14443A_NFC, + (ST25R3916_REG_ISO14443A_NFC_no_tx_par | ST25R3916_REG_ISO14443A_NFC_no_rx_par), + (ST25R3916_REG_ISO14443A_NFC_no_tx_par_off | ST25R3916_REG_ISO14443A_NFC_no_rx_par_off)); + + return FuriHalNfcErrorNone; +} + +static FuriHalNfcError furi_hal_nfc_iso14443a_listener_init(FuriHalSpiBusHandle* handle) { + furi_check(iso14443_3a_signal == NULL); + iso14443_3a_signal = iso14443_3a_signal_alloc(&gpio_spi_r_mosi); + + st25r3916_write_reg( + handle, + ST25R3916_REG_OP_CONTROL, + ST25R3916_REG_OP_CONTROL_en | ST25R3916_REG_OP_CONTROL_rx_en | + ST25R3916_REG_OP_CONTROL_en_fd_auto_efd); + st25r3916_write_reg( + handle, ST25R3916_REG_MODE, ST25R3916_REG_MODE_targ_targ | ST25R3916_REG_MODE_om0); + st25r3916_write_reg( + handle, + ST25R3916_REG_PASSIVE_TARGET, + ST25R3916_REG_PASSIVE_TARGET_fdel_2 | ST25R3916_REG_PASSIVE_TARGET_fdel_0 | + ST25R3916_REG_PASSIVE_TARGET_d_ac_ap2p | ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r); + + st25r3916_write_reg(handle, ST25R3916_REG_MASK_RX_TIMER, 0x02); + + st25r3916_direct_cmd(handle, ST25R3916_CMD_STOP); + uint32_t interrupts = + (ST25R3916_IRQ_MASK_FWL | ST25R3916_IRQ_MASK_TXE | ST25R3916_IRQ_MASK_RXS | + ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_CRC | + ST25R3916_IRQ_MASK_ERR1 | ST25R3916_IRQ_MASK_ERR2 | ST25R3916_IRQ_MASK_NRE | + ST25R3916_IRQ_MASK_EON | ST25R3916_IRQ_MASK_EOF | ST25R3916_IRQ_MASK_WU_A_X | + ST25R3916_IRQ_MASK_WU_A); + // Clear interrupts + st25r3916_get_irq(handle); + // Enable interrupts + st25r3916_mask_irq(handle, ~interrupts); + // Enable auto collision resolution + st25r3916_clear_reg_bits( + handle, ST25R3916_REG_PASSIVE_TARGET, ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a); + st25r3916_direct_cmd(handle, ST25R3916_CMD_GOTO_SENSE); + + return furi_hal_nfc_iso14443a_common_init(handle); +} + +static FuriHalNfcError furi_hal_nfc_iso14443a_listener_deinit(FuriHalSpiBusHandle* handle) { + UNUSED(handle); + + if(iso14443_3a_signal) { + iso14443_3a_signal_free(iso14443_3a_signal); + iso14443_3a_signal = NULL; + } + + return FuriHalNfcErrorNone; +} + +static FuriHalNfcEvent furi_hal_nfc_iso14443_3a_listener_wait_event(uint32_t timeout_ms) { + FuriHalNfcEvent event = furi_hal_nfc_wait_event_common(timeout_ms); + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + if(event & FuriHalNfcEventListenerActive) { + st25r3916_set_reg_bits( + handle, ST25R3916_REG_PASSIVE_TARGET, ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a); + } + + return event; +} + +FuriHalNfcError furi_hal_nfc_iso14443a_poller_trx_short_frame(FuriHalNfcaShortFrame frame) { + FuriHalNfcError error = FuriHalNfcErrorNone; + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + // Disable crc check + st25r3916_set_reg_bits(handle, ST25R3916_REG_AUX, ST25R3916_REG_AUX_no_crc_rx); + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_ISO14443A_NFC, + (ST25R3916_REG_ISO14443A_NFC_no_tx_par | ST25R3916_REG_ISO14443A_NFC_no_rx_par), + (ST25R3916_REG_ISO14443A_NFC_no_tx_par_off | ST25R3916_REG_ISO14443A_NFC_no_rx_par_off)); + + st25r3916_write_reg(handle, ST25R3916_REG_NUM_TX_BYTES2, 0); + uint32_t interrupts = + (ST25R3916_IRQ_MASK_FWL | ST25R3916_IRQ_MASK_TXE | ST25R3916_IRQ_MASK_RXS | + ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_CRC | + ST25R3916_IRQ_MASK_ERR1 | ST25R3916_IRQ_MASK_ERR2 | ST25R3916_IRQ_MASK_NRE); + // Clear interrupts + st25r3916_get_irq(handle); + // Enable interrupts + st25r3916_mask_irq(handle, ~interrupts); + if(frame == FuriHalNfcaShortFrameAllReq) { + st25r3916_direct_cmd(handle, ST25R3916_CMD_TRANSMIT_REQA); + } else { + st25r3916_direct_cmd(handle, ST25R3916_CMD_TRANSMIT_WUPA); + } + + return error; +} + +FuriHalNfcError furi_hal_nfc_iso14443a_tx_sdd_frame(const uint8_t* tx_data, size_t tx_bits) { + FuriHalNfcError error = FuriHalNfcErrorNone; + // No anticollision is supported in this version of library + error = furi_hal_nfc_poller_tx(tx_data, tx_bits); + + return error; +} + +FuriHalNfcError + furi_hal_nfc_iso14443a_rx_sdd_frame(uint8_t* rx_data, size_t rx_data_size, size_t* rx_bits) { + FuriHalNfcError error = FuriHalNfcErrorNone; + UNUSED(rx_data); + UNUSED(rx_bits); + UNUSED(rx_data_size); + + error = furi_hal_nfc_poller_rx(rx_data, rx_data_size, rx_bits); + // No anticollision is supported in this version of library + + return error; +} + +FuriHalNfcError + furi_hal_nfc_iso14443a_poller_tx_custom_parity(const uint8_t* tx_data, size_t tx_bits) { + furi_assert(tx_data); + + FuriHalNfcError err = FuriHalNfcErrorNone; + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + // Prepare tx + st25r3916_direct_cmd(handle, ST25R3916_CMD_CLEAR_FIFO); + st25r3916_clear_reg_bits( + handle, ST25R3916_REG_TIMER_EMV_CONTROL, ST25R3916_REG_TIMER_EMV_CONTROL_nrt_emv); + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_ISO14443A_NFC, + (ST25R3916_REG_ISO14443A_NFC_no_tx_par | ST25R3916_REG_ISO14443A_NFC_no_rx_par), + (ST25R3916_REG_ISO14443A_NFC_no_tx_par | ST25R3916_REG_ISO14443A_NFC_no_rx_par)); + uint32_t interrupts = + (ST25R3916_IRQ_MASK_FWL | ST25R3916_IRQ_MASK_TXE | ST25R3916_IRQ_MASK_RXS | + ST25R3916_IRQ_MASK_RXE | ST25R3916_IRQ_MASK_PAR | ST25R3916_IRQ_MASK_CRC | + ST25R3916_IRQ_MASK_ERR1 | ST25R3916_IRQ_MASK_ERR2 | ST25R3916_IRQ_MASK_NRE); + // Clear interrupts + st25r3916_get_irq(handle); + // Enable interrupts + st25r3916_mask_irq(handle, ~interrupts); + + st25r3916_write_fifo(handle, tx_data, tx_bits); + st25r3916_direct_cmd(handle, ST25R3916_CMD_TRANSMIT_WITHOUT_CRC); + return err; +} + +FuriHalNfcError furi_hal_nfc_iso14443a_listener_set_col_res_data( + uint8_t* uid, + uint8_t uid_len, + uint8_t* atqa, + uint8_t sak) { + furi_assert(uid); + furi_assert(atqa); + UNUSED(uid_len); + UNUSED(sak); + FuriHalNfcError error = FuriHalNfcErrorNone; + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + // Set 4 or 7 bytes UID + if(uid_len == 4) { + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_AUX, + ST25R3916_REG_AUX_nfc_id_mask, + ST25R3916_REG_AUX_nfc_id_4bytes); + } else { + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_AUX, + ST25R3916_REG_AUX_nfc_id_mask, + ST25R3916_REG_AUX_nfc_id_7bytes); + } + // Write PT Memory + uint8_t pt_memory[15] = {}; + memcpy(pt_memory, uid, uid_len); + pt_memory[10] = atqa[0]; + pt_memory[11] = atqa[1]; + if(uid_len == 4) { + pt_memory[12] = sak & ~0x04; + } else { + pt_memory[12] = 0x04; + } + pt_memory[13] = sak & ~0x04; + pt_memory[14] = sak & ~0x04; + + st25r3916_write_pta_mem(handle, pt_memory, sizeof(pt_memory)); + + return error; +} + +FuriHalNfcError furi_hal_nfc_iso4443a_listener_tx( + FuriHalSpiBusHandle* handle, + const uint8_t* tx_data, + size_t tx_bits) { + FuriHalNfcError error = FuriHalNfcErrorNone; + + do { + error = furi_hal_nfc_common_fifo_tx(handle, tx_data, tx_bits); + if(error != FuriHalNfcErrorNone) break; + + bool tx_end = furi_hal_nfc_event_wait_for_specific_irq(handle, ST25R3916_IRQ_MASK_TXE, 10); + if(!tx_end) { + error = FuriHalNfcErrorCommunicationTimeout; + break; + } + + } while(false); + + return error; +} + +FuriHalNfcError furi_hal_nfc_iso14443a_listener_tx_custom_parity( + const uint8_t* tx_data, + const uint8_t* tx_parity, + size_t tx_bits) { + furi_assert(tx_data); + furi_assert(tx_parity); + + furi_assert(iso14443_3a_signal); + + FuriHalSpiBusHandle* handle = &furi_hal_spi_bus_handle_nfc; + + st25r3916_direct_cmd(handle, ST25R3916_CMD_TRANSPARENT_MODE); + // Reconfigure gpio for Transparent mode + furi_hal_spi_bus_handle_deinit(&furi_hal_spi_bus_handle_nfc); + + // Send signal + iso14443_3a_signal_tx(iso14443_3a_signal, tx_data, tx_parity, tx_bits); + + // Exit transparent mode + furi_hal_gpio_write(&gpio_spi_r_mosi, false); + + // Configure gpio back to SPI and exit transparent + furi_hal_spi_bus_handle_init(&furi_hal_spi_bus_handle_nfc); + st25r3916_direct_cmd(handle, ST25R3916_CMD_UNMASK_RECEIVE_DATA); + + return FuriHalNfcErrorNone; +} + +FuriHalNfcError furi_hal_nfc_iso14443_3a_listener_sleep(FuriHalSpiBusHandle* handle) { + // Enable auto collision resolution + st25r3916_clear_reg_bits( + handle, ST25R3916_REG_PASSIVE_TARGET, ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a); + st25r3916_direct_cmd(handle, ST25R3916_CMD_STOP); + st25r3916_direct_cmd(handle, ST25R3916_CMD_GOTO_SLEEP); + + return FuriHalNfcErrorNone; +} + +FuriHalNfcError furi_hal_nfc_iso14443_3a_listener_idle(FuriHalSpiBusHandle* handle) { + // Enable auto collision resolution + st25r3916_clear_reg_bits( + handle, ST25R3916_REG_PASSIVE_TARGET, ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a); + st25r3916_direct_cmd(handle, ST25R3916_CMD_STOP); + st25r3916_direct_cmd(handle, ST25R3916_CMD_GOTO_SENSE); + + return FuriHalNfcErrorNone; +} + +const FuriHalNfcTechBase furi_hal_nfc_iso14443a = { + .poller = + { + .compensation = + { + .fdt = FURI_HAL_NFC_POLLER_FDT_COMP_FC, + .fwt = FURI_HAL_NFC_POLLER_FWT_COMP_FC, + }, + .init = furi_hal_nfc_iso14443a_poller_init, + .deinit = furi_hal_nfc_iso14443a_poller_deinit, + .wait_event = furi_hal_nfc_wait_event_common, + .tx = furi_hal_nfc_poller_tx_common, + .rx = furi_hal_nfc_common_fifo_rx, + }, + + .listener = + { + .compensation = + { + .fdt = FURI_HAL_NFC_ISO14443A_LISTENER_FDT_COMP_FC, + }, + .init = furi_hal_nfc_iso14443a_listener_init, + .deinit = furi_hal_nfc_iso14443a_listener_deinit, + .wait_event = furi_hal_nfc_iso14443_3a_listener_wait_event, + .tx = furi_hal_nfc_iso4443a_listener_tx, + .rx = furi_hal_nfc_common_fifo_rx, + .sleep = furi_hal_nfc_iso14443_3a_listener_sleep, + .idle = furi_hal_nfc_iso14443_3a_listener_idle, + }, +}; diff --git a/targets/f7/furi_hal/furi_hal_nfc_iso14443b.c b/targets/f7/furi_hal/furi_hal_nfc_iso14443b.c new file mode 100644 index 000000000..bb1a63515 --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc_iso14443b.c @@ -0,0 +1,108 @@ +#include "furi_hal_nfc_i.h" +#include "furi_hal_nfc_tech_i.h" + +static FuriHalNfcError furi_hal_nfc_iso14443b_common_init(FuriHalSpiBusHandle* handle) { + // Common NFC-B settings, 106kbps + + // 1st stage zero = 60kHz, 3rd stage zero = 200 kHz + st25r3916_write_reg(handle, ST25R3916_REG_RX_CONF1, ST25R3916_REG_RX_CONF1_h200); + + // Enable AGC + // AGC Ratio 6 + // AGC algorithm with RESET (recommended for ISO14443-B) + // AGC operation during complete receive period + // Squelch ratio 6/3 (recommended for ISO14443-B) + // Squelch automatic activation on TX end + st25r3916_write_reg( + handle, + ST25R3916_REG_RX_CONF2, + ST25R3916_REG_RX_CONF2_agc6_3 | ST25R3916_REG_RX_CONF2_agc_alg | + ST25R3916_REG_RX_CONF2_agc_m | ST25R3916_REG_RX_CONF2_agc_en | + ST25R3916_REG_RX_CONF2_pulz_61 | ST25R3916_REG_RX_CONF2_sqm_dyn); + + // HF operation, full gain on AM and PM channels + st25r3916_write_reg(handle, ST25R3916_REG_RX_CONF3, 0x00); + // No gain reduction on AM and PM channels + st25r3916_write_reg(handle, ST25R3916_REG_RX_CONF4, 0x00); + + // Subcarrier end detector enabled + // Subcarrier end detection level = 66% + // BPSK start 33 pilot pulses + // AM & PM summation before digitizing on + st25r3916_write_reg( + handle, + ST25R3916_REG_CORR_CONF1, + ST25R3916_REG_CORR_CONF1_corr_s0 | ST25R3916_REG_CORR_CONF1_corr_s1 | + ST25R3916_REG_CORR_CONF1_corr_s3 | ST25R3916_REG_CORR_CONF1_corr_s4); + // Sleep mode disable, 424kHz mode off + st25r3916_write_reg(handle, ST25R3916_REG_CORR_CONF2, 0x00); + + return FuriHalNfcErrorNone; +} + +static FuriHalNfcError furi_hal_nfc_iso14443b_poller_init(FuriHalSpiBusHandle* handle) { + // Enable ISO14443B mode, AM modulation + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_MODE, + ST25R3916_REG_MODE_om_mask | ST25R3916_REG_MODE_tr_am, + ST25R3916_REG_MODE_om_iso14443b | ST25R3916_REG_MODE_tr_am_am); + + // 10% ASK modulation + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_TX_DRIVER, + ST25R3916_REG_TX_DRIVER_am_mod_mask, + ST25R3916_REG_TX_DRIVER_am_mod_10percent); + + // Use regulator AM, resistive AM disabled + st25r3916_clear_reg_bits( + handle, + ST25R3916_REG_AUX_MOD, + ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am); + + // EGT = 0 etu + // SOF = 10 etu LOW + 2 etu HIGH + // EOF = 10 etu + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_ISO14443B_1, + ST25R3916_REG_ISO14443B_1_egt_mask | ST25R3916_REG_ISO14443B_1_sof_mask | + ST25R3916_REG_ISO14443B_1_eof, + (0U << ST25R3916_REG_ISO14443B_1_egt_shift) | ST25R3916_REG_ISO14443B_1_sof_0_10etu | + ST25R3916_REG_ISO14443B_1_sof_1_2etu | ST25R3916_REG_ISO14443B_1_eof_10etu); + + // TR1 = 80 / fs + // B' mode off (no_sof & no_eof = 0) + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_ISO14443B_2, + ST25R3916_REG_ISO14443B_2_tr1_mask | ST25R3916_REG_ISO14443B_2_no_sof | + ST25R3916_REG_ISO14443B_2_no_eof, + ST25R3916_REG_ISO14443B_2_tr1_80fs80fs); + + return furi_hal_nfc_iso14443b_common_init(handle); +} + +static FuriHalNfcError furi_hal_nfc_iso14443b_poller_deinit(FuriHalSpiBusHandle* handle) { + UNUSED(handle); + return FuriHalNfcErrorNone; +} + +const FuriHalNfcTechBase furi_hal_nfc_iso14443b = { + .poller = + { + .compensation = + { + .fdt = FURI_HAL_NFC_POLLER_FDT_COMP_FC, + .fwt = FURI_HAL_NFC_POLLER_FWT_COMP_FC, + }, + .init = furi_hal_nfc_iso14443b_poller_init, + .deinit = furi_hal_nfc_iso14443b_poller_deinit, + .wait_event = furi_hal_nfc_wait_event_common, + .tx = furi_hal_nfc_poller_tx_common, + .rx = furi_hal_nfc_common_fifo_rx, + }, + + .listener = {}, +}; diff --git a/targets/f7/furi_hal/furi_hal_nfc_iso15693.c b/targets/f7/furi_hal/furi_hal_nfc_iso15693.c new file mode 100644 index 000000000..cc936644b --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc_iso15693.c @@ -0,0 +1,463 @@ +#include "furi_hal_nfc_i.h" +#include "furi_hal_nfc_tech_i.h" + +#include +#include + +#include + +#define FURI_HAL_NFC_ISO15693_MAX_FRAME_SIZE (1024U) +#define FURI_HAL_NFC_ISO15693_POLLER_MAX_BUFFER_SIZE (64) + +#define FURI_HAL_NFC_ISO15693_RESP_SOF_SIZE (5) +#define FURI_HAL_NFC_ISO15693_RESP_EOF_SIZE (5) +#define FURI_HAL_NFC_ISO15693_RESP_SOF_MASK (0x1FU) +#define FURI_HAL_NFC_ISO15693_RESP_SOF_PATTERN (0x17U) +#define FURI_HAL_NFC_ISO15693_RESP_EOF_PATTERN (0x1DU) + +#define FURI_HAL_NFC_ISO15693_RESP_PATTERN_MASK (0x03U) +#define FURI_HAL_NFC_ISO15693_RESP_PATTERN_0 (0x01U) +#define FURI_HAL_NFC_ISO15693_RESP_PATTERN_1 (0x02U) + +// Derived experimentally +#define FURI_HAL_NFC_ISO15693_POLLER_FWT_COMP_FC (-1300) +#define FURI_HAL_NFC_ISO15693_LISTENER_FDT_COMP_FC (2850) + +#define BITS_IN_BYTE (8U) + +#define TAG "FuriHalIso15693" + +typedef struct { + Iso15693Signal* signal; + Iso15693Parser* parser; +} FuriHalNfcIso15693Listener; + +typedef struct { + // 4 bits per data bit on transmit + uint8_t fifo_buf[FURI_HAL_NFC_ISO15693_POLLER_MAX_BUFFER_SIZE * 4]; + size_t fifo_buf_bits; + uint8_t frame_buf[FURI_HAL_NFC_ISO15693_POLLER_MAX_BUFFER_SIZE * 2]; + size_t frame_buf_bits; +} FuriHalNfcIso15693Poller; + +static FuriHalNfcIso15693Listener* furi_hal_nfc_iso15693_listener = NULL; +static FuriHalNfcIso15693Poller* furi_hal_nfc_iso15693_poller = NULL; + +static FuriHalNfcIso15693Listener* furi_hal_nfc_iso15693_listener_alloc() { + FuriHalNfcIso15693Listener* instance = malloc(sizeof(FuriHalNfcIso15693Listener)); + + instance->signal = iso15693_signal_alloc(&gpio_spi_r_mosi); + instance->parser = + iso15693_parser_alloc(&gpio_nfc_irq_rfid_pull, FURI_HAL_NFC_ISO15693_MAX_FRAME_SIZE); + + return instance; +} + +static void furi_hal_nfc_iso15693_listener_free(FuriHalNfcIso15693Listener* instance) { + furi_assert(instance); + + iso15693_signal_free(instance->signal); + iso15693_parser_free(instance->parser); + + free(instance); +} + +static FuriHalNfcIso15693Poller* furi_hal_nfc_iso15693_poller_alloc() { + FuriHalNfcIso15693Poller* instance = malloc(sizeof(FuriHalNfcIso15693Poller)); + + return instance; +} + +static void furi_hal_nfc_iso15693_poller_free(FuriHalNfcIso15693Poller* instance) { + furi_assert(instance); + + free(instance); +} + +static FuriHalNfcError furi_hal_nfc_iso15693_common_init(FuriHalSpiBusHandle* handle) { + // Common NFC-V settings, 26.48 kbps + + // 1st stage zero = 12 kHz, 3rd stage zero = 80 kHz, low-pass = 600 kHz + st25r3916_write_reg( + handle, + ST25R3916_REG_RX_CONF1, + ST25R3916_REG_RX_CONF1_z12k | ST25R3916_REG_RX_CONF1_h80 | + ST25R3916_REG_RX_CONF1_lp_600khz); + + // Enable AGC + // AGC Ratio 6 + // AGC algorithm with RESET (recommended for ISO15693) + // AGC operation during complete receive period + // Squelch automatic activation on TX end + st25r3916_write_reg( + handle, + ST25R3916_REG_RX_CONF2, + ST25R3916_REG_RX_CONF2_agc6_3 | ST25R3916_REG_RX_CONF2_agc_m | + ST25R3916_REG_RX_CONF2_agc_en | ST25R3916_REG_RX_CONF2_sqm_dyn); + + // HF operation, full gain on AM and PM channels + st25r3916_write_reg(handle, ST25R3916_REG_RX_CONF3, 0x00); + // No gain reduction on AM and PM channels + st25r3916_write_reg(handle, ST25R3916_REG_RX_CONF4, 0x00); + + // Collision detection level 53% + // AM & PM summation before digitizing on + st25r3916_write_reg( + handle, + ST25R3916_REG_CORR_CONF1, + ST25R3916_REG_CORR_CONF1_corr_s0 | ST25R3916_REG_CORR_CONF1_corr_s1 | + ST25R3916_REG_CORR_CONF1_corr_s4); + // 424 kHz subcarrier stream mode on + st25r3916_write_reg(handle, ST25R3916_REG_CORR_CONF2, ST25R3916_REG_CORR_CONF2_corr_s8); + return FuriHalNfcErrorNone; +} + +static FuriHalNfcError furi_hal_nfc_iso15693_poller_init(FuriHalSpiBusHandle* handle) { + furi_assert(furi_hal_nfc_iso15693_poller == NULL); + + furi_hal_nfc_iso15693_poller = furi_hal_nfc_iso15693_poller_alloc(); + + // Enable Subcarrier Stream mode, OOK modulation + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_MODE, + ST25R3916_REG_MODE_om_mask | ST25R3916_REG_MODE_tr_am, + ST25R3916_REG_MODE_om_subcarrier_stream | ST25R3916_REG_MODE_tr_am_ook); + + // Subcarrier 424 kHz mode + // 8 sub-carrier pulses in report period + st25r3916_write_reg( + handle, + ST25R3916_REG_STREAM_MODE, + ST25R3916_REG_STREAM_MODE_scf_sc424 | ST25R3916_REG_STREAM_MODE_stx_106 | + ST25R3916_REG_STREAM_MODE_scp_8pulses); + + // Use regulator AM, resistive AM disabled + st25r3916_clear_reg_bits( + handle, + ST25R3916_REG_AUX_MOD, + ST25R3916_REG_AUX_MOD_dis_reg_am | ST25R3916_REG_AUX_MOD_res_am); + + return furi_hal_nfc_iso15693_common_init(handle); +} + +static FuriHalNfcError furi_hal_nfc_iso15693_poller_deinit(FuriHalSpiBusHandle* handle) { + UNUSED(handle); + furi_assert(furi_hal_nfc_iso15693_poller); + + furi_hal_nfc_iso15693_poller_free(furi_hal_nfc_iso15693_poller); + furi_hal_nfc_iso15693_poller = NULL; + + return FuriHalNfcErrorNone; +} + +static void iso15693_3_poller_encode_frame( + const uint8_t* tx_data, + size_t tx_bits, + uint8_t* frame_buf, + size_t frame_buf_size, + size_t* frame_buf_bits) { + static const uint8_t bit_patterns_1_out_of_4[] = {0x02, 0x08, 0x20, 0x80}; + size_t frame_buf_size_calc = (tx_bits / 2) + 2; + furi_assert(frame_buf_size >= frame_buf_size_calc); + + // Add SOF 1 out of 4 + frame_buf[0] = 0x21; + + size_t byte_pos = 1; + for(size_t i = 0; i < tx_bits / BITS_IN_BYTE; ++i) { + for(size_t j = 0; j < BITS_IN_BYTE; j += (BITS_IN_BYTE) / 4) { + const uint8_t bit_pair = (tx_data[i] >> j) & 0x03; + frame_buf[byte_pos++] = bit_patterns_1_out_of_4[bit_pair]; + } + } + // Add EOF + frame_buf[byte_pos++] = 0x04; + *frame_buf_bits = byte_pos * BITS_IN_BYTE; +} + +static FuriHalNfcError iso15693_3_poller_decode_frame( + const uint8_t* buf, + size_t buf_bits, + uint8_t* buf_decoded, + size_t buf_decoded_size, + size_t* buf_decoded_bits) { + FuriHalNfcError ret = FuriHalNfcErrorDataFormat; + size_t bit_pos = 0; + memset(buf_decoded, 0, buf_decoded_size); + + do { + if(buf_bits == 0) break; + // Check SOF + if((buf[0] & FURI_HAL_NFC_ISO15693_RESP_SOF_MASK) != + FURI_HAL_NFC_ISO15693_RESP_SOF_PATTERN) + break; + + if(buf_bits == BITS_IN_BYTE) { + ret = FuriHalNfcErrorIncompleteFrame; + break; + } + + // 2 response bits = 1 data bit + for(uint32_t i = FURI_HAL_NFC_ISO15693_RESP_SOF_SIZE; + i < buf_bits - FURI_HAL_NFC_ISO15693_RESP_SOF_SIZE; + i += BITS_IN_BYTE / 4) { + const size_t byte_index = i / BITS_IN_BYTE; + const size_t bit_offset = i % BITS_IN_BYTE; + const uint8_t resp_byte = (buf[byte_index] >> bit_offset) | + (buf[byte_index + 1] << (BITS_IN_BYTE - bit_offset)); + + // Check EOF + if(resp_byte == FURI_HAL_NFC_ISO15693_RESP_EOF_PATTERN) { + ret = FuriHalNfcErrorNone; + break; + } + + const uint8_t bit_pattern = resp_byte & FURI_HAL_NFC_ISO15693_RESP_PATTERN_MASK; + + if(bit_pattern == FURI_HAL_NFC_ISO15693_RESP_PATTERN_0) { + bit_pos++; + } else if(bit_pattern == FURI_HAL_NFC_ISO15693_RESP_PATTERN_1) { + buf_decoded[bit_pos / BITS_IN_BYTE] |= 1 << (bit_pos % BITS_IN_BYTE); + bit_pos++; + } else { + break; + } + if(bit_pos / BITS_IN_BYTE > buf_decoded_size) { + break; + } + } + + } while(false); + + if(ret == FuriHalNfcErrorNone) { + *buf_decoded_bits = bit_pos; + } + + return ret; +} + +static FuriHalNfcError furi_hal_nfc_iso15693_poller_tx( + FuriHalSpiBusHandle* handle, + const uint8_t* tx_data, + size_t tx_bits) { + FuriHalNfcIso15693Poller* instance = furi_hal_nfc_iso15693_poller; + iso15693_3_poller_encode_frame( + tx_data, + tx_bits, + instance->frame_buf, + sizeof(instance->frame_buf), + &instance->frame_buf_bits); + return furi_hal_nfc_poller_tx_common(handle, instance->frame_buf, instance->frame_buf_bits); +} + +static FuriHalNfcError furi_hal_nfc_iso15693_poller_rx( + FuriHalSpiBusHandle* handle, + uint8_t* rx_data, + size_t rx_data_size, + size_t* rx_bits) { + FuriHalNfcError error = FuriHalNfcErrorNone; + FuriHalNfcIso15693Poller* instance = furi_hal_nfc_iso15693_poller; + + do { + error = furi_hal_nfc_common_fifo_rx( + handle, instance->fifo_buf, sizeof(instance->fifo_buf), &instance->fifo_buf_bits); + if(error != FuriHalNfcErrorNone) break; + + error = iso15693_3_poller_decode_frame( + instance->fifo_buf, + instance->fifo_buf_bits, + instance->frame_buf, + sizeof(instance->frame_buf), + &instance->frame_buf_bits); + if(error != FuriHalNfcErrorNone) break; + + if(rx_data_size < instance->frame_buf_bits / BITS_IN_BYTE) { + error = FuriHalNfcErrorBufferOverflow; + break; + } + + memcpy(rx_data, instance->frame_buf, instance->frame_buf_bits / BITS_IN_BYTE); + *rx_bits = instance->frame_buf_bits; + } while(false); + + return error; +} + +static void furi_hal_nfc_iso15693_listener_transparent_mode_enter(FuriHalSpiBusHandle* handle) { + st25r3916_direct_cmd(handle, ST25R3916_CMD_TRANSPARENT_MODE); + + furi_hal_spi_bus_handle_deinit(handle); + furi_hal_nfc_deinit_gpio_isr(); +} + +static void furi_hal_nfc_iso15693_listener_transparent_mode_exit(FuriHalSpiBusHandle* handle) { + // Configure gpio back to SPI and exit transparent mode + furi_hal_nfc_init_gpio_isr(); + furi_hal_spi_bus_handle_init(handle); + + st25r3916_direct_cmd(handle, ST25R3916_CMD_UNMASK_RECEIVE_DATA); +} + +static FuriHalNfcError furi_hal_nfc_iso15693_listener_init(FuriHalSpiBusHandle* handle) { + furi_assert(furi_hal_nfc_iso15693_listener == NULL); + + furi_hal_nfc_iso15693_listener = furi_hal_nfc_iso15693_listener_alloc(); + + // Set default operation mode + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_MODE, + ST25R3916_REG_MODE_om_mask | ST25R3916_REG_MODE_tr_am, + ST25R3916_REG_MODE_om_targ_nfca | ST25R3916_REG_MODE_tr_am_ook); + + st25r3916_change_reg_bits( + handle, + ST25R3916_REG_OP_CONTROL, + ST25R3916_REG_OP_CONTROL_rx_en, + ST25R3916_REG_OP_CONTROL_rx_en); + + // Enable passive target mode + st25r3916_change_reg_bits( + handle, ST25R3916_REG_MODE, ST25R3916_REG_MODE_targ, ST25R3916_REG_MODE_targ_targ); + + FuriHalNfcError error = furi_hal_nfc_iso15693_common_init(handle); + + furi_hal_nfc_iso15693_listener_transparent_mode_enter(handle); + + return error; +} + +static FuriHalNfcError furi_hal_nfc_iso15693_listener_deinit(FuriHalSpiBusHandle* handle) { + furi_assert(furi_hal_nfc_iso15693_listener); + + furi_hal_nfc_iso15693_listener_transparent_mode_exit(handle); + + furi_hal_nfc_iso15693_listener_free(furi_hal_nfc_iso15693_listener); + furi_hal_nfc_iso15693_listener = NULL; + + return FuriHalNfcErrorNone; +} + +static FuriHalNfcError + furi_hal_nfc_iso15693_listener_tx_transparent(const uint8_t* data, size_t data_size) { + iso15693_signal_tx( + furi_hal_nfc_iso15693_listener->signal, Iso15693SignalDataRateHi, data, data_size); + + return FuriHalNfcErrorNone; +} + +static void furi_hal_nfc_iso15693_parser_callback(Iso15693ParserEvent event, void* context) { + furi_assert(context); + + if(event == Iso15693ParserEventDataReceived) { + FuriThreadId thread_id = context; + furi_thread_flags_set(thread_id, FuriHalNfcEventInternalTypeTransparentDataReceived); + } +} + +static FuriHalNfcEvent furi_hal_nfc_iso15693_wait_event(uint32_t timeout_ms) { + FuriHalNfcEvent event = 0; + + FuriThreadId thread_id = furi_thread_get_current_id(); + iso15693_parser_start( + furi_hal_nfc_iso15693_listener->parser, furi_hal_nfc_iso15693_parser_callback, thread_id); + + while(true) { + uint32_t flag = furi_thread_flags_wait( + FuriHalNfcEventInternalTypeAbort | FuriHalNfcEventInternalTypeTransparentDataReceived, + FuriFlagWaitAny, + timeout_ms); + furi_thread_flags_clear(flag); + + if(flag & FuriHalNfcEventInternalTypeAbort) { + event = FuriHalNfcEventAbortRequest; + break; + } + if(flag & FuriHalNfcEventInternalTypeTransparentDataReceived) { + if(iso15693_parser_run(furi_hal_nfc_iso15693_listener->parser)) { + event = FuriHalNfcEventRxEnd; + break; + } + } + } + iso15693_parser_stop(furi_hal_nfc_iso15693_listener->parser); + + return event; +} + +static FuriHalNfcError furi_hal_nfc_iso15693_listener_tx( + FuriHalSpiBusHandle* handle, + const uint8_t* tx_data, + size_t tx_bits) { + UNUSED(handle); + furi_assert(furi_hal_nfc_iso15693_listener); + + FuriHalNfcError error = FuriHalNfcErrorNone; + + error = furi_hal_nfc_iso15693_listener_tx_transparent(tx_data, tx_bits / BITS_IN_BYTE); + + return error; +} + +FuriHalNfcError furi_hal_nfc_iso15693_listener_tx_sof() { + iso15693_signal_tx_sof(furi_hal_nfc_iso15693_listener->signal, Iso15693SignalDataRateHi); + + return FuriHalNfcErrorNone; +} + +static FuriHalNfcError furi_hal_nfc_iso15693_listener_rx( + FuriHalSpiBusHandle* handle, + uint8_t* rx_data, + size_t rx_data_size, + size_t* rx_bits) { + furi_assert(furi_hal_nfc_iso15693_listener); + UNUSED(handle); + + if(rx_data_size < + iso15693_parser_get_data_size_bytes(furi_hal_nfc_iso15693_listener->parser)) { + return FuriHalNfcErrorBufferOverflow; + } + + iso15693_parser_get_data( + furi_hal_nfc_iso15693_listener->parser, rx_data, rx_data_size, rx_bits); + + return FuriHalNfcErrorNone; +} + +FuriHalNfcError furi_hal_nfc_iso15693_listener_sleep(FuriHalSpiBusHandle* handle) { + UNUSED(handle); + + return FuriHalNfcErrorNone; +} + +const FuriHalNfcTechBase furi_hal_nfc_iso15693 = { + .poller = + { + .compensation = + { + .fdt = FURI_HAL_NFC_POLLER_FDT_COMP_FC, + .fwt = FURI_HAL_NFC_ISO15693_POLLER_FWT_COMP_FC, + }, + .init = furi_hal_nfc_iso15693_poller_init, + .deinit = furi_hal_nfc_iso15693_poller_deinit, + .wait_event = furi_hal_nfc_wait_event_common, + .tx = furi_hal_nfc_iso15693_poller_tx, + .rx = furi_hal_nfc_iso15693_poller_rx, + }, + + .listener = + { + .compensation = + { + .fdt = FURI_HAL_NFC_ISO15693_LISTENER_FDT_COMP_FC, + }, + .init = furi_hal_nfc_iso15693_listener_init, + .deinit = furi_hal_nfc_iso15693_listener_deinit, + .wait_event = furi_hal_nfc_iso15693_wait_event, + .tx = furi_hal_nfc_iso15693_listener_tx, + .rx = furi_hal_nfc_iso15693_listener_rx, + .sleep = furi_hal_nfc_iso15693_listener_sleep, + .idle = furi_hal_nfc_iso15693_listener_sleep, + }, +}; diff --git a/targets/f7/furi_hal/furi_hal_nfc_tech_i.h b/targets/f7/furi_hal/furi_hal_nfc_tech_i.h new file mode 100644 index 000000000..e36dc852e --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc_tech_i.h @@ -0,0 +1,167 @@ +/** + * @file furi_hal_nfc_tech_i.h + * @brief NFC HAL technology-related private definitions. + * + * This file is an implementation detail. It must not be included in + * any public API-related headers. + * + * This file is to be changed in an unlikely event of adding support + * for a new NFC technology. + */ +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Configure the NFC chip for use with this technology. + * + * Used for init() and deinit() functions. + * + * @param[in,out] handle pointer to the NFC chip SPI handle. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +typedef FuriHalNfcError (*FuriHalNfcChipConfig)(FuriHalSpiBusHandle* handle); + +/** + * @brief Transmit data using technology-specific framing and timings. + * + * @param[in,out] handle pointer to the NFC chip SPI handle. + * @param[in] tx_data pointer to a byte array containing the data to be transmitted. + * @param[in] tx_bits transmit data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +typedef FuriHalNfcError ( + *FuriHalNfcTx)(FuriHalSpiBusHandle* handle, const uint8_t* tx_data, size_t tx_bits); + +/** + * @brief Receive data using technology-specific framing and timings. + * + * @param[in,out] handle pointer to the NFC chip SPI handle. + * @param[out] rx_data pointer to a byte array to be filled with received data. + * @param[in] rx_data_size maximum received data length, in bytes. + * @param[out] rx_bits pointer to a variable to contain received data length, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +typedef FuriHalNfcError (*FuriHalNfcRx)( + FuriHalSpiBusHandle* handle, + uint8_t* rx_data, + size_t rx_data_size, + size_t* rx_bits); + +/** + * @brief Wait for an event using technology-specific method. + * + * @param[in] timeout_ms maximum time to wait, in milliseconds. + * @return bitmask of occurred events. + */ +typedef FuriHalNfcEvent (*FuriHalNfcWaitEvent)(uint32_t timeout_ms); + +/** + * @brief Go to sleep in listener mode. + * + * Puts the passive target logic into Sleep (Halt) state. + * + * @param[in,out] handle pointer to the NFC chip SPI handle. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +typedef FuriHalNfcError (*FuriHalNfcSleep)(FuriHalSpiBusHandle* handle); + +/** + * @brief Go to idle in listener mode. + * + * Puts the passive target logic into Sense (Idle) state. + * + * @param[in,out] handle pointer to the NFC chip SPI handle. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +typedef FuriHalNfcError (*FuriHalNfcIdle)(FuriHalSpiBusHandle* handle); + +/** + * @brief Technology-specific compenstaion values for pollers. + * + * Timing compensations are needed due to execution delays not accounted for + * in standards, they are usually found out experimentally. + * + * The compensation value will be subtracted from the respective timer running + * time, so positive values shorten timeouts, and negative ones make them longer. + */ +typedef struct { + int32_t fdt; /**< Frame delay time compensation, in carrier cycles. */ + int32_t fwt; /**< Frame wait time compensaton, in carrier cycles. */ +} FuriHalNfcPollerCompensation; + +/** + * @brief Abstract technology-specific poller structure. + */ +typedef struct { + FuriHalNfcPollerCompensation compensation; /**< Compensation values in poller mode. */ + FuriHalNfcChipConfig init; /**< Pointer to the init() function. */ + FuriHalNfcChipConfig deinit; /**< Pointer to the deinit() function. */ + FuriHalNfcWaitEvent wait_event; /**< Pointer to the wait_event() function. */ + FuriHalNfcTx tx; /**< Pointer to the tx() function. */ + FuriHalNfcRx rx; /**< Pointer to the rx() function. */ +} FuriHalNfcTechPollerBase; + +/** + * @brief Technology-specific compenstaion values for listeners. + * + * Same considerations apply as with FuriHalNfcPollerCompensation. + */ +typedef struct { + int32_t fdt; /**< Frame delay time compensation, in carrier cycles. */ +} FuriHalNfcListenerCompensation; + +/** + * @brief Abstract technology-specific listener structure. + * + * If the listener operating mode is not supported for a particular + * technology, fill this structure with zeroes. + */ +typedef struct { + FuriHalNfcListenerCompensation compensation; /**< Compensation values in listener mode. */ + FuriHalNfcChipConfig init; /**< Pointer to the init() function. */ + FuriHalNfcChipConfig deinit; /**< Pointer to the deinit() function. */ + FuriHalNfcWaitEvent wait_event; /**< Pointer to the wait_event() function. */ + FuriHalNfcTx tx; /**< Pointer to the tx() function. */ + FuriHalNfcRx rx; /**< Pointer to the rx() function. */ + FuriHalNfcSleep sleep; /**< Pointer to the sleep() function. */ + FuriHalNfcIdle idle; /**< Pointer to the idle() function. */ +} FuriHalNfcTechListenerBase; + +/** + * @brief Abstract NFC technology definition structure. + * + * Each concrete technology implementation must fill this structure + * with its proper functions and constants. + */ +typedef struct { + FuriHalNfcTechPollerBase poller; /**< Structure containing the poller definition. */ + FuriHalNfcTechListenerBase listener; /**< Structure containing the listener definition. */ +} FuriHalNfcTechBase; + +/** @brief Technology declaration for ISO14443 (Type A). */ +extern const FuriHalNfcTechBase furi_hal_nfc_iso14443a; +/** @brief Technology declaration for ISO14443 (Type B). */ +extern const FuriHalNfcTechBase furi_hal_nfc_iso14443b; +/** @brief Technology declaration for ISO15693. */ +extern const FuriHalNfcTechBase furi_hal_nfc_iso15693; +/** @brief Technology declaration for FeliCa. */ +extern const FuriHalNfcTechBase furi_hal_nfc_felica; +/* Declare new tehcnologies here. */ + +/** + * @brief Array of pointers to every supported technology. + * + * This variable is defined in furi_hal_nfc.c. It will need to be modified + * in case when a new technology is to be added. + */ +extern const FuriHalNfcTechBase* furi_hal_nfc_tech[]; + +#ifdef __cplusplus +} +#endif diff --git a/targets/f7/furi_hal/furi_hal_nfc_timer.c b/targets/f7/furi_hal/furi_hal_nfc_timer.c new file mode 100644 index 000000000..c9de9dfe8 --- /dev/null +++ b/targets/f7/furi_hal/furi_hal_nfc_timer.c @@ -0,0 +1,229 @@ +#include "furi_hal_nfc_i.h" +#include "furi_hal_nfc_tech_i.h" + +#include + +#include +#include +#include + +#define TAG "FuriHalNfcTimer" + +#define FURI_HAL_NFC_TIMER_US_IN_S (1000000UL) + +/** + * To enable timer debug output on GPIO, define the FURI_HAL_NFC_TIMER_DEBUG macro + * Example: ./fbt --extra-define=FURI_HAL_NFC_TIMER_DEBUG + */ + +typedef enum { + FuriHalNfcTimerFwt, + FuriHalNfcTimerBlockTx, + FuriHalNfcTimerCount, +} FuriHalNfcTimer; + +typedef struct { + TIM_TypeDef* timer; + FuriHalBus bus; + uint32_t prescaler; + uint32_t freq_khz; + FuriHalNfcEventInternalType event; + FuriHalInterruptId irq_id; + IRQn_Type irq_type; +#ifdef FURI_HAL_NFC_TIMER_DEBUG + const GpioPin* pin; +#endif +} FuriHalNfcTimerConfig; + +static const FuriHalNfcTimerConfig furi_hal_nfc_timers[FuriHalNfcTimerCount] = { + [FuriHalNfcTimerFwt] = + { + .timer = TIM1, + .bus = FuriHalBusTIM1, + .event = FuriHalNfcEventInternalTypeTimerFwtExpired, + .irq_id = FuriHalInterruptIdTim1UpTim16, + .irq_type = TIM1_UP_TIM16_IRQn, +#ifdef FURI_HAL_NFC_TIMER_DEBUG + .pin = &gpio_ext_pa7, +#endif + }, + [FuriHalNfcTimerBlockTx] = + { + .timer = TIM17, + .bus = FuriHalBusTIM17, + .event = FuriHalNfcEventInternalTypeTimerBlockTxExpired, + .irq_id = FuriHalInterruptIdTim1TrgComTim17, + .irq_type = TIM1_TRG_COM_TIM17_IRQn, +#ifdef FURI_HAL_NFC_TIMER_DEBUG + .pin = &gpio_ext_pa6, +#endif + }, +}; + +static void furi_hal_nfc_timer_irq_callback(void* context) { + // Returning removed const-ness + const FuriHalNfcTimerConfig* config = context; + if(LL_TIM_IsActiveFlag_UPDATE(config->timer)) { + LL_TIM_ClearFlag_UPDATE(config->timer); + furi_hal_nfc_event_set(config->event); +#ifdef FURI_HAL_NFC_TIMER_DEBUG + furi_hal_gpio_write(timer_config->pin, false); +#endif + } +} + +static void furi_hal_nfc_timer_init(FuriHalNfcTimer timer) { + const FuriHalNfcTimerConfig* config = &furi_hal_nfc_timers[timer]; + + furi_hal_bus_enable(config->bus); + + LL_TIM_SetOnePulseMode(config->timer, LL_TIM_ONEPULSEMODE_SINGLE); + LL_TIM_EnableUpdateEvent(config->timer); + LL_TIM_SetCounterMode(config->timer, LL_TIM_COUNTERMODE_UP); + LL_TIM_SetClockSource(config->timer, LL_TIM_CLOCKSOURCE_INTERNAL); + + furi_hal_interrupt_set_isr( + config->irq_id, + furi_hal_nfc_timer_irq_callback, + // Warning: casting const-ness away + (FuriHalNfcTimerConfig*)config); + NVIC_SetPriority(config->irq_type, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 5, 0)); + NVIC_EnableIRQ(config->irq_type); +#ifdef FURI_HAL_NFC_TIMER_DEBUG + furi_hal_gpio_init(config->pin, GpioModeOutputPushPull, GpioPullNo, GpioSpeedVeryHigh); + furi_hal_gpio_write(config->pin, false); +#endif +} + +static void furi_hal_nfc_timer_deinit(FuriHalNfcTimer timer) { + const FuriHalNfcTimerConfig* config = &furi_hal_nfc_timers[timer]; + + LL_TIM_ClearFlag_UPDATE(config->timer); + furi_hal_interrupt_set_isr(config->irq_id, NULL, NULL); + NVIC_DisableIRQ(config->irq_type); + + if(furi_hal_bus_is_enabled(config->bus)) { + furi_hal_bus_disable(config->bus); + } +#ifdef FURI_HAL_NFC_TIMER_DEBUG + furi_hal_gpio_init_simple(config->pin, GpioModeAnalog); + furi_hal_gpio_write(config->pin, false); +#endif +} + +static int32_t furi_hal_nfc_timer_get_compensation(FuriHalNfcTimer timer) { + const FuriHalNfcTechBase* current_tech = furi_hal_nfc_tech[furi_hal_nfc.tech]; + + if(furi_hal_nfc.mode == FuriHalNfcModePoller) { + const FuriHalNfcPollerCompensation* comp = ¤t_tech->poller.compensation; + if(timer == FuriHalNfcTimerFwt) + return comp->fwt; + else if(timer == FuriHalNfcTimerBlockTx) + return comp->fdt; + + } else if(furi_hal_nfc.mode == FuriHalNfcModeListener) { + const FuriHalNfcListenerCompensation* comp = ¤t_tech->listener.compensation; + if(timer == FuriHalNfcTimerBlockTx) return comp->fdt; + } + + return 0; +} + +static inline bool furi_hal_nfc_timer_is_running(FuriHalNfcTimer timer) { + return LL_TIM_IsEnabledCounter(furi_hal_nfc_timers[timer].timer) != 0; +} + +static void furi_hal_nfc_timer_start_core_ticks(FuriHalNfcTimer timer, uint64_t core_ticks) { + furi_check(!furi_hal_nfc_timer_is_running(timer)); + + const FuriHalNfcTimerConfig* config = &furi_hal_nfc_timers[timer]; + furi_check(furi_hal_bus_is_enabled(config->bus)); + + const uint32_t prescaler = (core_ticks - 1) / UINT16_MAX; + furi_check(prescaler <= UINT16_MAX); + + const uint32_t arr_reg = core_ticks / (prescaler + 1); + furi_check(arr_reg <= UINT16_MAX); + + LL_TIM_DisableIT_UPDATE(config->timer); + + LL_TIM_SetPrescaler(config->timer, prescaler); + LL_TIM_SetAutoReload(config->timer, arr_reg); + + LL_TIM_GenerateEvent_UPDATE(config->timer); + while(!LL_TIM_IsActiveFlag_UPDATE(config->timer)) + ; + LL_TIM_ClearFlag_UPDATE(config->timer); + + LL_TIM_EnableIT_UPDATE(config->timer); + LL_TIM_EnableCounter(config->timer); +#ifdef FURI_HAL_NFC_TIMER_DEBUG + furi_hal_gpio_write(config->pin, true); +#endif +} + +static void furi_hal_nfc_timer_start_us(FuriHalNfcTimer timer, uint32_t time_us) { + furi_hal_nfc_timer_start_core_ticks( + timer, SystemCoreClock / FURI_HAL_NFC_TIMER_US_IN_S * time_us); +} + +static void furi_hal_nfc_timer_start_fc(FuriHalNfcTimer timer, uint32_t time_fc) { + const int32_t comp_fc = furi_hal_nfc_timer_get_compensation(timer); + // Not starting the timer if the compensation value is greater than the requested delay + if(comp_fc >= (int32_t)time_fc) return; + + furi_hal_nfc_timer_start_core_ticks( + timer, ((uint64_t)SystemCoreClock * (time_fc - comp_fc)) / FURI_HAL_NFC_CARRIER_HZ); +} + +static void furi_hal_nfc_timer_stop(FuriHalNfcTimer timer) { + const FuriHalNfcTimerConfig* config = &furi_hal_nfc_timers[timer]; + + LL_TIM_DisableIT_UPDATE(config->timer); + LL_TIM_DisableCounter(config->timer); + LL_TIM_SetCounter(config->timer, 0); + LL_TIM_SetAutoReload(config->timer, 0); + + if(LL_TIM_IsActiveFlag_UPDATE(config->timer)) { + LL_TIM_ClearFlag_UPDATE(config->timer); + } +#ifdef FURI_HAL_NFC_TIMER_DEBUG + furi_hal_gpio_write(config->pin, false); +#endif +} + +void furi_hal_nfc_timers_init() { + for(size_t i = 0; i < FuriHalNfcTimerCount; i++) { + furi_hal_nfc_timer_init(i); + } +} + +void furi_hal_nfc_timers_deinit() { + for(size_t i = 0; i < FuriHalNfcTimerCount; i++) { + furi_hal_nfc_timer_deinit(i); + } +} + +void furi_hal_nfc_timer_fwt_start(uint32_t time_fc) { + furi_hal_nfc_timer_start_fc(FuriHalNfcTimerFwt, time_fc); +} + +void furi_hal_nfc_timer_fwt_stop() { + furi_hal_nfc_timer_stop(FuriHalNfcTimerFwt); +} + +void furi_hal_nfc_timer_block_tx_start(uint32_t time_fc) { + furi_hal_nfc_timer_start_fc(FuriHalNfcTimerBlockTx, time_fc); +} + +void furi_hal_nfc_timer_block_tx_start_us(uint32_t time_us) { + furi_hal_nfc_timer_start_us(FuriHalNfcTimerBlockTx, time_us); +} + +void furi_hal_nfc_timer_block_tx_stop() { + furi_hal_nfc_timer_stop(FuriHalNfcTimerBlockTx); +} + +bool furi_hal_nfc_timer_block_tx_is_running() { + return furi_hal_nfc_timer_is_running(FuriHalNfcTimerBlockTx); +} diff --git a/firmware/targets/f7/furi_hal/furi_hal_os.c b/targets/f7/furi_hal/furi_hal_os.c similarity index 99% rename from firmware/targets/f7/furi_hal/furi_hal_os.c rename to targets/f7/furi_hal/furi_hal_os.c index 046cf79dc..ea835b95f 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_os.c +++ b/targets/f7/furi_hal/furi_hal_os.c @@ -10,6 +10,9 @@ #include +#include +#include + #define TAG "FuriHalOs" #define FURI_HAL_IDLE_TIMER_CLK_HZ 32768 diff --git a/firmware/targets/f7/furi_hal/furi_hal_os.h b/targets/f7/furi_hal/furi_hal_os.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_os.h rename to targets/f7/furi_hal/furi_hal_os.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_power.c b/targets/f7/furi_hal/furi_hal_power.c similarity index 99% rename from firmware/targets/f7/furi_hal/furi_hal_power.c rename to targets/f7/furi_hal/furi_hal_power.c index 0eb93e664..119dee81f 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_power.c +++ b/targets/f7/furi_hal/furi_hal_power.c @@ -459,10 +459,10 @@ void furi_hal_power_disable_external_3_3v() { } void furi_hal_power_suppress_charge_enter() { - vTaskSuspendAll(); + FURI_CRITICAL_ENTER(); bool disable_charging = furi_hal_power.suppress_charge == 0; furi_hal_power.suppress_charge++; - xTaskResumeAll(); + FURI_CRITICAL_EXIT(); if(disable_charging) { furi_hal_i2c_acquire(&furi_hal_i2c_handle_power); @@ -472,10 +472,10 @@ void furi_hal_power_suppress_charge_enter() { } void furi_hal_power_suppress_charge_exit() { - vTaskSuspendAll(); + FURI_CRITICAL_ENTER(); furi_hal_power.suppress_charge--; bool enable_charging = furi_hal_power.suppress_charge == 0; - xTaskResumeAll(); + FURI_CRITICAL_EXIT(); if(enable_charging) { furi_hal_i2c_acquire(&furi_hal_i2c_handle_power); diff --git a/firmware/targets/f7/furi_hal/furi_hal_power_config.c b/targets/f7/furi_hal/furi_hal_power_config.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_power_config.c rename to targets/f7/furi_hal/furi_hal_power_config.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_pwm.c b/targets/f7/furi_hal/furi_hal_pwm.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_pwm.c rename to targets/f7/furi_hal/furi_hal_pwm.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_pwm.h b/targets/f7/furi_hal/furi_hal_pwm.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_pwm.h rename to targets/f7/furi_hal/furi_hal_pwm.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_random.c b/targets/f7/furi_hal/furi_hal_random.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_random.c rename to targets/f7/furi_hal/furi_hal_random.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_region.c b/targets/f7/furi_hal/furi_hal_region.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_region.c rename to targets/f7/furi_hal/furi_hal_region.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_resources.c b/targets/f7/furi_hal/furi_hal_resources.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_resources.c rename to targets/f7/furi_hal/furi_hal_resources.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_resources.h b/targets/f7/furi_hal/furi_hal_resources.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_resources.h rename to targets/f7/furi_hal/furi_hal_resources.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_rfid.c b/targets/f7/furi_hal/furi_hal_rfid.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_rfid.c rename to targets/f7/furi_hal/furi_hal_rfid.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_rfid.h b/targets/f7/furi_hal/furi_hal_rfid.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_rfid.h rename to targets/f7/furi_hal/furi_hal_rfid.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_rtc.c b/targets/f7/furi_hal/furi_hal_rtc.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_rtc.c rename to targets/f7/furi_hal/furi_hal_rtc.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_sd.c b/targets/f7/furi_hal/furi_hal_sd.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_sd.c rename to targets/f7/furi_hal/furi_hal_sd.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_speaker.c b/targets/f7/furi_hal/furi_hal_speaker.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_speaker.c rename to targets/f7/furi_hal/furi_hal_speaker.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_spi.c b/targets/f7/furi_hal/furi_hal_spi.c similarity index 99% rename from firmware/targets/f7/furi_hal/furi_hal_spi.c rename to targets/f7/furi_hal/furi_hal_spi.c index a8884105a..98ca71af3 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_spi.c +++ b/targets/f7/furi_hal/furi_hal_spi.c @@ -200,7 +200,7 @@ bool furi_hal_spi_bus_trx_dma( furi_assert(size > 0); // If scheduler is not running, use blocking mode - if(xTaskGetSchedulerState() != taskSCHEDULER_RUNNING) { + if(furi_kernel_is_running()) { return furi_hal_spi_bus_trx(handle, tx_buffer, rx_buffer, size, timeout_ms); } @@ -221,7 +221,7 @@ bool furi_hal_spi_bus_trx_dma( dma_rx_req = LL_DMAMUX_REQ_SPI2_RX; dma_tx_req = LL_DMAMUX_REQ_SPI2_TX; } else { - furi_crash(NULL); + furi_crash(); } if(rx_buffer == NULL) { diff --git a/firmware/targets/f7/furi_hal/furi_hal_spi_config.c b/targets/f7/furi_hal/furi_hal_spi_config.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_spi_config.c rename to targets/f7/furi_hal/furi_hal_spi_config.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_spi_config.h b/targets/f7/furi_hal/furi_hal_spi_config.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_spi_config.h rename to targets/f7/furi_hal/furi_hal_spi_config.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_spi_types.h b/targets/f7/furi_hal/furi_hal_spi_types.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_spi_types.h rename to targets/f7/furi_hal/furi_hal_spi_types.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_subghz.c b/targets/f7/furi_hal/furi_hal_subghz.c similarity index 99% rename from firmware/targets/f7/furi_hal/furi_hal_subghz.c rename to targets/f7/furi_hal/furi_hal_subghz.c index 323f737f4..7db0329c7 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_subghz.c +++ b/targets/f7/furi_hal/furi_hal_subghz.c @@ -658,7 +658,7 @@ static void furi_hal_subghz_async_tx_timer_isr() { furi_hal_gpio_init(&gpio_cc1101_g0, GpioModeInput, GpioPullDown, GpioSpeedLow); LL_TIM_DisableCounter(TIM2); } else { - furi_crash(NULL); + furi_crash(); } } } diff --git a/firmware/targets/f7/furi_hal/furi_hal_subghz.h b/targets/f7/furi_hal/furi_hal_subghz.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_subghz.h rename to targets/f7/furi_hal/furi_hal_subghz.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_subghz_i.h b/targets/f7/furi_hal/furi_hal_subghz_i.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_subghz_i.h rename to targets/f7/furi_hal/furi_hal_subghz_i.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_target_hw.h b/targets/f7/furi_hal/furi_hal_target_hw.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_target_hw.h rename to targets/f7/furi_hal/furi_hal_target_hw.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_uart.c b/targets/f7/furi_hal/furi_hal_uart.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_uart.c rename to targets/f7/furi_hal/furi_hal_uart.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_uart.h b/targets/f7/furi_hal/furi_hal_uart.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_uart.h rename to targets/f7/furi_hal/furi_hal_uart.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_usb.c b/targets/f7/furi_hal/furi_hal_usb.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_usb.c rename to targets/f7/furi_hal/furi_hal_usb.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_usb_ccid.c b/targets/f7/furi_hal/furi_hal_usb_ccid.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_usb_ccid.c rename to targets/f7/furi_hal/furi_hal_usb_ccid.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_usb_cdc.c b/targets/f7/furi_hal/furi_hal_usb_cdc.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_usb_cdc.c rename to targets/f7/furi_hal/furi_hal_usb_cdc.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_usb_cdc.h b/targets/f7/furi_hal/furi_hal_usb_cdc.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_usb_cdc.h rename to targets/f7/furi_hal/furi_hal_usb_cdc.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_usb_hid.c b/targets/f7/furi_hal/furi_hal_usb_hid.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_usb_hid.c rename to targets/f7/furi_hal/furi_hal_usb_hid.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_usb_i.h b/targets/f7/furi_hal/furi_hal_usb_i.h similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_usb_i.h rename to targets/f7/furi_hal/furi_hal_usb_i.h diff --git a/firmware/targets/f7/furi_hal/furi_hal_usb_u2f.c b/targets/f7/furi_hal/furi_hal_usb_u2f.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_usb_u2f.c rename to targets/f7/furi_hal/furi_hal_usb_u2f.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_version.c b/targets/f7/furi_hal/furi_hal_version.c similarity index 99% rename from firmware/targets/f7/furi_hal/furi_hal_version.c rename to targets/f7/furi_hal/furi_hal_version.c index b6460cc5f..46a15bde8 100644 --- a/firmware/targets/f7/furi_hal/furi_hal_version.c +++ b/targets/f7/furi_hal/furi_hal_version.c @@ -207,7 +207,7 @@ void furi_hal_version_init() { furi_hal_version_load_otp_v2(); break; default: - furi_crash(NULL); + furi_crash(); } furi_hal_rtc_set_register(FuriHalRtcRegisterVersion, (uint32_t)version_get()); diff --git a/firmware/targets/f7/furi_hal/furi_hal_version_device.c b/targets/f7/furi_hal/furi_hal_version_device.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_version_device.c rename to targets/f7/furi_hal/furi_hal_version_device.c diff --git a/firmware/targets/f7/furi_hal/furi_hal_vibro.c b/targets/f7/furi_hal/furi_hal_vibro.c similarity index 100% rename from firmware/targets/f7/furi_hal/furi_hal_vibro.c rename to targets/f7/furi_hal/furi_hal_vibro.c diff --git a/firmware/targets/f7/inc/FreeRTOSConfig.h b/targets/f7/inc/FreeRTOSConfig.h similarity index 99% rename from firmware/targets/f7/inc/FreeRTOSConfig.h rename to targets/f7/inc/FreeRTOSConfig.h index 024d43a6d..3bc57f8f3 100644 --- a/firmware/targets/f7/inc/FreeRTOSConfig.h +++ b/targets/f7/inc/FreeRTOSConfig.h @@ -3,13 +3,14 @@ #if defined(__ICCARM__) || defined(__CC_ARM) || defined(__GNUC__) #include #pragma GCC diagnostic ignored "-Wredundant-decls" -extern uint32_t SystemCoreClock; #endif #ifndef CMSIS_device_header #define CMSIS_device_header "stm32wbxx.h" #endif /* CMSIS_device_header */ +#include CMSIS_device_header + #define configENABLE_FPU 1 #define configENABLE_MPU 0 diff --git a/firmware/targets/f7/inc/alt_boot.h b/targets/f7/inc/alt_boot.h similarity index 100% rename from firmware/targets/f7/inc/alt_boot.h rename to targets/f7/inc/alt_boot.h diff --git a/targets/f7/inc/furi_config.h b/targets/f7/inc/furi_config.h new file mode 100644 index 000000000..c935611ab --- /dev/null +++ b/targets/f7/inc/furi_config.h @@ -0,0 +1,3 @@ +#pragma once + +#define FURI_CONFIG_THREAD_MAX_PRIORITIES (32) \ No newline at end of file diff --git a/firmware/targets/f7/inc/stm32.h b/targets/f7/inc/stm32.h similarity index 100% rename from firmware/targets/f7/inc/stm32.h rename to targets/f7/inc/stm32.h diff --git a/firmware/targets/f7/inc/stm32_assert.h b/targets/f7/inc/stm32_assert.h similarity index 100% rename from firmware/targets/f7/inc/stm32_assert.h rename to targets/f7/inc/stm32_assert.h diff --git a/firmware/targets/f7/platform_specific/intrinsic_export.h b/targets/f7/platform_specific/intrinsic_export.h similarity index 100% rename from firmware/targets/f7/platform_specific/intrinsic_export.h rename to targets/f7/platform_specific/intrinsic_export.h diff --git a/firmware/targets/f7/platform_specific/math_wrapper.h b/targets/f7/platform_specific/math_wrapper.h similarity index 100% rename from firmware/targets/f7/platform_specific/math_wrapper.h rename to targets/f7/platform_specific/math_wrapper.h diff --git a/firmware/targets/f7/src/dfu.c b/targets/f7/src/dfu.c similarity index 100% rename from firmware/targets/f7/src/dfu.c rename to targets/f7/src/dfu.c diff --git a/firmware/targets/f7/src/main.c b/targets/f7/src/main.c similarity index 98% rename from firmware/targets/f7/src/main.c rename to targets/f7/src/main.c index 2c353f52b..ca705fe5e 100644 --- a/firmware/targets/f7/src/main.c +++ b/targets/f7/src/main.c @@ -2,7 +2,6 @@ #include #include #include -#include #include #define TAG "Main" diff --git a/firmware/targets/f7/src/recovery.c b/targets/f7/src/recovery.c similarity index 100% rename from firmware/targets/f7/src/recovery.c rename to targets/f7/src/recovery.c diff --git a/firmware/targets/f7/src/system_stm32wbxx.c b/targets/f7/src/system_stm32wbxx.c similarity index 100% rename from firmware/targets/f7/src/system_stm32wbxx.c rename to targets/f7/src/system_stm32wbxx.c diff --git a/firmware/targets/f7/src/update.c b/targets/f7/src/update.c similarity index 100% rename from firmware/targets/f7/src/update.c rename to targets/f7/src/update.c diff --git a/firmware/targets/f7/startup_stm32wb55xx_cm4.s b/targets/f7/startup_stm32wb55xx_cm4.s similarity index 100% rename from firmware/targets/f7/startup_stm32wb55xx_cm4.s rename to targets/f7/startup_stm32wb55xx_cm4.s diff --git a/firmware/targets/f7/stm32wb55xx_flash.ld b/targets/f7/stm32wb55xx_flash.ld similarity index 100% rename from firmware/targets/f7/stm32wb55xx_flash.ld rename to targets/f7/stm32wb55xx_flash.ld diff --git a/firmware/targets/f7/stm32wb55xx_ram_fw.ld b/targets/f7/stm32wb55xx_ram_fw.ld similarity index 100% rename from firmware/targets/f7/stm32wb55xx_ram_fw.ld rename to targets/f7/stm32wb55xx_ram_fw.ld diff --git a/firmware/targets/f7/target.json b/targets/f7/target.json similarity index 94% rename from firmware/targets/f7/target.json rename to targets/f7/target.json index 9bb87000c..63b5cdb92 100644 --- a/firmware/targets/f7/target.json +++ b/targets/f7/target.json @@ -30,9 +30,9 @@ "nfc", "digital_signal", "pulse_reader", + "signal_reader", "microtar", "usb_stm32", - "st25rfal002", "infrared", "appframe", "assets", @@ -44,6 +44,7 @@ "lfrfid", "flipper_application", "flipperformat", - "toolbox" + "toolbox", + "flipper7" ] } \ No newline at end of file diff --git a/firmware/targets/furi_hal_include/furi_hal.h b/targets/furi_hal_include/furi_hal.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal.h rename to targets/furi_hal_include/furi_hal.h diff --git a/firmware/targets/furi_hal_include/furi_hal_bt.h b/targets/furi_hal_include/furi_hal_bt.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_bt.h rename to targets/furi_hal_include/furi_hal_bt.h diff --git a/firmware/targets/furi_hal_include/furi_hal_bt_hid.h b/targets/furi_hal_include/furi_hal_bt_hid.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_bt_hid.h rename to targets/furi_hal_include/furi_hal_bt_hid.h diff --git a/firmware/targets/furi_hal_include/furi_hal_bt_serial.h b/targets/furi_hal_include/furi_hal_bt_serial.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_bt_serial.h rename to targets/furi_hal_include/furi_hal_bt_serial.h diff --git a/firmware/targets/furi_hal_include/furi_hal_cortex.h b/targets/furi_hal_include/furi_hal_cortex.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_cortex.h rename to targets/furi_hal_include/furi_hal_cortex.h diff --git a/firmware/targets/furi_hal_include/furi_hal_crypto.h b/targets/furi_hal_include/furi_hal_crypto.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_crypto.h rename to targets/furi_hal_include/furi_hal_crypto.h diff --git a/firmware/targets/furi_hal_include/furi_hal_debug.h b/targets/furi_hal_include/furi_hal_debug.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_debug.h rename to targets/furi_hal_include/furi_hal_debug.h diff --git a/firmware/targets/furi_hal_include/furi_hal_i2c.h b/targets/furi_hal_include/furi_hal_i2c.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_i2c.h rename to targets/furi_hal_include/furi_hal_i2c.h diff --git a/firmware/targets/furi_hal_include/furi_hal_info.h b/targets/furi_hal_include/furi_hal_info.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_info.h rename to targets/furi_hal_include/furi_hal_info.h diff --git a/firmware/targets/furi_hal_include/furi_hal_infrared.h b/targets/furi_hal_include/furi_hal_infrared.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_infrared.h rename to targets/furi_hal_include/furi_hal_infrared.h diff --git a/firmware/targets/furi_hal_include/furi_hal_light.h b/targets/furi_hal_include/furi_hal_light.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_light.h rename to targets/furi_hal_include/furi_hal_light.h diff --git a/firmware/targets/furi_hal_include/furi_hal_memory.h b/targets/furi_hal_include/furi_hal_memory.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_memory.h rename to targets/furi_hal_include/furi_hal_memory.h diff --git a/firmware/targets/furi_hal_include/furi_hal_mpu.h b/targets/furi_hal_include/furi_hal_mpu.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_mpu.h rename to targets/furi_hal_include/furi_hal_mpu.h diff --git a/targets/furi_hal_include/furi_hal_nfc.h b/targets/furi_hal_include/furi_hal_nfc.h new file mode 100644 index 000000000..ad4080e26 --- /dev/null +++ b/targets/furi_hal_include/furi_hal_nfc.h @@ -0,0 +1,457 @@ +/** + * @file furi_hal_nfc.h + * @brief NFC HAL library. + * + * This library contains functions and definitions needed for NFC hardware low-level access. + * + * Application developers should first consider using the NFC protocol stack or + * the NFC transport layer and see if the APIs provided there sufficient + * for the applicaton's intended purpose. + * + * @see nfc.h + * @see nfc_protocol.h + * + * If any of the above mentioned options is used, calling any of the functions provided by this + * library is hardly necessary, as it will be taken care of under the hood. + * + */ +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief NFC carrier frequency, in Hz. + */ +#define FURI_HAL_NFC_CARRIER_HZ (13560000UL) + +/** + * @brief Special value indicating that waiting for an event shall never time out. + */ +#define FURI_HAL_NFC_EVENT_WAIT_FOREVER (0xFFFFFFFFU) + +/** + * @brief Enumeration of possible NFC HAL events. + */ +typedef enum { + FuriHalNfcEventOscOn = (1U << 0), /**< Oscillator has been started. */ + FuriHalNfcEventFieldOn = (1U << 1), /**< External field (carrier) has been detected. */ + FuriHalNfcEventFieldOff = (1U << 2), /**< External field (carrier) has been lost. */ + FuriHalNfcEventListenerActive = (1U << 3), /**< Reader has issued a wake-up command. */ + FuriHalNfcEventTxStart = (1U << 4), /**< Transmission has started. */ + FuriHalNfcEventTxEnd = (1U << 5), /**< Transmission has ended. */ + FuriHalNfcEventRxStart = (1U << 6), /**< Reception has started. */ + FuriHalNfcEventRxEnd = (1U << 7), /**< Reception has ended. */ + FuriHalNfcEventCollision = (1U << 8), /**< A collision has occurred. */ + FuriHalNfcEventTimerFwtExpired = (1U << 9), /**< Frame wait timer has expired. */ + FuriHalNfcEventTimerBlockTxExpired = (1U << 10), /**< Transmission block timer has expired. */ + FuriHalNfcEventTimeout = + (1U << 11), /**< No events have occurred in a specified time period. */ + FuriHalNfcEventAbortRequest = + (1U << 12), /**< User has requested to abort current operation. */ +} FuriHalNfcEvent; + +/** + * @brief Enumeration of possible NFC HAL errors. + */ +typedef enum { + FuriHalNfcErrorNone, /**< No error has occurred. */ + FuriHalNfcErrorBusy, /**< The communication bus is busy. */ + FuriHalNfcErrorCommunication, /**< NFC hardware did not respond or responded unexpectedly. */ + FuriHalNfcErrorOscillator, /**< Oscillator failed to start. */ + FuriHalNfcErrorCommunicationTimeout, /**< NFC hardware did not respond in time. */ + FuriHalNfcErrorBufferOverflow, /**< Receive buffer was too small for the received data. */ + FuriHalNfcErrorIncompleteFrame, /**< Not enough data was received to parse a valid frame. */ + FuriHalNfcErrorDataFormat, /**< Cannot parse a frame due to unexpected/invalid data. */ +} FuriHalNfcError; + +/** + * @brief Enumeration of possible NFC HAL operating modes. + */ +typedef enum { + FuriHalNfcModePoller, /**< Configure NFC HAL to operate as a poller. */ + FuriHalNfcModeListener, /**< Configure NFC HAL to operate as a listener. */ + + FuriHalNfcModeNum, /**< Special value equal to the operating modes count. Internal use. */ +} FuriHalNfcMode; + +/** + * @brief Enumeration of supported NFC technologies. + */ +typedef enum { + FuriHalNfcTechIso14443a, /**< Configure NFC HAL to use the ISO14443 (type A) technology. */ + FuriHalNfcTechIso14443b, /**< Configure NFC HAL to use the ISO14443 (type B) technology. */ + FuriHalNfcTechIso15693, /**< Configure NFC HAL to use the ISO15693 technology. */ + FuriHalNfcTechFelica, /**< Configure NFC HAL to use the FeliCa technology. */ + + FuriHalNfcTechNum, /**< Special value equal to the supported technologies count. Internal use. */ + FuriHalNfcTechInvalid, /**< Special value indicating the unconfigured state. Internal use. */ +} FuriHalNfcTech; + +/** + * @brief Initialise the NFC HAL and associated hardware. + * + * This function is called automatically during the firmware initialisation, + * so there is no need to call it explicitly. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_init(); + +/** + * @brief Check whether the NFC HAL was properly initialised and is ready. + * + * @returns FuriHalNfcErrorNone if ready, any other error code if not ready. + */ +FuriHalNfcError furi_hal_nfc_is_hal_ready(); + +/** + * @brief Exclusively take over the NFC HAL and associated hardware. + * + * This function needs to be called whenever an interaction with the NFC HAL + * is to take place (usually once upon the application start). + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_acquire(); + +/** + * @brief Release the exclusive lock and make the NFC HAL available for others. + * + * This function needs to be called when the user code is done working + * with the NFC HAL (usually once upon application exit). It must be called + * from the same thread that has called furi_hal_nfc_acquire(). + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_release(); + +/** + * @brief Configure the NFC hardware to enter the low-power mode. + * + * This function must be called each time when the user code is done working + * with the NFC HAL for the time being (e.g. waiting on user input). + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_low_power_mode_start(); + +/** + * @brief Configure the NFC hardware to exit the low-power mode. + * + * This function must be called each time when the user code begins working + * with the NFC HAL, as the default state is low-power mode. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_low_power_mode_stop(); + +/** + * @brief Configure the NFC HAL to work in a particular mode. + * + * Not all technologies implement the listener operating mode. + * + * @param[in] mode required operating mode. + * @param[in] tech required technology configuration. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_set_mode(FuriHalNfcMode mode, FuriHalNfcTech tech); + +/** + * @brief Reset the NFC HAL to its default (unconfigured) state. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_reset_mode(); + +/** + * @brief Enable field (carrier) detection by the NFC hardware. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_field_detect_start(); + +/** + * @brief Disable field (carrier) detection by the NFC hardware. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_field_detect_stop(); + +/** + * @brief Check if the reader field (carrier) was detected by the NFC hardware. + * + * @returns true if the field was detected, false otherwise. + */ +bool furi_hal_nfc_field_is_present(); + +/** + * @brief Enable field (carrier) generation by the NFC hardware. + * + * No carrier modulation will occur unless a transmission is explicitly started. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_poller_field_on(); + +/** + * @brief Wait for an NFC HAL event in poller mode. + * + * @param[in] timeout_ms time to wait (timeout) in milliseconds. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcEvent furi_hal_nfc_poller_wait_event(uint32_t timeout_ms); + +/** + * @brief Wait for an NFC HAL event in listener mode. + * @param[in] timeout_ms time to wait (timeout) in milliseconds. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcEvent furi_hal_nfc_listener_wait_event(uint32_t timeout_ms); + +/** + * @brief Transmit data in poller mode. + * + * @param[in] tx_data pointer to a byte array containing the data to be transmitted. + * @param[in] tx_bits transmit data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_poller_tx(const uint8_t* tx_data, size_t tx_bits); + +/** + * @brief Receive data in poller mode. + * + * The receive buffer must be big enough to accomodate all of the expected data. + * + * @param rx_data[out] pointer to a byte array to be filled with received data. + * @param rx_data_size[in] maximum received data size, in bytes. + * @param rx_bits[out] pointer to the variable to hold received data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_poller_rx(uint8_t* rx_data, size_t rx_data_size, size_t* rx_bits); + +/** + * @brief Transmit data in listener mode. + * + * @param[in] tx_data pointer to a byte array containing the data to be transmitted. + * @param[in] tx_bits transmit data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_listener_tx(const uint8_t* tx_data, size_t tx_bits); + +/** + * @brief Receive data in listener mode. + * + * The receive buffer must be big enough to accomodate all of the expected data. + * + * @param rx_data[out] pointer to a byte array to be filled with received data. + * @param rx_data_size[in] maximum received data size, in bytes. + * @param rx_bits[out] pointer to the variable to hold received data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_listener_rx(uint8_t* rx_data, size_t rx_data_size, size_t* rx_bits); + +/** + * @brief Go to sleep in listener mode. + * + * Puts the passive target logic into Sleep (Halt) state. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_listener_sleep(); + +/** + * @brief Go to idle in listener mode. + * + * Puts the passive target logic into Sense (Idle) state. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_listener_idle(); + +/** + * @brief Enable reception in listener mode. + * + * Starts hardware receivers and receive decoders. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_listener_enable_rx(); + +/** + * @brief Reset communication. + * + * Resets the communication state and stops all activities: transmission, reception, etc. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_trx_reset(); + +/** + * @brief Enable generation of NFC HAL events. + * + * @warning This function must be called from the same thread from which + * the the furi_hal_nfc_*_wait_event() calls will be made. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_event_start(); + +/** + * @brief Disable generation of NFC HAL events. + * + * Unlike furi_hal_nfc_event_start(), this function may be called from any thread. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_event_stop(); + +/** + * @brief Manually emit the FuriHalNfcEventAbortRequest event. + * + * @returns FuriHalNfcErrorNone on success, any other error code on failure. +*/ +FuriHalNfcError furi_hal_nfc_abort(); + +/** + * @brief Start frame wait timeout timer. + * + * @param[in] time_fc time to wait, in carrier cycles. + */ +void furi_hal_nfc_timer_fwt_start(uint32_t time_fc); + +/** + * @brief Stop frame wait timeout timer. + */ +void furi_hal_nfc_timer_fwt_stop(); + +/** + * @brief Start block transmit (frame delay) timer. + * + * @param[in] time_fc time to wait, in carrier cycles. +*/ +void furi_hal_nfc_timer_block_tx_start(uint32_t time_fc); + +/** + * @brief Start block transmit (frame delay) timer. + * + * @param[in] time_us time to wait, in microseconds. + */ +void furi_hal_nfc_timer_block_tx_start_us(uint32_t time_us); + +/** + * @brief Stop block transmit (frame delay) timer. + */ +void furi_hal_nfc_timer_block_tx_stop(); + +/** + * @brief Check whether block transmit (frame delay) timer is running. + * + * @returns true if timer is running, false otherwise. + */ +bool furi_hal_nfc_timer_block_tx_is_running(); + +/* + * Technology-specific functions. + * + * In a perfect world, this would not be necessary. + * However, the current implementation employs NFC hardware that partially implements + * certain protocols (e.g. ISO14443-3A), thus requiring methods to access such features. + */ + +/******************* Iso14443a specific API *******************/ + +/** + * @brief Enumeration of ISO14443 (Type A) short frame types. + */ +typedef enum { + FuriHalNfcaShortFrameAllReq, + FuriHalNfcaShortFrameSensReq, +} FuriHalNfcaShortFrame; + +/** + * @brief Transmit ISO14443 (Type A) short frame in poller mode. + * + * @param[in] frame short frame type to be transmitted. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_iso14443a_poller_trx_short_frame(FuriHalNfcaShortFrame frame); + +/** Transmit ISO14443 (Type A) SDD frame in poller mode. + * + * @param[in] tx_data pointer to a byte array containing the data to be transmitted. + * @param[in] tx_bits transmit data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_iso14443a_tx_sdd_frame(const uint8_t* tx_data, size_t tx_bits); + +/** + * Receive ISO14443 (Type A) SDD frame in poller mode. + * + * The receive buffer must be big enough to accomodate all of the expected data. + * + * @param rx_data[out] pointer to a byte array to be filled with received data. + * @param rx_data_size[in] maximum received data size, in bytes. + * @param rx_bits[out] pointer to the variable to hold received data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError + furi_hal_nfc_iso14443a_rx_sdd_frame(uint8_t* rx_data, size_t rx_data_size, size_t* rx_bits); + +/** + * @brief Transmit ISO14443 (Type A) frame with custom parity bits in poller mode. + * + * Same as furi_hal_nfc_poller_tx(), but uses the parity bits provided + * by the user code instead of calculating them automatically. + * + * @param[in] tx_data pointer to a byte array containing the data to be transmitted. + * @param[in] tx_bits transmit data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError + furi_hal_nfc_iso14443a_poller_tx_custom_parity(const uint8_t* tx_data, size_t tx_bits); + +/** + * @brief Set ISO14443 (Type A) collision resolution parameters in listener mode. + * + * Configures the NFC hardware for automatic collision resolution. + * + * @param[in] uid pointer to a byte array containing the UID. + * @param[in] uid_len UID length in bytes (must be supported by the protocol). + * @param[in] atqa ATQA byte value. + * @param[in] sak SAK byte value. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_iso14443a_listener_set_col_res_data( + uint8_t* uid, + uint8_t uid_len, + uint8_t* atqa, + uint8_t sak); + +/** + * @brief Transmit ISO14443 (Type A) frame with custom parity bits in listener mode. + * + * @param[in] tx_data pointer to a byte array containing the data to be transmitted. + * @param[in] tx_parity pointer to a (bit-packed) byte array containing the parity to be transmitted. + * @param[in] tx_bits transmit data size, in bits. + * @returns FuriHalNfcErrorNone on success, any other error code on failure. + */ +FuriHalNfcError furi_hal_nfc_iso14443a_listener_tx_custom_parity( + const uint8_t* tx_data, + const uint8_t* tx_parity, + size_t tx_bits); + +/** Send ISO15693 SOF in listener mode + * + * @return FuriHalNfcError +*/ +FuriHalNfcError furi_hal_nfc_iso15693_listener_tx_sof(); + +#ifdef __cplusplus +} +#endif diff --git a/firmware/targets/furi_hal_include/furi_hal_power.h b/targets/furi_hal_include/furi_hal_power.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_power.h rename to targets/furi_hal_include/furi_hal_power.h diff --git a/firmware/targets/furi_hal_include/furi_hal_random.h b/targets/furi_hal_include/furi_hal_random.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_random.h rename to targets/furi_hal_include/furi_hal_random.h diff --git a/firmware/targets/furi_hal_include/furi_hal_region.h b/targets/furi_hal_include/furi_hal_region.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_region.h rename to targets/furi_hal_include/furi_hal_region.h diff --git a/firmware/targets/furi_hal_include/furi_hal_rtc.h b/targets/furi_hal_include/furi_hal_rtc.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_rtc.h rename to targets/furi_hal_include/furi_hal_rtc.h diff --git a/firmware/targets/furi_hal_include/furi_hal_sd.h b/targets/furi_hal_include/furi_hal_sd.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_sd.h rename to targets/furi_hal_include/furi_hal_sd.h diff --git a/firmware/targets/furi_hal_include/furi_hal_speaker.h b/targets/furi_hal_include/furi_hal_speaker.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_speaker.h rename to targets/furi_hal_include/furi_hal_speaker.h diff --git a/firmware/targets/furi_hal_include/furi_hal_spi.h b/targets/furi_hal_include/furi_hal_spi.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_spi.h rename to targets/furi_hal_include/furi_hal_spi.h diff --git a/firmware/targets/furi_hal_include/furi_hal_usb.h b/targets/furi_hal_include/furi_hal_usb.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_usb.h rename to targets/furi_hal_include/furi_hal_usb.h diff --git a/firmware/targets/furi_hal_include/furi_hal_usb_ccid.h b/targets/furi_hal_include/furi_hal_usb_ccid.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_usb_ccid.h rename to targets/furi_hal_include/furi_hal_usb_ccid.h diff --git a/firmware/targets/furi_hal_include/furi_hal_usb_hid.h b/targets/furi_hal_include/furi_hal_usb_hid.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_usb_hid.h rename to targets/furi_hal_include/furi_hal_usb_hid.h diff --git a/firmware/targets/furi_hal_include/furi_hal_usb_hid_u2f.h b/targets/furi_hal_include/furi_hal_usb_hid_u2f.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_usb_hid_u2f.h rename to targets/furi_hal_include/furi_hal_usb_hid_u2f.h diff --git a/firmware/targets/furi_hal_include/furi_hal_version.h b/targets/furi_hal_include/furi_hal_version.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_version.h rename to targets/furi_hal_include/furi_hal_version.h diff --git a/firmware/targets/furi_hal_include/furi_hal_vibro.h b/targets/furi_hal_include/furi_hal_vibro.h similarity index 100% rename from firmware/targets/furi_hal_include/furi_hal_vibro.h rename to targets/furi_hal_include/furi_hal_vibro.h