diff --git a/src/.project b/src/.project index 6d959ad..0fa5b13 100644 --- a/src/.project +++ b/src/.project @@ -1,6 +1,6 @@ - hydrafw + hydrafw_hydranfc_shield_v2 diff --git a/src/Makefile b/src/Makefile index 03de97d..7c43f60 100644 --- a/src/Makefile +++ b/src/Makefile @@ -9,17 +9,23 @@ MAKEFLAGS += --no-builtin-rules # Set CPU target (default STM32F4XX) export STM32F4XX ?= 1 -# Set to 1 HYDRAFW_NFC to include HydraNFC extension support -export HYDRAFW_NFC ?= 1 +#Set to 1 to include HydraNFC V1 Shield (TRF7970A) extension support +#Set to 2 to include HydraNFC V2 Shield (ST25R3916) extension support +export HYDRAFW_HYDRANFC ?= 2 + export HYDRAFW_DEBUG ?= 0 export FW_REVISION := $(shell python build-scripts/hydrafw-revision.py) HYDRAFW_OPTS = -ifeq ($(HYDRAFW_NFC),1) +ifeq ($(HYDRAFW_HYDRANFC),1) HYDRAFW_OPTS += -DHYDRANFC endif +ifeq ($(HYDRAFW_HYDRANFC),2) +HYDRAFW_OPTS += -DHYDRANFC_V2 +endif + # Compiler options here. ifeq ($(USE_OPT),) USE_OPT = -Os -fomit-frame-pointer -falign-functions=16 -std=gnu89 --specs=nosys.specs @@ -143,11 +149,18 @@ ifeq ($(STM32F4XX),1) include drv/stm32cube/stm32f4xx_hal.mk endif -ifeq ($(HYDRAFW_NFC),1) +ifeq ($(HYDRAFW_HYDRANFC),1) include hydranfc/trf7970a/trf7970a.mk include hydranfc/hydranfc.mk endif +ifeq ($(HYDRAFW_HYDRANFC),2) +include hydranfc_v2/hydranfc_v2.mk +include hydranfc_v2/hal.mk +include hydranfc_v2/rfal.mk +include hydranfc_v2/lib.mk +endif + # Define linker script file here ifeq ($(STM32F4XX),1) LDSCRIPT= $(STARTUPLD)/STM32F405xG.ld @@ -175,11 +188,18 @@ ifeq ($(STM32F4XX),1) CSRC += $(STM32F4XX_HAL_SRC) endif -ifeq ($(HYDRAFW_NFC),1) +ifeq ($(HYDRAFW_HYDRANFC),1) CSRC += $(TRFSRC) \ $(HYDRANFCSRC) endif +ifeq ($(HYDRAFW_HYDRANFC),2) +CSRC += $(HYDRANFC_V2_SRC) +CSRC += $(HYDRANFC_V2_HAL_SRC) +CSRC += $(HYDRANFC_V2_RFAL_SRC) +CSRC += $(HYDRANFC_V2_LIB_SRC) +endif + # C++ sources that can be compiled in ARM or THUMB mode depending on the global # setting. CPPSRC = @@ -222,11 +242,18 @@ ifeq ($(STM32F4XX),1) INCDIR += $(STM32F4XX_HAL_INC) endif -ifeq ($(HYDRAFW_NFC),1) +ifeq ($(HYDRAFW_HYDRANFC),1) INCDIR += $(TRFINC) \ $(HYDRANFCINC) endif +ifeq ($(HYDRAFW_HYDRANFC),2) +INCDIR += $(HYDRANFC_V2_INC) +INCDIR += $(HYDRANFC_V2_HAL_INC) +INCDIR += $(HYDRANFC_V2_RFAL_INC) +INCDIR += $(HYDRANFC_V2_LIB_INC) +endif + # # Project, sources and paths ############################################################################## diff --git a/src/common/exec.c b/src/common/exec.c index 8487b51..8bf1157 100644 --- a/src/common/exec.c +++ b/src/common/exec.c @@ -194,7 +194,7 @@ static struct cmd_map { { T_SPI, cmd_mode_init }, { T_I2C, cmd_mode_init }, { T_UART, cmd_mode_init }, -#ifdef HYDRANFC +#if defined(HYDRANFC) || defined(HYDRANFC_V2) { T_NFC, cmd_mode_init }, #endif { T_CAN, cmd_mode_init }, diff --git a/src/hydrabus/commands.c b/src/hydrabus/commands.c index 55c03f2..537eec6 100644 --- a/src/hydrabus/commands.c +++ b/src/hydrabus/commands.c @@ -86,10 +86,14 @@ t_token_dict tl_dict[] = { { T_PERIOD, "period" }, { T_CONTINUOUS, "continuous" }, { T_SCAN, "scan" }, -#ifdef HYDRANFC +#if defined(HYDRANFC) || defined(HYDRANFC_V2) { T_NFC, "nfc" }, - { T_TYPEA, "typea" }, - { T_VICINITY, "vicinity" }, + /* + { T_NFCA, "nfc-a" }, + { T_NFCB, "nfc-b" }, + { T_NFCV, "nfc-v" }, + { T_NFCF, "nfc-f" }, + */ { T_EMUL_MIFARE, "emul-mifare" }, { T_EMUL_ISO14443A, "emul-3a" }, { T_REGISTERS, "registers" }, @@ -309,7 +313,7 @@ t_token tokens_mode_trigger[] = { { } }; -#ifdef HYDRANFC +#if defined(HYDRANFC) || defined(HYDRANFC_V2) t_token tokens_mode_nfc_show[] = { { @@ -369,20 +373,32 @@ t_token tokens_mode_nfc_sniff[] = { { } }; -#define NFC_PARAMETERS \ +// For future add selection of NFC A/B/V/F to scan +/* {\ - T_TYPEA,\ - .help = "TypeA (ISO14443A => MIFARE...)"\ + T_NFCA,\ + .help = "NFC-A (ISO14443A => MIFARE...)"\ },\ {\ - T_VICINITY,\ - .help = "Vicinity (ISO/IEC 15693)"\ + T_NFCB,\ + .help = "NFC-B (ISO14443B)"\ },\ + {\ + T_NFCV,\ + .help = "NFC-V Vicinity (ISO/IEC 15693)"\ + },\ + {\ + T_NFCF,\ + .help = "NFC-F Felica"\ + },\ +*/ + +#define NFC_PARAMETERS \ {\ T_SCAN,\ - .subtokens = tokens_mode_nfc_scan,\ .help = "Scan"\ },\ +/* {\ T_READ_MF_ULTRALIGHT,\ .arg_type = T_ARG_STRING,\ @@ -419,6 +435,7 @@ t_token tokens_mode_nfc_sniff[] = { T_DIRECT_MODE_1,\ .help = "Enter Direct Mode 1 (IO5/PC4=CLK, IO6/PC2=Data)"\ }, +*/ t_token tokens_sd[]; t_token tokens_mode_nfc[] = { @@ -444,7 +461,7 @@ t_token tokens_nfc[] = { NFC_PARAMETERS { } }; -#endif /* ifdef HYDRANFC */ +#endif /* ifdef HYDRANFC or HYDRANFC_V2 */ t_token tokens_parity[] = { { T_NONE }, @@ -2141,7 +2158,7 @@ t_token tl_tokens[] = { .help = "UART mode", .help_full = "Configuration: uart [device (1/2)] [speed (value in bauds)] [parity (none/even/odd)] [stop-bits (1/2)]\r\nInteraction: " }, -#ifdef HYDRANFC +#if defined(HYDRANFC) || defined(HYDRANFC_V2) { T_NFC, .subtokens = tokens_nfc, diff --git a/src/hydrabus/commands.h b/src/hydrabus/commands.h index afe01e0..e0349fb 100644 --- a/src/hydrabus/commands.h +++ b/src/hydrabus/commands.h @@ -78,10 +78,14 @@ enum { T_PERIOD, T_CONTINUOUS, T_SCAN, -#ifdef HYDRANFC +#if defined(HYDRANFC) || defined(HYDRANFC_V2) T_NFC, - T_TYPEA, - T_VICINITY, + /* + T_NFCA, + T_NFCB, + T_NFCV, + T_NFCF, + */ T_EMUL_MIFARE, T_EMUL_ISO14443A, T_REGISTERS, diff --git a/src/hydrabus/hydrabus_mode.c b/src/hydrabus/hydrabus_mode.c index 7b0ca36..76f08e1 100644 --- a/src/hydrabus/hydrabus_mode.c +++ b/src/hydrabus/hydrabus_mode.c @@ -55,7 +55,7 @@ extern const mode_exec_t mode_smartcard_exec; extern t_token tokens_mode_spi[]; extern t_token tokens_mode_i2c[]; extern t_token tokens_mode_uart[]; -#ifdef HYDRANFC +#if defined(HYDRANFC) || defined(HYDRANFC_V2) extern t_token tokens_mode_nfc[]; #endif extern t_token tokens_mode_jtag[]; @@ -76,7 +76,7 @@ static struct { { T_SPI, tokens_mode_spi, &mode_spi_exec }, { T_I2C, tokens_mode_i2c, &mode_i2c_exec }, { T_UART, tokens_mode_uart, &mode_uart_exec }, -#ifdef HYDRANFC +#if defined(HYDRANFC) || defined(HYDRANFC_V2) { T_NFC, tokens_mode_nfc, &mode_nfc_exec }, #endif { T_JTAG, tokens_mode_jtag, &mode_jtag_exec }, diff --git a/src/hydranfc/hydranfc.c b/src/hydranfc/hydranfc.c index 2792090..141020c 100644 --- a/src/hydranfc/hydranfc.c +++ b/src/hydranfc/hydranfc.c @@ -814,7 +814,7 @@ static void scan(t_hydra_console *con) { mode_config_proto_t* proto = &con->mode->proto; - if (proto->config.hydranfc.dev_function == NFC_TYPEA) + if (proto->config.hydranfc.dev_function == NFC_A) hydranfc_scan_mifare(con); else if (proto->config.hydranfc.dev_function == NFC_VICINITY) hydranfc_scan_vicinity(con); diff --git a/src/hydranfc_v2/hal.mk b/src/hydranfc_v2/hal.mk new file mode 100644 index 0000000..a4c81f6 --- /dev/null +++ b/src/hydranfc_v2/hal.mk @@ -0,0 +1,16 @@ +# List of all the HydraNFC v2 hal related files. +HYDRANFC_V2_HAL_SRC = hydranfc_v2/hal/src/led.c \ + hydranfc_v2/hal/src/logger.c \ + hydranfc_v2/hal/src/spi.c \ + hydranfc_v2/hal/src/stream_dispatcher.c \ + hydranfc_v2/hal/src/timer.c \ + hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_core.c \ + hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_ctlreq.c \ + hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_ioreq.c \ + hydranfc_v2/hal/src/stm32_usb_device_library_class_customhid/src/usbd_customhid.c \ + hydranfc_v2/hal/src/rfal_analogConfigCustomTbl.c + +# Required include directories +HYDRANFC_V2_HAL_INC = ./hydranfc_v2/hal/inc \ + ./hydranfc_v2/hal/src/stm32_usb_device_library_core/inc \ + ./hydranfc_v2/hal/src/stm32_usb_device_library_class_customhid/inc diff --git a/src/hydranfc_v2/hal/inc/dispatcher.h b/src/hydranfc_v2/hal/inc/dispatcher.h new file mode 100644 index 0000000..61a09a0 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/dispatcher.h @@ -0,0 +1,66 @@ +/****************************************************************************** + * @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: ST25R3911 firmware + * $Revision: $ + * LANGUAGE: ANSI C + */ + +/*! \file + * + * \author Ulrich Herrmann + * + * \brief Application dispatcher + * + */ +/*! + * + * Moudle used to dispatch the commands received by the PC application. + */ + +#ifndef DISPATCHER_H +#define DISPATCHER_H + +/* +****************************************************************************** +* INCLUDES +****************************************************************************** +*/ + +/* +****************************************************************************** +* GLOBAL FUNCTION PROTOTYPES +****************************************************************************** +*/ + +/*! + ***************************************************************************** + * \brief Handle interrupt requests which are targetted for the dispatcher + * + * The GUI may enable interrupts and read out proper results at the time of the + * interrupt. + * This function handles these interrupts and stores the results for a later + * time when the GUI polls it. + */ +extern void dispatcherWorker(void); + +#endif /* DISPATCHER_H */ + diff --git a/src/hydranfc_v2/hal/inc/hydranfc_v2_common.h b/src/hydranfc_v2/hal/inc/hydranfc_v2_common.h new file mode 100644 index 0000000..849a75b --- /dev/null +++ b/src/hydranfc_v2/hal/inc/hydranfc_v2_common.h @@ -0,0 +1,67 @@ +/** + ****************************************************************************** + * @file hydranfc_v2_common.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief Header for main.c module + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2016 STMicroelectronics

+ * + * Licensed under MMY-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __HYDRANFC_V2_COMMON_H +#define __HYDRANFC_V2_COMMON_H + +/* Includes ------------------------------------------------------------------*/ +#include "stdint.h" +#include +#include "math.h" +//#include "st25_discovery_nfctag.h" +//#include "tagtype5_wrapper.h" + +/* Exported types ------------------------------------------------------------*/ +//typedef uint8_t boolean; + + +/* Exported macro ------------------------------------------------------------*/ + +#undef FAIL +#define FAIL 0 + +#undef PASS +#define PASS !FAIL + +/* Exported constants --------------------------------------------------------*/ +#define MAX_NDEF_MEM ((uint32_t)0xC00) +#define NFC_DEVICE_MAX_NDEFMEMORY ((uint32_t)MAX_NDEF_MEM) + +#define RESULTOK 0x00 +#define ERRORCODE_GENERIC 1 +/* Exported functions ------------------------------------------------------- */ + +typedef enum { + NFCTAG_OK = 0, + NFCTAG_ERROR, + NFCTAG_RESPONSE_ERROR +} NFCTAG_StatusTypeDef; + +#endif /* __HYDRANFC_V2_COMMON_H */ + +/************************ (C) COPYRIGHT 2016 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/inc/led.h b/src/hydranfc_v2/hal/inc/led.h new file mode 100644 index 0000000..b3b03ab --- /dev/null +++ b/src/hydranfc_v2/hal/inc/led.h @@ -0,0 +1,81 @@ +/****************************************************************************** + * @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: ST25R3911 firmware + * $Revision: $ + * LANGUAGE: ANSI C + */ + +/*! \file + * + * \author + * + * \brief Module for controlling shield LEDs + * + */ +/*! + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef LED_H +#define LED_H + +/* Includes ------------------------------------------------------------------*/ +#include "stdint.h" + +/* +****************************************************************************** +* GLOBAL DEFINES +****************************************************************************** +*/ +extern volatile uint16_t msLedA; +extern volatile uint16_t msLedB; +extern volatile uint16_t msLedF; +extern volatile uint16_t msLedV; +extern volatile uint16_t msLedAP2P; + + +typedef enum +{ + LED_A = 0x1, + LED_B = 0x2, + LED_F = 0x3, + LED_V = 0x4, + LED_AP2P = 0x5, +}st25R3911Led_t; + +/* +****************************************************************************** +* GLOBAL MACROS +****************************************************************************** +*/ + +void ledOn(st25R3911Led_t Led); +void ledOff(st25R3911Led_t Led); +void ledToggle(st25R3911Led_t Led); + +#define VISUAL_FEEDBACK_DELAY 600 +void ledOnOff(st25R3911Led_t Led, uint32_t delay); +void ledFeedbackHandler(void); + +#endif /* LED_H */ + diff --git a/src/hydranfc_v2/hal/inc/logger.h b/src/hydranfc_v2/hal/inc/logger.h new file mode 100644 index 0000000..9cade61 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/logger.h @@ -0,0 +1,108 @@ +/****************************************************************************** + * @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: + * $Revision: $ + * LANGUAGE: ANSI C + */ + +/*! \file + * + * \author + * + * \brief Serial output log declaration file + * + */ + +/*! + * + * This driver provides a printf-like way to output log messages + * via the UART interface. It makes use of the uart driver. + * + */ + +#ifndef LOGGER_H +#define LOGGER_H + +/* +****************************************************************************** +* INCLUDES +****************************************************************************** +*/ +#include "platform.h" + +#if (USE_LOGGER == LOGGER_OFF && !defined(HAL_UART_MODULE_ENABLED)) + #define UART_HandleTypeDef void +#endif + +/* +****************************************************************************** +* DEFINES +****************************************************************************** +*/ +#define LOGGER_ON 1 +#define LOGGER_OFF 0 + +/*! + ***************************************************************************** + * \brief Writes out a formated string via UART interface + * + * This function is used to write a formated string via the UART interface. + * + ***************************************************************************** + */ +extern void logUsartInit(UART_HandleTypeDef *husart); + +/*! + ***************************************************************************** + * \brief Writes out a formated string via UART interface + * + * This function is used to write a formated string via the UART interface. + * + ***************************************************************************** + */ +extern int logUsart(const char* format, ...); + +/*! + ***************************************************************************** + * \brief Writes out a formated string via ITM interface + * + * This function is used to write a formated string via the ITM interface. + * + ***************************************************************************** + */ +extern int logITM(const char* format, ...); +/*! + ***************************************************************************** + * \brief helper to convert hex data into formated string + * + * \param[in] data : pointer to buffer to be dumped. + * + * \param[in] dataLen : buffer length + * + * \return hex formated string + * + ***************************************************************************** + */ +extern char* hex2Str(unsigned char * data, size_t dataLen); + +#endif /* LOGGER_H */ + diff --git a/src/hydranfc_v2/hal/inc/platform.h b/src/hydranfc_v2/hal/inc/platform.h new file mode 100644 index 0000000..4e86e35 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/platform.h @@ -0,0 +1,253 @@ +/* + * HydraBus/HydraNFC v2 + * + * Copyright (C) 2020 Benjamin VERNOUX + * + * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PLATFORM_H +#define PLATFORM_H + +/* Platform definitions for ST25RFAL002 V2.2.0 / 22-May-2020 */ + +/* +****************************************************************************** +* INCLUDES +****************************************************************************** +*/ +#include +#include +#include +#include + +// hydrafw\src\drv\stm32cube\bsp.h +#include "bsp.h" +#include "bsp_spi.h" +#include "hydranfc_v2_common.h" + +#include "st_errno.h" + +#include "spi.h" +#include "timer.h" + +void DelayMs(uint32_t delay_ms); +void rfalPreTransceiveCb(void); + +/* USER CODE END Private defines */ + +#ifdef __cplusplus + extern "C" { +#endif +void _Error_Handler(char *, int); + +#define Error_Handler() _Error_Handler(__FILE__, __LINE__) +#ifdef __cplusplus +} +#endif + +/* +****************************************************************************** +* GLOBAL DEFINES +****************************************************************************** +*/ +#define ST25R391X_SPI_DEVICE BSP_DEV_SPI2 + +#define ST25R_COM_SINGLETXRX /*!< Use single Transceive */ +#define ST25R_SS_PIN GPIO_PIN_1 /*!< GPIO pin used for ST25R SPI SS */ +#define ST25R_SS_PORT GPIOC /*!< GPIO port used for ST25R SPI SS port */ +#define ST25R_INT_PIN GPIO_PIN_1 /*!< GPIO pin used for ST25R External Interrupt */ +#define ST25R_INT_PORT GPIOA /*!< GPIO port used for ST25R External Interrupt */ + +#ifdef LED_FIELD_Pin +#define PLATFORM_LED_FIELD_PIN LED_FIELD_Pin /*!< GPIO pin used as field LED */ +#endif + +#ifdef LED_FIELD_GPIO_Port +#define PLATFORM_LED_FIELD_PORT LED_FIELD_GPIO_Port /*!< GPIO port used as field LED */ +#endif + +#ifdef LED_RX_Pin +#define PLATFORM_LED_RX_PIN LED_RX_Pin /*!< GPIO pin used as field LED */ +#endif + +#ifdef LED_RX_GPIO_Port +#define PLATFORM_LED_RX_PORT LED_RX_GPIO_Port /*!< GPIO port used as field LED */ +#endif + +/* +****************************************************************************** +* GLOBAL MACROS +****************************************************************************** +*/ +#define HAL_Delay(Delay) ( DelayMs(Delay) ) +#define HAL_GetTickMs() ( (HAL_GetTick()/10) ) // On HydraBus HAL_GetTick returns common/chconf.h/CH_CFG_ST_FREQUENCY set by default to 10000 for accurate ticks +#define HAL_GetTick() ( HAL_GetTickMs() ) +#define _Error_Handler(__FILE__, __LINE__) // Ignore errors + +//#define platformProtectST25RComm() do{ globalCommProtectCnt++; __DSB();NVIC_DisableIRQ(EXTI0_IRQn);__DSB();__ISB();}while(0) /*!< Protect unique access to ST25R communication channel - IRQ disable on single thread environment (MCU) ; Mutex lock on a multi thread environment */ +//#define platformUnprotectST25RComm() do{ if (--globalCommProtectCnt==0) {NVIC_EnableIRQ(EXTI0_IRQn);} }while(0) /*!< Unprotect unique access to ST25R communication channel - IRQ enable on a single thread environment (MCU) ; Mutex unlock on a multi thread environment */ +#define platformProtectST25RComm() do{ globalCommProtectCnt++; __DSB();NVIC_DisableIRQ(EXTI15_10_IRQn);__DSB();__ISB();}while(0) /*!< Protect unique access to ST25R391x communication channel - IRQ disable on single thread environment (MCU) ; Mutex lock on a multi thread environment */ +#define platformUnprotectST25RComm() do{ if (--globalCommProtectCnt==0) {NVIC_EnableIRQ(EXTI15_10_IRQn);} }while(0) /*!< Unprotect unique access to ST25R391x communication channel - IRQ enable on a single thread environment (MCU) ; Mutex unlock on a multi thread environment */ + +#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 platformLedOff( port, pin ) platformGpioClear((port), (pin)) /*!< Turns the given LED Off */ +#define platformLedOn( port, pin ) platformGpioSet((port), (pin)) /*!< Turns the given LED On */ +#define platformLedToogle( port, pin ) platformGpioToogle((port), (pin)) /*!< Toogle the given LED */ + +#define platformGpioSet( port, pin ) HAL_GPIO_WritePin(port, pin, GPIO_PIN_SET) /*!< Turns the given GPIO High */ +#define platformGpioClear( port, pin ) HAL_GPIO_WritePin(port, pin, GPIO_PIN_RESET) /*!< Turns the given GPIO Low */ +#define platformGpioToogle( port, pin ) HAL_GPIO_TogglePin(port, pin) /*!< Toogles the given GPIO */ +#define platformGpioIsHigh( port, pin ) (HAL_GPIO_ReadPin(port, pin) == GPIO_PIN_SET) /*!< 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 ) HAL_Delay( t ) /*!< Performs a delay for the given time (ms) */ + +#define platformGetSysTick() HAL_GetTick() /*!< Get System Tick (1 tick = 1 ms) */ + +#define platformAssert( exp ) assert_param( exp ) /*!< Asserts whether the given expression is true */ +#define platformErrorHandle() _Error_Handler(__FILE__, __LINE__) /*!< Global error handle\trap */ + +#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 platformSpiTxRx(txBuf, rxBuf, len) hal_st25r3916_spiTxRx(txBuf, rxBuf, len) /*!< SPI transceive */ + +/* I2C not used disabled */ +#if 0 +#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 */ +#endif + +#define platformLog(...) +#define LOGGER_ON 1 +#define LOGGER_OFF 0 +#define USE_LOGGER LOGGER_OFF + +/* +****************************************************************************** +* GLOBAL VARIABLES +****************************************************************************** +*/ +extern uint8_t globalCommProtectCnt; /* Global Protection Counter provided per platform - instantiated in hydranfc_v2.c */ + +/* +****************************************************************************** +* RFAL FEATURES 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 false /*!< 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 true /*!< Enable/Disable Analog Configs to be dynamically updated (RAM) */ +#define RFAL_FEATURE_DPO true /*!< Enable/Disable RFAL Dynamic Power Output support */ +#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. */ + +/* Use HydraNFC Shield v2 RFAL Analog Config Custom */ +#define RFAL_ANALOG_CONFIG_CUSTOM true +// Custom configuration is defined in rfal_analogConfigCustomTbl.c + +/* SELFTEST Helpfull to diagnose porting issues. */ +#define ST25R_SELFTEST +#define ST25R_SELFTEST_TIMER + +/* + ****************************************************************************** + * 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 */ + +#endif /* PLATFORM_H */ diff --git a/src/hydranfc_v2/hal/inc/platform.h.bak b/src/hydranfc_v2/hal/inc/platform.h.bak new file mode 100644 index 0000000..3f35e24 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/platform.h.bak @@ -0,0 +1,255 @@ +/* + * HydraBus/HydraNFC v2 + * + * Copyright (C) 2020 Benjamin VERNOUX + * + * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PLATFORM_H +#define PLATFORM_H + +/* Platform definitions for ST25RFAL002 V2.2.0 / 22-May-2020 */ + +/* +****************************************************************************** +* INCLUDES +****************************************************************************** +*/ +#include +#include +#include +#include + +// hydrafw\src\drv\stm32cube\bsp.h +#include "bsp.h" +#include "bsp_spi.h" +#include "hydranfc_v2_common.h" + +#include "st_errno.h" + +#include "spi.h" +#include "timer.h" + +void DelayMs(uint32_t delay_ms); +void rfalPreTransceiveCb(void); + +/* USER CODE END Private defines */ + +#ifdef __cplusplus + extern "C" { +#endif +void _Error_Handler(char *, int); + +#define Error_Handler() _Error_Handler(__FILE__, __LINE__) +#ifdef __cplusplus +} +#endif + +/* +****************************************************************************** +* GLOBAL DEFINES +****************************************************************************** +*/ +#define ST25R391X_SPI_DEVICE BSP_DEV_SPI2 + +#define ST25R_COM_SINGLETXRX /*!< Use single Transceive */ +#define ST25R_SS_PIN GPIO_PIN_1 /*!< GPIO pin used for ST25R SPI SS */ +#define ST25R_SS_PORT GPIOC /*!< GPIO port used for ST25R SPI SS port */ +#define ST25R_INT_PIN GPIO_PIN_1 /*!< GPIO pin used for ST25R External Interrupt */ +#define ST25R_INT_PORT GPIOA /*!< GPIO port used for ST25R External Interrupt */ + +#ifdef LED_FIELD_Pin +#define PLATFORM_LED_FIELD_PIN LED_FIELD_Pin /*!< GPIO pin used as field LED */ +#endif + +#ifdef LED_FIELD_GPIO_Port +#define PLATFORM_LED_FIELD_PORT LED_FIELD_GPIO_Port /*!< GPIO port used as field LED */ +#endif + +#ifdef LED_RX_Pin +#define PLATFORM_LED_RX_PIN LED_RX_Pin /*!< GPIO pin used as field LED */ +#endif + +#ifdef LED_RX_GPIO_Port +#define PLATFORM_LED_RX_PORT LED_RX_GPIO_Port /*!< GPIO port used as field LED */ +#endif + +/* +****************************************************************************** +* GLOBAL MACROS +****************************************************************************** +*/ +#define HAL_Delay(Delay) ( DelayMs(Delay) ) +#define HAL_GetTickMs() ( (HAL_GetTick()/10) ) // On HydraBus HAL_GetTick returns common/chconf.h/CH_CFG_ST_FREQUENCY set by default to 10000 for accurate ticks +#define HAL_GetTick() ( HAL_GetTickMs() ) +#define _Error_Handler(__FILE__, __LINE__) // Ignore errors + +//#define platformProtectST25RComm() do{ globalCommProtectCnt++; __DSB();NVIC_DisableIRQ(EXTI0_IRQn);__DSB();__ISB();}while(0) /*!< Protect unique access to ST25R communication channel - IRQ disable on single thread environment (MCU) ; Mutex lock on a multi thread environment */ +//#define platformUnprotectST25RComm() do{ if (--globalCommProtectCnt==0) {NVIC_EnableIRQ(EXTI0_IRQn);} }while(0) /*!< Unprotect unique access to ST25R communication channel - IRQ enable on a single thread environment (MCU) ; Mutex unlock on a multi thread environment */ +#define platformProtectST25RComm() do{ globalCommProtectCnt++; __DSB();NVIC_DisableIRQ(EXTI15_10_IRQn);__DSB();__ISB();}while(0) /*!< Protect unique access to ST25R391x communication channel - IRQ disable on single thread environment (MCU) ; Mutex lock on a multi thread environment */ +#define platformUnprotectST25RComm() do{ if (--globalCommProtectCnt==0) {NVIC_EnableIRQ(EXTI15_10_IRQn);} }while(0) /*!< Unprotect unique access to ST25R391x communication channel - IRQ enable on a single thread environment (MCU) ; Mutex unlock on a multi thread environment */ + +#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 platformLedOff( port, pin ) platformGpioClear((port), (pin)) /*!< Turns the given LED Off */ +#define platformLedOn( port, pin ) platformGpioSet((port), (pin)) /*!< Turns the given LED On */ +#define platformLedToogle( port, pin ) platformGpioToogle((port), (pin)) /*!< Toogle the given LED */ + +#define platformGpioSet( port, pin ) HAL_GPIO_WritePin(port, pin, GPIO_PIN_SET) /*!< Turns the given GPIO High */ +#define platformGpioClear( port, pin ) HAL_GPIO_WritePin(port, pin, GPIO_PIN_RESET) /*!< Turns the given GPIO Low */ +#define platformGpioToogle( port, pin ) HAL_GPIO_TogglePin(port, pin) /*!< Toogles the given GPIO */ +#define platformGpioIsHigh( port, pin ) (HAL_GPIO_ReadPin(port, pin) == GPIO_PIN_SET) /*!< 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 ) HAL_Delay( t ) /*!< Performs a delay for the given time (ms) */ + +#define platformGetSysTick() HAL_GetTick() /*!< Get System Tick (1 tick = 1 ms) */ + +#define platformAssert( exp ) assert_param( exp ) /*!< Asserts whether the given expression is true */ +#define platformErrorHandle() _Error_Handler(__FILE__, __LINE__) /*!< Global error handle\trap */ + +#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 platformSpiTxRx(txBuf, rxBuf, len) hal_st25r3916_spiTxRx(txBuf, rxBuf, len) /*!< SPI transceive */ + +/* I2C not used disabled */ +#if 0 +#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 */ +#endif + +#define platformLog(...) +#define LOGGER_ON 1 +#define LOGGER_OFF 0 +#define USE_LOGGER LOGGER_OFF + +/* +****************************************************************************** +* GLOBAL VARIABLES +****************************************************************************** +*/ +extern uint8_t globalCommProtectCnt; /* Global Protection Counter provided per platform - instantiated in hydranfc_v2.c */ + +/* +****************************************************************************** +* RFAL FEATURES 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 false /*!< 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 true /*!< Enable/Disable Analog Configs to be dynamically updated (RAM) */ +#define RFAL_FEATURE_DPO true /*!< 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. */ + +/* Use HydraNFC Shield v2 RFAL Analog Config Custom */ +#define RFAL_ANALOG_CONFIG_CUSTOM true +/* Custim configuration is defined in rfal_analogConfigCustomTbl.c */ +extern const uint8_t* rfalAnalogConfigCustomSettings; +extern const uint16_t rfalAnalogConfigCustomSettingsLength; + +/* SELFTEST Helpfull to diagnose porting issues. */ +#define ST25R_SELFTEST +#define ST25R_SELFTEST_TIMER + +/* + ****************************************************************************** + * 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 */ + +#endif /* PLATFORM_H */ diff --git a/src/hydranfc_v2/hal/inc/spi.h b/src/hydranfc_v2/hal/inc/spi.h new file mode 100644 index 0000000..2d8fd2e --- /dev/null +++ b/src/hydranfc_v2/hal/inc/spi.h @@ -0,0 +1,104 @@ +/** + ****************************************************************************** + * COPYRIGHT(c) 2016 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 + * + * \author + * + * \brief SPI communication header file + * + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __spi_H +#define __spi_H + +/* Includes ------------------------------------------------------------------*/ +#include "platform.h" + +/*! + ***************************************************************************** + * \brief Initalize SPI + * + * This function initalize the SPI handle. + * + * \param[in] dev_num : bsp_dev_spi_t device number + * + ***************************************************************************** + */ +void hal_st25r3916_spiInit(bsp_dev_spi_t dev_num); + +/*! + ***************************************************************************** + * \brief Set SPI CS line + * + * \param[in] ssPort : pointer CS gpio port + * + * \param[in] ssPin : CS pin + * + * \return : none + * + ***************************************************************************** + */ +void hal_st25r3916_spiSelect(GPIO_TypeDef *ssPort, uint16_t ssPin); + +/*! + ***************************************************************************** + * \brief Reset SPI CS line + * + * \param[in] ssPort : pointer CS gpio port + * + * \param[in] ssPin : CS pin + * + * \return : none + * + ***************************************************************************** + */ +void hal_st25r3916_spiDeselect(GPIO_TypeDef *ssPort, uint16_t ssPin); + +/*! + ***************************************************************************** + * \brief Transmit Receive data + * + * This funtion transmits first no of "length" bytes from "txData" and tries + * then to receive "length" bytes. + * + * \param[in] txData : pointer to buffer to be transmitted. + * + * \param[out] rxData : pointer to buffer to be received. + * + * \param[in] length : buffer length + * + * \return : HAL error code + * + ***************************************************************************** + */ +HAL_StatusTypeDef hal_st25r3916_spiTxRx(const uint8_t *txData, uint8_t *rxData, uint16_t length); + +#endif /*__spi_H */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/inc/st_errno.h b/src/hydranfc_v2/hal/inc/st_errno.h new file mode 100644 index 0000000..747628b --- /dev/null +++ b/src/hydranfc_v2/hal/inc/st_errno.h @@ -0,0 +1,165 @@ + +/****************************************************************************** + * \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: + * + * 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 +****************************************************************************** +*/ + + +/* +****************************************************************************** +* 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 + */ + +#define ERR_NONE ((ReturnCode)0U) /*!< no error occurred */ +#define ERR_NOMEM ((ReturnCode)1U) /*!< not enough memory to perform the requested operation */ +#define ERR_BUSY ((ReturnCode)2U) /*!< device or resource busy */ +#define ERR_IO ((ReturnCode)3U) /*!< generic IO error */ +#define ERR_TIMEOUT ((ReturnCode)4U) /*!< error due to timeout */ +#define ERR_REQUEST ((ReturnCode)5U) /*!< invalid request or requested function can't be executed at the moment */ +#define ERR_NOMSG ((ReturnCode)6U) /*!< No message of desired type */ +#define ERR_PARAM ((ReturnCode)7U) /*!< Parameter error */ +#define ERR_SYSTEM ((ReturnCode)8U) /*!< System error */ +#define ERR_FRAMING ((ReturnCode)9U) /*!< Framing error */ +#define ERR_OVERRUN ((ReturnCode)10U) /*!< lost one or more received bytes */ +#define ERR_PROTO ((ReturnCode)11U) /*!< protocol error */ +#define ERR_INTERNAL ((ReturnCode)12U) /*!< Internal Error */ +#define ERR_AGAIN ((ReturnCode)13U) /*!< Call again */ +#define ERR_MEM_CORRUPT ((ReturnCode)14U) /*!< memory corruption */ +#define ERR_NOT_IMPLEMENTED ((ReturnCode)15U) /*!< not implemented */ +#define ERR_PC_CORRUPT ((ReturnCode)16U) /*!< Program Counter has been manipulated or spike/noise trigger illegal operation */ +#define ERR_SEND ((ReturnCode)17U) /*!< error sending*/ +#define ERR_IGNORE ((ReturnCode)18U) /*!< indicates error detected but to be ignored */ +#define ERR_SEMANTIC ((ReturnCode)19U) /*!< indicates error in state machine (unexpected cmd) */ +#define ERR_SYNTAX ((ReturnCode)20U) /*!< indicates error in state machine (unknown cmd) */ +#define ERR_CRC ((ReturnCode)21U) /*!< crc error */ +#define ERR_NOTFOUND ((ReturnCode)22U) /*!< transponder not found */ +#define ERR_NOTUNIQUE ((ReturnCode)23U) /*!< transponder not unique - more than one transponder in field */ +#define ERR_NOTSUPP ((ReturnCode)24U) /*!< requested operation not supported */ +#define ERR_WRITE ((ReturnCode)25U) /*!< write error */ +#define ERR_FIFO ((ReturnCode)26U) /*!< fifo over or underflow error */ +#define ERR_PAR ((ReturnCode)27U) /*!< parity error */ +#define ERR_DONE ((ReturnCode)28U) /*!< transfer has already finished */ +#define ERR_RF_COLLISION ((ReturnCode)29U) /*!< collision error (Bit Collision or during RF Collision avoidance ) */ +#define ERR_HW_OVERRUN ((ReturnCode)30U) /*!< lost one or more received bytes */ +#define ERR_RELEASE_REQ ((ReturnCode)31U) /*!< device requested release */ +#define ERR_SLEEP_REQ ((ReturnCode)32U) /*!< device requested sleep */ +#define ERR_WRONG_STATE ((ReturnCode)33U) /*!< incorrent state for requested operation */ +#define ERR_MAX_RERUNS ((ReturnCode)34U) /*!< blocking procedure reached maximum runs */ +#define ERR_DISABLED ((ReturnCode)35U) /*!< operation aborted due to disabled configuration */ +#define ERR_HW_MISMATCH ((ReturnCode)36U) /*!< expected hw do not match */ +#define ERR_LINK_LOSS ((ReturnCode)37U) /*!< Other device's field didn't behave as expected: turned off by Initiator in Passive mode, or AP2P did not turn on field */ +#define ERR_INVALID_HANDLE ((ReturnCode)38U) /*!< invalid or not initalized device handle */ + +#define ERR_INCOMPLETE_BYTE ((ReturnCode)40U) /*!< Incomplete byte rcvd */ +#define ERR_INCOMPLETE_BYTE_01 ((ReturnCode)41U) /*!< Incomplete byte rcvd - 1 bit */ +#define ERR_INCOMPLETE_BYTE_02 ((ReturnCode)42U) /*!< Incomplete byte rcvd - 2 bit */ +#define ERR_INCOMPLETE_BYTE_03 ((ReturnCode)43U) /*!< Incomplete byte rcvd - 3 bit */ +#define ERR_INCOMPLETE_BYTE_04 ((ReturnCode)44U) /*!< Incomplete byte rcvd - 4 bit */ +#define ERR_INCOMPLETE_BYTE_05 ((ReturnCode)45U) /*!< Incomplete byte rcvd - 5 bit */ +#define ERR_INCOMPLETE_BYTE_06 ((ReturnCode)46U) /*!< Incomplete byte rcvd - 6 bit */ +#define ERR_INCOMPLETE_BYTE_07 ((ReturnCode)47U) /*!< 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) ((uint16_t)(x) & 0x00FFU) /*!< Mask the error number */ + + + +/*! Common code to exit a function with the error if function f return error */ +#define EXIT_ON_ERR(r, f) \ + (r) = (f); \ + if (ERR_NONE != (r)) \ + { \ + return (r); \ + } + +#endif /* ST_ERRNO_H */ + diff --git a/src/hydranfc_v2/hal/inc/st_stream.h b/src/hydranfc_v2/hal/inc/st_stream.h new file mode 100644 index 0000000..68e3403 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/st_stream.h @@ -0,0 +1,474 @@ +/****************************************************************************** + * @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: ST Streaming Communication + * $Revision: $ + * LANGUAGE: C++ + */ + +/*! \file st_stream.h + * + * \author M. Arpa + * + * \brief Constants shared between GUI and firmware concerning the st + * streaming communication. + */ + +#ifndef ST_STREAM_H +#define ST_STREAM_H + + + + +/* This is an example describing the streaming communication between + a PC Host and a MCU device using USB HID for transporting + the streaming packets. + + If you do not use USB HID but some other protocol your byte stream + will look different in point 3. + + Point 3. was added to show a full stack. + + + ============================================================================= + + From Host to Device: + + ------------------------------------------------------ + + On the physical line the following byte-stream is seen: + + Byte 0 1 2 3 4 5 6 7 8 (8 + tx-prot) (9+tx-prot) (10+tx-prot) + +------+-------+-------+----------+---------+---------+---------+---------+-------...---+-------------+-----------+-----------+------- + | TID |payload|re- | protocol | tx-prot | tx-prot | rx-prot | rx-prot | data | protocol B | tx-prot B | tx-prot B | + | | | served| | MSB | LSB | MSB | LSB | | | MSB | LSB | + +------+-------+-------+----------+---------+---------+---------+---------+-------...---+-------------+-----------+-----------+------- + + TID = the transaction ID is changed with every report sent. + payload = the amount of data in this report (sent from host to device) - a packet can be longer than + this size (i.e. the packet is sent with several reports - note *) + tx-prot = number of bytes transmitted (for this protocol packet) from host to device + rx-prot = number ob bytes expected to be received (for this protocol packet) from device + + *) if a packet cannot be sent in one report the next report will not have the "protocol header" set again, + but continue with the raw data. + + + This bytestream is build through the following 3 steps: + + ------------------------------------------------------ + + 1. The STComObject class provides a single data packet: + + Byte 0 1 ... tx-size -1 + +------------+-------- ... ----------------------------+ + | data | + +--------------------- ... ----------------------------+ + + + ------------------------------------------------------ + + 2. The stream driver on the Host side takes a single data packet and adds the protocol header : + + Byte 0 1 2 3 4 5 4 + tx-size + +------------+---------+---------+---------+---------+-------------------------- ... ------------------+ + | protocol | tx-prot | tx-prot | rx-prot | rx-prot | data | + | | MSB | LSB | MSB | LSB | | + +------------+---------+---------+---------+---------+-------------------------- ... ------------------+ + ^ ^ + | | + +----- this is the protocol header ------------------+ + + ^ ^ + | | + +----this is given to the HID driver as a single packet -----------------------------------------------+ + + + Steps 1. and 2. can be repeated several times for sending more than 1 packet in a single HID report. + + ------------------------------------------------------ + + 3. The Hid driver on the Host side adds for each Hid Report (the following report header): + + a) if the data-buffer fits in one HID-report: + + Byte 0 1 2 3 2+ payload .... 63 + +------+-------+------+----------+---... +-------------+------- -----------+ + | TID |payload|res. | packet(s) | padding if necessary | + +------+-------+------+----------+---...-+-------------+-------.... -----------+ + ^ ^ + | | + +---------------------+ + this is the HID + driver header + + b) if the packet(s) need more than 1 HID-report + + Byte 0 1 2 3 .... 63 + +------+-------+------+----------+---... +-------------+------- -----------+ + | TID |payload|res. | packet(s) | + | | = 61 | | | + +------+-------+------+----------+---...-+-------------+-------.... -----------+ + + +------+-------+------+----------+---... +-------------+------- -----------+ + | new |payload|res. | packet(s) | + | TID | = 61 | | continued | + +------+-------+------+----------+---...-+-------------+-------.... -----------+ + + .... as many HID reports as needed until the packet(s) are totally + transmitted (here is how the final report might look like): + + +------+-------+------+----------+---... +-------------+------- -----------+ + | next |payload|res. | packet(s) | padding if necessary | + | TID | <= 61 | | continued | | + +------+-------+------+----------+---...-+-------------+-------.... -----------+ + + + */ + + + +/* ============================================================================= + + From Device to Host: + + ------------------------------------------------------ + + On the physical line the following byte-stream is seen: + + Byte 0 1 2 3 4 5 6 7 8 (8 + tx-prot) (9+tx-prot) (10+tx-prot) + +------+-------+-------+----------+---------+---------+---------+---------+-------...---+-------------+-----------+-----------+------- + | TID |payload|HID | protocol | reserved| protocol| tx-prot | tx-prot | data | protocol B | reserved | status B | + | | | status| | | status | MSB | LSB | | | | + +------+-------+-------+----------+---------+---------+---------+---------+-------...---+-------------+-----------+-----------+------- + + TID = the transaction ID is reflected th every report sent. + payload = the amount of data in this report (sent from host to device) - a packet can be longer than + this size (i.e. the packet is sent with several reports - note *) + HID status = if a protocol was not processed (because e.g. the protocol id was unknown) the next HID + packet that is sent back will contain a HID status byte <> 0 indicating that an error + occurred (some time in the back). + protocol status = a single byte representing the result of the command if the command generated either data to + be sent back or is a read command (has the MSBit cleared) + tx-prot = number of bytes transmitted (for this protocol packet) from device to host + + *) if a packet cannot be sent in one report the next report will not have the "protocol header" set again, + but continue with the raw data. + + + This bytestream is build by through the following 3 steps: + + ------------------------------------------------------ + + 1. The Firmware-Application provides a single data packet containing the result: + + Byte 0 1 ... tx-size -1 + +------------+-------- ... ----------------------------+ + | data | + +--------------------- ... ----------------------------+ + + 2. The function processReceivedPackets of file stream_appl_handler.c in the firmware adds the protocol byte, + the reserved and the status byte and the tx-prot 16-bit word (from the information provided by the + firmware application): + + Byte 0 1 2 3 4 5 4 + tx-size + +------------+---------+---------+---------+---------+-------------------------- ... ------------------+ + | protocol | reserved| status | tx-prot | tx-prot | data | + | | | | MSB | LSB | | + +------------+---------+---------+---------+---------+-------------------------- ... ------------------+ + ^ ^ + | | + +----- this is the protocol header ------------------+ + + + Steps 1. and 2. can be repeated several times before handing a single buffer (containing all packets) + to the HID driver. + + ------------------------------------------------------ + + 3. The Hid driver on the Device side splits the buffer into Hid Reports and adds for each Hid Report + (the following report header): + + a) if the data-buffer fits in one HID-report: + + Byte 0 1 3 4 3+ payload .... 63 + +------+-------+-------+----------+---... +-------------+------- -----------+ + | TID |payload|status | packet(s) | padding if necessary | + +------+-------+-------+----------+---...-+-------------+-------.... -----------+ + ^ ^ + | | + +----------------------+ + this is the HID + driver header + + b) if the packet(s) need more than 1 HID-report + + Byte 0 1 2 3 .... 63 + +------+-------+------+----------+---... +-------------+------- -----------+ + | TID |payload|status| packet(s) | + | | = 61 | | | + +------+-------+------+----------+---...-+-------------+-------.... -----------+ + + +------+-------+------+----------+---... +-------------+------- -----------+ + | new |payload|status| packet(s) | + | TID | = 61 | | continued | + +------+-------+------+----------+---...-+-------------+-------.... -----------+ + + .... as many HID reports as needed until the packet(s) are totally + transmitted (here is how the final report might look like): + + +------+-------+------+----------+---... +-------------+------- -----------+ + | next |payload|status| packet(s) | padding if necessary | + | TID | <= 61 | | continued | | + +------+-------+------+----------+---...-+-------------+-------.... -----------+ + + */ + + +/* ============================================================================= + TID-Rules: + + On the host side, the TID is generated as a 4-bit number counting from 0 to 0x0F + and than rolling over to 0. + + The device side takes the TID received from the Host and moves it to the upper + nibble, increments its own TID counter by one (range is again 0 to 0x0F) and + adds its own TID counter. + txTID = (rxTID << 4) | ( ++txTID & 0xF ) + + */ + +/* ============================================================================= + Protocol-Rules: + + The MSBit of the protocol byte defines the direction: 1 = write, 0 = read. + This bit is set by the ST Stream class itself during sending or receiving. + + The following number range is special: + 0x60 - 0x7F: reserved for generic commands (part of the common firmware) + 0x60: is a configuration protocol for the firmware itself + 0x6B: is reserved for the bootloader + 0x7F: is reserved for the flush + + An application can use the numbers: 0x00 - 0x5F for its own commands. + + */ + + + +/* ------------- defines and macros ---------------------------------------- */ + +/* the stream adds a header to each packet of this size */ +#define ST_STREAM_HEADER_SIZE 5 + +/* macros to write the packet on the host side: HT = Host Transmitter */ +#define ST_STREAM_HT_SET_PROTOCOL( buf, prot ) do { (buf)[0] = (prot); } while ( 0 ) +#define ST_STREAM_HT_SET_TX_LENGTH( buf, len ) do { (buf)[1] = (len) >> 8; (buf)[2] = (len) & 0xFF; } while ( 0 ) +#define ST_STREAM_HT_SET_RX_LENGTH( buf, len ) do { (buf)[3] = (len) >> 8; (buf)[4] = (len) & 0xFF; } while ( 0 ) + +/* macros to read the packet on the device side: DR = Device Receiver */ +#define ST_STREAM_DR_GET_PROTOCOL( buf ) ( (buf)[0] ) +#define ST_STREAM_DR_GET_RX_LENGTH( buf ) ( ( ((unsigned short)((buf)[1])) << 8 ) | (buf)[2] ) +#define ST_STREAM_DR_GET_TX_LENGTH( buf ) ( ( ((unsigned short)((buf)[3])) << 8 ) | (buf)[4] ) + +/* macros to write the packet on the device side: DT = Device Transmitter */ +#define ST_STREAM_DT_SET_PROTOCOL( buf, prot ) do { (buf)[0] = (prot); } while ( 0 ) +#define ST_STREAM_DT_SET_STATUS( buf, stat ) do { (buf)[1] = 0; (buf)[2] = (stat); } while ( 0 ) +#define ST_STREAM_DT_SET_TX_LENGTH( buf, len ) do { (buf)[3] = (len) >> 8; (buf)[4] = (len) & 0xFF; } while ( 0 ) + +/* macros to read the packet on the host side: HR = Host Receiver */ +#define ST_STREAM_HR_GET_PROTOCOL( buf ) ( (buf)[0] ) +#define ST_STREAM_HR_GET_STATUS( buf ) ( (buf)[2] ) +#define ST_STREAM_HR_GET_RX_LENGTH( buf ) ( (((unsigned short)((buf)[3])) << 8 ) | (buf)[4] ) + +/* the payload starts after the header */ +#define ST_STREAM_PAYLOAD( buf ) ( (buf) + ST_STREAM_HEADER_SIZE ) + + +/* maximum amount of data that can be transported in a single packet */ +#define ST_STREAM_MAX_DATA_SIZE (1024 + 64) + +/* the size of a buffer to hold at least one packet + header */ +#define ST_STREAM_BUFFER_SIZE ( ST_STREAM_HEADER_SIZE + ST_STREAM_MAX_DATA_SIZE ) + + + +/* the size of the serialized i2c config object in byte */ +#define ST_STREAM_I2C_CONFIG_OBJ_LENGTH 7 + +/* deserializes the i2c_clock_speed (32-bit value) out of a serialized i2c config object */ +#define ST_STREAM_I2C_CONFIG_GET_CUSTOM_CLK_SPEED( buf ) ( (((unsigned long)((buf)[3])) << 24 ) | (((unsigned long)((buf)[4])) << 16 ) | (((unsigned long)((buf)[5])) << 8 ) | (buf)[6] ) + +/* serializes the i2c_clock_speed (32-bit value) into a byte array. position according to serialized i2c config object */ +#define ST_STREAM_I2C_CONFIG_SET_CUSTOM_CLK_SPEED( buf, speed ) do { (buf)[3] = ((speed) >> 24) & 0xFF; (buf)[4] = ((speed) >> 16) & 0xFF; (buf)[5] = ((speed) >> 8) & 0xFF; (buf)[6] = speed & 0xFF; } while ( 0 ) + + + + +/* all communication protocols that use the STComStream for communication + must define their protocol identifier here */ + +/* if the MSB bit is set this a command for write, else this is for read */ +#define ST_COM_WRITE_READ_NOT 0x80 + +/* protocol ids can range from 0x60 - 0x7f */ +#define ST_COM_CONFIG 0x60 /* reserved */ +#define ST_COM_I2C 0x61 +#define ST_COM_I2C_CONFIG 0x62 +#define ST_COM_SPI 0x63 +#define ST_COM_SPI_CONFIG 0x64 +#define ST_COM_CTRL_CMD_RESET 0x65 +#define ST_COM_CTRL_CMD_FW_INFORMATION 0x66 /* returns zero-terminated string with information about fw e.g. chip, board */ +#define ST_COM_CTRL_CMD_FW_NUMBER 0x67 /* returns the 3-byte FW number */ +#define ST_COM_WRITE_REG 0x68 +#define ST_COM_READ_REG 0x69 + +#define ST_COM_LOG_D2H 0x6A /* logging object from device to host only */ + +/* 0x6B = reserved protocol id + This will become 0xEB at sending because it is: + ST_COM_WRITE_READ_NOT | ST_COM_CTRL_CMD_ENTER_BOOTLOADER == 0x80 | 0x6B = 0xEB */ +#define ST_COM_CTRL_CMD_ENTER_BOOTLOADER 0x6B + + +/* 0x7F = reserved protocol id */ +#define ST_COM_FLUSH 0x7F + +/* currently available reserved numbers are: 0x6A and 0x6C - 0x7E */ + +/* all unused numbers between 0x00 and 0x5F are forwarded in the firmware (by the stream_dispatcher.c) + to the function + uint8_t applProcessCmd ( u8 protocol, u16 rxSize, const u8 * rxData, u16 * txSize, u8 * txData ) + A weak default implementation of this function is provided in weak_stream_functions.c + in the firmware that just flags an error. Implement this function in your + firmware to override the default behavior. +*/ + + +/* -------- additional defines ------------------------------------------- */ + +#define ST_COM_RESET_MCU 0x01 /* to reset the MCU use this as the objectToReset parameter */ +#define ST_COM_RESET_PERIPHERAL 0x02 /* to reset all peripherals use this */ +#define ST_STREAM_SHORT_STRING 0x40 /* a const char * must not point to something longer than this */ + +/* ST_CONFIG request format: + * + * Write request: write to Address = (Mask & Value) + * buf[ 0 ] = WORD_SIZE (either 1, 2, 4 ) + * buf[ 1 .. wordSize +1 ] = Address + * buf[ ... ] = Mask + * buf[ ... ] = Value to be written + * + * Read request: read from Address a 16-bit value + * buf[ 0 ] = WORD_SIZE (either 1, 2, 4 ) + * buf[ 1 .. wordSize +1 ] = Address + * Read response: + * buf[ 0 ] = WORD_SIZE (either 1, 2, 4 ) + * buf[ 1 .. wordSize +1 ] = Value + */ + +#define ST_CONFIG_WORD_SIZE_OFFSET 0 /* at position 0 we find the word size = 1, 2 or 4*/ +#define ST_CONFIG_PIC_WORD_SIZE 2 /* on the PIC 24F a word is 16-bit wide */ +#define ST_CONFIG_ARM_WORD_SIZE 4 /* on the ARM Cortex M0 a word is 32-bit wide */ + +/* write request is: reg-addr + mask + value == 3 * wordSize */ +#define ST_CONFIG_WRITE_REQUEST_LENGTH(wordSize) (3*(wordSize)) +/* read reqeust is: reg-addr */ +#define ST_CONFIG_READ_REQUEST_LENGTH(wordSize) (wordSize) +/* read response is: value */ +#define ST_CONFIG_READ_RESPONSE_LENGTH(wordSize) (wordSize) + +#define ST_SET_32BIT(v,buf) \ + do { \ + (buf)[0] = (unsigned char)(((unsigned int)(v)) >> 24); \ + (buf)[1] = (unsigned char)(((unsigned int)(v)) >> 16); \ + (buf)[2] = (unsigned char)(((unsigned int)(v)) >> 8); \ + (buf)[3] = (unsigned char)(((unsigned int)(v)) ); \ + } while ( 0 ) + +#define ST_GET_32BIT(buf) \ + ( (((unsigned int)((buf)[0])) << 24) \ + | (((unsigned int)((buf)[1])) << 16) \ + | (((unsigned int)((buf)[2])) << 8) \ + | (((unsigned int)((buf)[3])) ) \ + ) + +#define ST_SET_16BIT(v,buf) \ + do { \ + (buf)[0] = (unsigned char)(((unsigned int)(v)) >> 8); \ + (buf)[1] = (unsigned char)(((unsigned int)(v)) ); \ + } while ( 0 ) + +#define ST_GET_16BIT(buf) \ + ( (((unsigned int)((buf)[0])) << 8) \ + | (((unsigned int)((buf)[1])) ) \ + ) + + +/* one byte for errors in the dispatcher (and protocols if the protocol + was a write request = unconfirmed by the protocol itself) +*/ +#define ST_STREAM_UNHANDLED_PROTOCOL 0x01 /* no function implemented to handle this protocol */ +#define ST_STREAM_PROTOCOL_FAILED 0x02 /* function call returned a status <> 0 - and this was an unconfirmed protocol */ +#define ST_STREAM_SIZE_ERROR 0x03 /* the rx/tx size is out of allowed range */ +#define ST_STREAM_NO_ERROR 0x00 /* no error at all */ + +/* this define is used as a special TID used by the firmware when a request in the old format + is received */ +#define ST_STREAM_COMPATIBILITY_TID 0xDE + +/* -------- usb hid defines ---------------------------------------------- */ + +#define USB_HID_REPORT_ID 0 +#define USB_HID_REPORT_SIZE 64 /** the USB-HID report size is 0x40 (refer to usb_descriptors.c). */ +#define USB_HID_HEADER_SIZE 3 /** the PIC USB HID stack hides the report ID at position 0 */ +#define USB_HID_MAX_PAYLOAD_SIZE (USB_HID_REPORT_SIZE - USB_HID_HEADER_SIZE) + +/* HID header macros for the MCU */ +#define USB_HID_TID(buf) ((buf)[0]) +#define USB_HID_PAYLOAD_SIZE(buf) ((buf)[1]) +#define USB_HID_STATUS(buf) ((buf)[2]) +#define USB_HID_PAYLOAD(buf) ((buf)+USB_HID_HEADER_SIZE) + +#define USB_HID_GENERATE_TID_FOR_TX( rxtid, txtid ) \ + do { \ + (txtid)++; \ + (txtid) = ( (rxtid) << 4 ) | ( (txtid) & 0xF );\ + } while ( 0 ) + + + +/* -------- uart defines ---------------------------------------------- */ + +#define UART_HEADER_SIZE 4 + +/* uart header macros for the MCU */ +#define UART_TID(buf) (buf[0]) +#define UART_STATUS(buf) ((buf)[1]) +#define UART_SET_PAYLOAD_SIZE( buf, len ) do { (buf)[2] = (len) >> 8; (buf)[3] = (len) & 0xFF; } while ( 0 ) +#define UART_GET_PAYLOAD_SIZE( buf ) ( ( ((buf)[2]) << 8 ) | ( ((buf)[3]) & 0xFF ) ) +#define UART_PAYLOAD(buf) ((buf)+UART_HEADER_SIZE) + +#define UART_GENERATE_TID_FOR_TX( rxtid, txtid ) USB_HID_GENERATE_TID_FOR_TX( rxtid, txtid ) + + +#endif /* ST_STREAM_H */ diff --git a/src/hydranfc_v2/hal/inc/stream_dispatcher.h b/src/hydranfc_v2/hal/inc/stream_dispatcher.h new file mode 100644 index 0000000..f454213 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/stream_dispatcher.h @@ -0,0 +1,197 @@ +/****************************************************************************** + * @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: common firmware + * $Revision: $ + * LANGUAGE: C + */ + +/*! \file + * + * \author M. Arpa + * + * \brief Interface for stream packet handling. + * + */ + + +#ifndef STREAM_DISPATCHER_H +#define STREAM_DISPATCHER_H + +/* ------------ includes ----------------------------------------- */ + +#include +#include "stream_driver.h" + + +/* ------------ constants ---------------------------------------- */ + +/* + * The application should define its own firmware version. Please write + * in your application file: + * + * E.g. for major 0x01, minor 0x03, releaseMarker 0x07 + * const uint32_t firmwareNumber = 0x010307UL; + * + * E.g. for major 0x02, minor 0x00, releaseMarker 0x18 + * const uint32_t firmwareNumber = 0x020018UL; + */ +extern const uint32_t firmwareNumber; + + + +/* ------------ application functions ---------------------------- */ + +/*! + ***************************************************************************** + * \brief reset peripherals of board + * + * function which can be implemented by the application to reset + * the board peripherals. + * \return ST_STREAM_UNHANDLED_PROTOCOL if function was not overloaded by application + ***************************************************************************** + */ +extern uint8_t applPeripheralReset(void); + +/*! + ***************************************************************************** + * \brief get firmware information (zero-terminated) string + * + * function which can be implemented by the application to return the + * firmware inforamtion string (zero-terminated). E.g. information about + * the chip and board. + * \return the a pointer to the firmware information + ***************************************************************************** + */ +extern const char * applFirmwareInformation(void); + +/*! + ***************************************************************************** + * \brief Command dispatcher for application-specific commands + * + * function which can be implemented by the application process application- + * specific commands for I/O. If data should be returned, the txData buffer + * can be filled with data which should be sent to the PC. In argument txSize, + * the size is returned. + * \param[in] protocol : the protocol byte which needs to be processed + * \param[in] rxData : pointer to payload for appl commands (in stream protocol buffer). + * \param[in] rxSize : size of rxData + * \param[out] txData : pointer to buffer to store returned data (payload only) + * \param[out] txSize : size of returned data + * \return the status byte to be interpreted by the stream layer on the host + ***************************************************************************** + */ +extern uint8_t applProcessCmd( uint8_t protocol, uint16_t rxSize, const uint8_t * rxData, uint16_t * txSize, uint8_t * txData ); + +/*! + ***************************************************************************** + * \brief Called cyclic (even when no full usb packet was received). Use + * this is you need to send several packets (time delayed) in + * response to one usb request. + * + * function which can be implemented by the application process + * If data should be returned, the txData buffer must be filled with the data to + * be sent to the PC. In argument txSize, the size is returned. The function + * also must fill in the protocol byte (this is the protocol value that is + * filled in in the protocol header. + * \param[out] protocol : protocol byte to be used for the packet header + * \param[out] txData : pointer to buffer to store returned data (payload only) + * \param[out] txSize : size of returned data + * \param[in] remainingSize : how many bytes are free in the buffer txData + * \return the status byte to be interpreted by the stream layer on the host + ***************************************************************************** + */ +extern uint8_t applProcessCyclic( uint8_t * protocol, uint16_t * txSize, uint8_t * txData, uint16_t remainingSize ); + +/*! + ***************************************************************************** + * \brief Generic function to read one or more registers + * + * Function which can be implemented by the application to read registers. + * If data should be returned, the txData buffer must be filled with the data to + * be sent to the PC. In argument txSize, the size is returned. The function + * also must fill in the protocol byte (this is the protocol value that is + * filled in in the protocol header. + * \param[in] rxData : pointer to payload for appl commands (in stream protocol buffer). + * \param[in] rxSize : size of rxData + * \param[out] txData : pointer to buffer to store returned data (payload only) + * \param[out] txSize : size of returned data + * \return the status byte to be interpreted by the stream layer on the host + ***************************************************************************** + */ +extern uint8_t applReadReg( uint16_t rxSize, const uint8_t * rxData, uint16_t * txSize, uint8_t * txData ); + +/*! + ***************************************************************************** + * \brief Generic function to write one or more registers + * + * Function which can be implemented by the application to write registers. + * If data should be returned, the txData buffer must be filled with the data to + * be sent to the PC. In argument txSize, the size is returned. The function + * also must fill in the protocol byte (this is the protocol value that is + * filled in in the protocol header. + * \param[in] rxData : pointer to payload for appl commands (in stream protocol buffer). + * \param[in] rxSize : size of rxData + * \param[out] txData : pointer to buffer to store returned data (payload only) + * \param[out] txSize : size of returned data + * \return the status byte to be interpreted by the stream layer on the host + ***************************************************************************** + */ +extern uint8_t applWriteReg( uint16_t rxSize, const uint8_t * rxData, uint16_t * txSize, uint8_t * txData ); + + +/* ------------ functions ---------------------------------------- */ + + +/******************************************************************** + * \brief returns the last error that occured and clears the error + * *******************************************************************/ +uint8_t StreamDispatcherGetLastError(void); + +/******************************************************************** + * \brief initialization of stream dispatcher and connect to the + * communication stream (e.g. USB HID). + * + * This function does all the necessary initialization for the Stream dispatcher. + * It also connects to the IO. + * + * \param[in] sysClk : configured sysclk. + * Required to set correct transfer rates. + * *******************************************************************/ +void StreamDispatcherInitAndConnect( void ); + +/******************************************************************** + * \brief initialisation of the stream dispatcher (no connect) + * + * \param[in] sysClk : configured sysclk. Required to set correct spi/i2c data rates. + * *******************************************************************/ +void StreamDispatcherInit( void ); + +/******************************************************************** + * \brief Main entry point into the stream dispatcher must be called cyclic. + * + * This function checks the stream driver for received data. If new data is + * available it is processed and forwarded to the application + * functions. + * *******************************************************************/ +void ProcessIO(void); + +#endif /* STREAM_DISPATCHER */ diff --git a/src/hydranfc_v2/hal/inc/stream_driver.h b/src/hydranfc_v2/hal/inc/stream_driver.h new file mode 100644 index 0000000..be520ba --- /dev/null +++ b/src/hydranfc_v2/hal/inc/stream_driver.h @@ -0,0 +1,93 @@ +/****************************************************************************** + * @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: + * $Revision: $ + * LANGUAGE: ANSI C + */ + +/*! \file + * + * \author + * + * \brief Streaming driver interface declarations. + * The defines allow switching between different stream drivers, + * currently implemented are: + * - USB + * - UART + * + */ + +/*! + * + * + */ +#ifndef STREAM_DRIVER_H +#define STREAM_DRIVER_H +/* + ****************************************************************************** + * INCLUDES + ****************************************************************************** + */ +#include +#include "st_stream.h" /* stream protocol definitions */ + +#include "usb_hid_stream_driver.h" +#include "usbd_custom_hid_if.h" + + +/* + ****************************************************************************** + * DEFINES + ****************************************************************************** + */ + +#define USE_UART_STREAM_DRIVER 0 +/* redirect according to underlying communication protocol being usb-hid, uart */ +#if USE_UART_STREAM_DRIVER + +#define StreamInitialize uartStreamInitialize +#define StreamConnect uartStreamConnect +#define StreamDisconnect uartStreamDisconnect +#define StreamReady uartStreamReady +#define StreamHasAnotherPacket uartStreamHasAnotherPacket +#define StreamPacketProcessed uartStreamPacketProcessed +#define StreamReceive uartStreamReceive +#define StreamTransmit uartStreamTransmit + + +#else /* USE_USB_STREAM_DRIVER */ + +#define StreamInitialize usbStreamInitialize +#define StreamConnect usbStreamConnect +#define StreamDisconnect usbStreamDisconnect +#define StreamReady usbStreamReady +#define StreamHasAnotherPacket usbStreamHasAnotherPacket +#define StreamPacketProcessed usbStreamPacketProcessed +#define StreamReceive usbStreamReceive +#define StreamTransmit usbStreamTransmit + +#endif + + + +#endif /* STREAM_DRIVER_H */ + diff --git a/src/hydranfc_v2/hal/inc/timer.h b/src/hydranfc_v2/hal/inc/timer.h new file mode 100644 index 0000000..09a5742 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/timer.h @@ -0,0 +1,128 @@ +/****************************************************************************** + * @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: + * + * 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 "platform.h" + +/* +****************************************************************************** +* 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/src/hydranfc_v2/hal/inc/usart.h b/src/hydranfc_v2/hal/inc/usart.h new file mode 100644 index 0000000..74f21fe --- /dev/null +++ b/src/hydranfc_v2/hal/inc/usart.h @@ -0,0 +1,102 @@ +/** + ****************************************************************************** + * COPYRIGHT(c) 2016 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 + * + * \author + * + * \brief UART communication header file + * + */ +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __usart_H +#define __usart_H + +/* Includes ------------------------------------------------------------------*/ +#include "platform.h" + +/*! + ***************************************************************************** + * \brief Initalize USART + * + * This function initalize the USART handle. + * + * \param[in] husart : pointer to initalized USART block + * + ***************************************************************************** + */ +void usartInit(UART_HandleTypeDef *husart); + +/*! + ***************************************************************************** + * \brief Transmit byte + * + * This funtion transmits one data byte via the USART. + * + * \param[in] data : byte to be transmitted. + * + * \return : HAL error code + * + ***************************************************************************** + */ +uint8_t usartTxByte(uint8_t data); + +/*! + ***************************************************************************** + * \brief Transmit n byte + * + * This funtion transmits "dataLen" bytes from "data" via the USART. + * + * \param[in] data : bytes to be transmitted. + * + * \param[in] dataLen : no of bytes to be transmitted. + * + * \return : HAL error code + * + ***************************************************************************** + */ +uint8_t usartTx(uint8_t *data, uint16_t dataLen); + +/*! + ***************************************************************************** + * \brief Receive data + * + * This funtion receives "dataLen" bytes from "data" from the USART. + * + * \param[out] data : pointer to buffer where received data shall be copied to. + * + * \param[out] dataLen : max no of bytes that shall be received. + * + * \return : HAL error code + * + ***************************************************************************** + */ +uint8_t usartRx(uint8_t *data, uint16_t *dataLen); + +#endif /*__usart_H */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/inc/usb_hid_stream_driver.h b/src/hydranfc_v2/hal/inc/usb_hid_stream_driver.h new file mode 100644 index 0000000..8af6118 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/usb_hid_stream_driver.h @@ -0,0 +1,146 @@ +/****************************************************************************** + * @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: + * $Revision: $ + * LANGUAGE: ANSI C + */ + +/*! \file + * + * \author Wolfgang Reichart + * + * \brief USB HID streaming driver declarations. + * + */ + +/*! + * + * + */ +#ifndef _USB_HID_STREAM_DRIVER_H +#define _USB_HID_STREAM_DRIVER_H + +/* + ****************************************************************************** + * INCLUDES + ****************************************************************************** + */ +#include +#include "st_stream.h" +#include "stream_driver.h" + +/* + ****************************************************************************** + * GLOBAL FUNCTIONS + ****************************************************************************** + */ + + +/*! + ***************************************************************************** + * \brief initializes the USB HID Stream driver variables + * + * This function takes care for proper initialisation of buffers, variables, etc. + * + * \param rxBuf : buffer where received packets will be copied into + * \param txBuf : buffer where to be transmitted packets will be copied into + ***************************************************************************** + */ +void usbStreamInitialize (uint8_t * rxBuf, uint8_t * txBuf); + +/*! + ***************************************************************************** + * \brief initialises the usb endpoints and connects to host + ***************************************************************************** + */ +void usbStreamConnect(void); + +/*! + ***************************************************************************** + * \brief disconnects from usb host + ***************************************************************************** + */ +void usbStreamDisconnect(void); + +/*! + ***************************************************************************** + * \brief returns 1 if stream init is finished + * + * \return 0=init has not finished yet, 1=stream has been initialized + ***************************************************************************** + */ +uint8_t usbStreamReady(void); + +/*! + ***************************************************************************** + * \brief tells the stream driver that the packet has been processed and can + * be moved from the rx buffer + * + * \param rxed : number of bytes which have been processed + ***************************************************************************** + */ +void usbStreamPacketProcessed (uint16_t rxed); + +/*! + ***************************************************************************** + * \brief returns 1 if another packet is available in buffer + * + * \return 0=no packet available in buffer, 1=another packet available + ***************************************************************************** + */ +int8_t usbStreamHasAnotherPacket (void); + +/*! + ***************************************************************************** + * \brief checks if there is data received on the HID device from the host + * and copies the received data into a local buffer + * + * Checks if the usb HID device has data received from the host, copies this + * data into a local buffer. The data in the local buffer is than interpreted + * as a packet (with header, rx-length and tx-length). As soon as a full + * packet is received the function returns non-null. + * + * \return 0 = nothing to process, >0 at least 1 packet to be processed + ***************************************************************************** + */ +uint16_t usbStreamReceive (void); + +/*! + ***************************************************************************** + * \brief checks if there is data to be transmitted from the HID device to + * the host. + * + * Checks if there is data waiting to be transmitted to the host. Copies this + * data from a local buffer to the usb buffer and transmits this usb buffer. + * If more than 1 usb hid report is needed to transmit the data, the function + * waits until the first one is sent, and than refills the usb buffer with + * the next chunk of data and transmits the usb buffer again. And so on, until + * all data is sent. + * + * \param [in] totalTxSize: the size of the data to be transmitted (the HID + * header is not included) + ***************************************************************************** + */ +void usbStreamTransmit( uint16_t totalTxSize ); + +#endif // _USB_HID_STREAM_DRIVER_H + diff --git a/src/hydranfc_v2/hal/inc/usbd_conf.h b/src/hydranfc_v2/hal/inc/usbd_conf.h new file mode 100644 index 0000000..870f9c5 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/usbd_conf.h @@ -0,0 +1,196 @@ +/** + ****************************************************************************** + * @file : usbd_conf.h + * @brief : Header for usbd_conf file. + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution 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 other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS 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. + * + ****************************************************************************** +*/ +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __USBD_CONF__H__ +#define __USBD_CONF__H__ +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include +#include +#include +#include "bsp.h" +/* +#include "stm32l4xx.h" +#include "stm32l4xx_hal.h" +*/ + +/** @addtogroup USBD_OTG_DRIVER + * @{ + */ + +/** @defgroup USBD_CONF + * @brief usb otg low level driver configuration file + * @{ + */ + +/** @defgroup USBD_CONF_Exported_Defines + * @{ + */ + +/*---------- -----------*/ +#define USBD_MAX_NUM_INTERFACES 1 +/*---------- -----------*/ +#define USBD_MAX_NUM_CONFIGURATION 1 +/*---------- -----------*/ +#define USBD_MAX_STR_DESC_SIZ 512 +/*---------- -----------*/ +#define USBD_SUPPORT_USER_STRING 1 +/*---------- -----------*/ +#define USBD_DEBUG_LEVEL 0 +/*---------- -----------*/ +#define USBD_LPM_ENABLED 0 +/*---------- -----------*/ +#define USBD_SELF_POWERED 1 +/*---------- -----------*/ +#define USBD_CUSTOMHID_OUTREPORT_BUF_SIZE 64 +/*---------- -----------*/ +#define USBD_CUSTOM_HID_REPORT_DESC_SIZE 29 + +/****************************************/ +/* #define for FS and HS identification */ +#define DEVICE_FS 0 + +/** @defgroup USBD_Exported_Macros + * @{ + */ + +/* Memory management macros */ +#define USBD_malloc (uint32_t *)USBD_static_malloc +#define USBD_free USBD_static_free +#define USBD_memset /* Not used */ +#define USBD_memcpy /* Not used */ + +#define USBD_Delay HAL_Delay + + /* DEBUG macros */ + +#if (USBD_DEBUG_LEVEL > 0) +#define USBD_UsrLog(...) printf(__VA_ARGS__);\ + printf("\n"); +#else +#define USBD_UsrLog(...) +#endif + + +#if (USBD_DEBUG_LEVEL > 1) + +#define USBD_ErrLog(...) printf("ERROR: ") ;\ + printf(__VA_ARGS__);\ + printf("\n"); +#else +#define USBD_ErrLog(...) +#endif + + +#if (USBD_DEBUG_LEVEL > 2) +#define USBD_DbgLog(...) printf("DEBUG : ") ;\ + printf(__VA_ARGS__);\ + printf("\n"); +#else +#define USBD_DbgLog(...) +#endif + +/** + * @} + */ + + + +/** + * @} + */ + +/** @defgroup USBD_CONF_Exported_Types + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_CONF_Exported_Macros + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_CONF_Exported_Variables + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_CONF_Exported_FunctionsPrototype + * @{ + */ +/** + * @} + */ +/* Exported functions ------------------------------------------------------- */ +void *USBD_static_malloc(uint32_t size); +void USBD_static_free(void *p); + +#ifdef __cplusplus +} +#endif + +#endif /*__USBD_CONF__H__*/ + +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ + diff --git a/src/hydranfc_v2/hal/inc/usbd_custom_hid_if.h b/src/hydranfc_v2/hal/inc/usbd_custom_hid_if.h new file mode 100644 index 0000000..c7c2d11 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/usbd_custom_hid_if.h @@ -0,0 +1,142 @@ +/** + ****************************************************************************** + * @file : usbd_custom_hid_if_if.h + * @brief : header file for the usbd_custom_hid_if.c file + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution 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 other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS 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. + * + ****************************************************************************** +*/ + +/* Define to prevent recursive inclusion -------------------------------------*/ + +#ifndef __USBD_CUSTOM_HID_IF_H_ +#define __USBD_CUSTOM_HID_IF_H_ + +#ifdef __cplusplus + extern "C" { +#endif +/* Includes ------------------------------------------------------------------*/ +#include "usbd_customhid.h" +/* USER CODE BEGIN INCLUDE */ +/* USER CODE END INCLUDE */ + +/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USBD_CUSTOM_HID + * @brief header + * @{ + */ + +/** @defgroup USBD_CUSTOM_HID_Exported_Defines + * @{ + */ +/* USER CODE BEGIN EXPORTED_DEFINES */ +/* USER CODE END EXPORTED_DEFINES */ + +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_Exported_Types + * @{ + */ +/* USER CODE BEGIN EXPORTED_TYPES */ +/* USER CODE END EXPORTED_TYPES */ + +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_Exported_Macros + * @{ + */ +/* USER CODE BEGIN EXPORTED_MACRO */ +/* USER CODE END EXPORTED_MACRO */ + +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_Exported_Variables + * @{ + */ + extern USBD_CUSTOM_HID_ItfTypeDef USBD_CustomHID_fops_FS; + +/* USER CODE BEGIN EXPORTED_VARIABLES */ +/* USER CODE END EXPORTED_VARIABLES */ + +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_Exported_FunctionsPrototype + * @{ + */ + +/* USER CODE BEGIN EXPORTED_FUNCTIONS */ +extern uint8_t UsbReceive(uint8_t *data, uint16_t *dataLen); + +extern uint8_t UsbTransmitReady(void); +extern uint8_t UsbTransmit(uint8_t *data, uint16_t dataLen); + +/* USER CODE END EXPORTED_FUNCTIONS */ +/** + * @} + */ + +/** + * @} + */ + +/** +* @} +*/ + +#ifdef __cplusplus +} +#endif + +#endif /* __USBD_CUSTOM_HID_IF_H_ */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/inc/usbd_customhid.h b/src/hydranfc_v2/hal/inc/usbd_customhid.h new file mode 100644 index 0000000..64b8536 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/usbd_customhid.h @@ -0,0 +1,161 @@ +/** + ****************************************************************************** + * @file usbd_customhid.h + * @author MCD Application Team + * @version V2.4.2 + * @date 11-December-2015 + * @brief header file for the usbd_customhid.c file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __USB_CUSTOMHID_H +#define __USB_CUSTOMHID_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_ioreq.h" + +/** @addtogroup STM32_USB_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USBD_CUSTOM_HID + * @brief This file is the Header file for USBD_customhid.c + * @{ + */ + + +/** @defgroup USBD_CUSTOM_HID_Exported_Defines + * @{ + */ +#define CUSTOM_HID_EPIN_ADDR 0x81 +#define CUSTOM_HID_EPIN_SIZE 0x40 + +#define CUSTOM_HID_EPOUT_ADDR 0x01 +#define CUSTOM_HID_EPOUT_SIZE 0x40 + +#define USB_CUSTOM_HID_CONFIG_DESC_SIZ 41 +#define USB_CUSTOM_HID_DESC_SIZ 9 + +#define CUSTOM_HID_DESCRIPTOR_TYPE 0x21 +#define CUSTOM_HID_REPORT_DESC 0x22 + + +#define CUSTOM_HID_REQ_SET_PROTOCOL 0x0B +#define CUSTOM_HID_REQ_GET_PROTOCOL 0x03 + +#define CUSTOM_HID_REQ_SET_IDLE 0x0A +#define CUSTOM_HID_REQ_GET_IDLE 0x02 + +#define CUSTOM_HID_REQ_SET_REPORT 0x09 +#define CUSTOM_HID_REQ_GET_REPORT 0x01 +/** + * @} + */ + + +/** @defgroup USBD_CORE_Exported_TypesDefinitions + * @{ + */ +typedef enum +{ + CUSTOM_HID_IDLE = 0, + CUSTOM_HID_BUSY, +} +CUSTOM_HID_StateTypeDef; + +typedef struct _USBD_CUSTOM_HID_Itf +{ + uint8_t *pReport; + int8_t (* Init) (void); + int8_t (* DeInit) (void); + int8_t (* OutEvent) (uint8_t, uint8_t ); + +}USBD_CUSTOM_HID_ItfTypeDef; + +typedef struct +{ + uint8_t Report_buf[USBD_CUSTOMHID_OUTREPORT_BUF_SIZE]; + uint32_t Protocol; + uint32_t IdleState; + uint32_t AltSetting; + uint32_t IsReportAvailable; + CUSTOM_HID_StateTypeDef state; +} +USBD_CUSTOM_HID_HandleTypeDef; +/** + * @} + */ + + + +/** @defgroup USBD_CORE_Exported_Macros + * @{ + */ + +/** + * @} + */ + +/** @defgroup USBD_CORE_Exported_Variables + * @{ + */ + +extern USBD_ClassTypeDef USBD_CUSTOM_HID; +#define USBD_CUSTOM_HID_CLASS &USBD_CUSTOM_HID +/** + * @} + */ + +/** @defgroup USB_CORE_Exported_Functions + * @{ + */ +uint8_t USBD_CUSTOM_HID_SendReport (USBD_HandleTypeDef *pdev, + uint8_t *report, + uint16_t len); + + + +uint8_t USBD_CUSTOM_HID_RegisterInterface (USBD_HandleTypeDef *pdev, + USBD_CUSTOM_HID_ItfTypeDef *fops); + +uint8_t USBD_CUSTOM_HID_ReceivePacket (USBD_HandleTypeDef *pdev); +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __USB_CUSTOMHID_H */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/inc/usbd_desc.h b/src/hydranfc_v2/hal/inc/usbd_desc.h new file mode 100644 index 0000000..4dfdd09 --- /dev/null +++ b/src/hydranfc_v2/hal/inc/usbd_desc.h @@ -0,0 +1,119 @@ +/** + ****************************************************************************** + * @file : usbd_desc.h + * @version : v2.0_Cube + * @brief : Header for usbd_desc file. + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution 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 other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS 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. + * + ****************************************************************************** +*/ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __USBD_DESC__H__ +#define __USBD_DESC__H__ + +#ifdef __cplusplus + extern "C" { +#endif +/* Includes ------------------------------------------------------------------*/ +#include "usbd_def.h" + +/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USB_DESC + * @brief general defines for the usb device library file + * @{ + */ + +/** @defgroup USB_DESC_Exported_Defines + * @{ + */ + +/** + * @} + */ + +/** @defgroup USBD_DESC_Exported_TypesDefinitions + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_DESC_Exported_Macros + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_DESC_Exported_Variables + * @{ + */ +extern USBD_DescriptorsTypeDef FS_Desc; +/** + * @} + */ + +/** @defgroup USBD_DESC_Exported_FunctionsPrototype + * @{ + */ + +/** + * @} + */ +#ifdef __cplusplus +} +#endif + +#endif /* __USBD_DESC_H */ + +/** + * @} + */ + +/** +* @} +*/ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/inc/utils.h b/src/hydranfc_v2/hal/inc/utils.h new file mode 100644 index 0000000..db1556e --- /dev/null +++ b/src/hydranfc_v2/hal/inc/utils.h @@ -0,0 +1,112 @@ + +/****************************************************************************** + * @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: + * + * 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 + +/* +****************************************************************************** +* 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 SIZEOF_ARRAY(a) (sizeof(a) / sizeof((a)[0])) /*!< Compute the size of an array */ +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) /*!< Return the maximum of the 2 values */ +#undef MIN +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) /*!< Return the minimum of the 2 values */ +#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) | (uint16_t)(a)[1])/*!< Cast two Big Endian 8-bits byte array to 16-bits unsigned */ +#define GETU32(a) (((uint32_t)(a)[0] << 24) | ((uint32_t)(a)[1] << 16) | ((uint32_t)(a)[2] << 8) | ((uint32_t)(a)[3])) /*!< Cast four Big Endian 8-bit byte array to 32-bit unsigned */ + +#define REVERSE_BYTES(pData, nDataSize) \ + {unsigned char swap, *lo = ((unsigned char *)(pData)), *hi = ((unsigned char *)(pData)) + (nDataSize) - 1; \ + while (lo < hi) { swap = *lo; *lo++ = *hi; *hi-- = swap; }} + +#ifdef __CSMC__ +/* STM8 COSMIC */ +#define ST_MEMMOVE(s1,s2,n) memmove(s1,s2,n) /*!< map memmove to string library code */ +static inline void * ST_MEMCPY(void *s1, const void *s2, uint32_t n) { return memcpy(s1,s2,(uint16_t)n); } /* PRQA S 0431 # MISRA 1.1 - string.h from Cosmic only provides functions with low qualified parameters */ +#define ST_MEMSET(s1,c,n) memset(s1,(char)(c),n) /*!< map memset to string library code */ +static inline int32_t ST_BYTECMP(void *s1, const void *s2, uint32_t n) { return (int32_t)memcmp(s1,s2,(uint16_t)n); } /* PRQA S 0431 # MISRA 1.1 - string.h from Cosmic only provides functions with low qualified parameters */ + +#else /* __CSMC__ */ + +#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 */ +#endif /* __CSMC__ */ + +#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/src/hydranfc_v2/hal/src/led.c b/src/hydranfc_v2/hal/src/led.c new file mode 100644 index 0000000..338df80 --- /dev/null +++ b/src/hydranfc_v2/hal/src/led.c @@ -0,0 +1,145 @@ +/****************************************************************************** + * @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: ST25R3911 firmware + * $Revision: $ + * LANGUAGE: ANSI C + */ + +/*! \file + * + * \author + * + * \brief Implementation for controlling shield LEDs functionality + * + */ + +/*! + * + */ + +/* +****************************************************************************** +* INCLUDES +****************************************************************************** +*/ +#include "bsp.h" +#include "led.h" + +volatile uint16_t msLedA = 0; +volatile uint16_t msLedB = 0; +volatile uint16_t msLedF = 0; +volatile uint16_t msLedV = 0; +volatile uint16_t msLedAP2P = 0; + +void ledOn(st25R3911Led_t Led) +{ +#ifdef _NUCLEO_ + switch(Led){ + case LED_A: HAL_GPIO_WritePin(LED_A_GPIO_Port , LED_A_Pin , GPIO_PIN_SET); break; + case LED_B: HAL_GPIO_WritePin(LED_B_GPIO_Port , LED_B_Pin , GPIO_PIN_SET); break; + case LED_F: HAL_GPIO_WritePin(LED_F_GPIO_Port , LED_F_Pin , GPIO_PIN_SET); break; + case LED_V: HAL_GPIO_WritePin(LED_V_GPIO_Port , LED_V_Pin , GPIO_PIN_SET); break; + case LED_AP2P: HAL_GPIO_WritePin(LED_AP2P_GPIO_Port , LED_AP2P_Pin , GPIO_PIN_SET); break; + default: + break; + } +#endif +} + +void ledOff(st25R3911Led_t Led) +{ +#ifdef _NUCLEO_ + switch(Led){ + case LED_A: HAL_GPIO_WritePin(LED_A_GPIO_Port , LED_A_Pin , GPIO_PIN_RESET); break; + case LED_B: HAL_GPIO_WritePin(LED_B_GPIO_Port , LED_B_Pin , GPIO_PIN_RESET); break; + case LED_F: HAL_GPIO_WritePin(LED_F_GPIO_Port , LED_F_Pin , GPIO_PIN_RESET); break; + case LED_V: HAL_GPIO_WritePin(LED_V_GPIO_Port , LED_V_Pin , GPIO_PIN_RESET); break; + case LED_AP2P: HAL_GPIO_WritePin(LED_AP2P_GPIO_Port , LED_AP2P_Pin , GPIO_PIN_RESET); break; + default: + break; + } +#endif +} + +void ledToggle(st25R3911Led_t Led) +{ +#ifdef _NUCLEO_ + switch(Led){ + case LED_A: HAL_GPIO_TogglePin(LED_A_GPIO_Port , LED_A_Pin ); break; + case LED_B: HAL_GPIO_TogglePin(LED_B_GPIO_Port , LED_B_Pin ); break; + case LED_F: HAL_GPIO_TogglePin(LED_F_GPIO_Port , LED_F_Pin ); break; + case LED_V: HAL_GPIO_TogglePin(LED_V_GPIO_Port , LED_V_Pin ); break; + case LED_AP2P: HAL_GPIO_TogglePin(LED_AP2P_GPIO_Port , LED_AP2P_Pin ); break; + default: + break; + } +#endif +} + + + +void ledOnOff(st25R3911Led_t Led, uint32_t delay) +{ + ledOn(Led); + + switch(Led){ + case LED_A: msLedA = delay; break; + case LED_B: msLedB = delay; break; + case LED_F: msLedF = delay; break; + case LED_V: msLedV = delay; break; + case LED_AP2P: msLedAP2P = delay; break; + default: + break; + } +} +void ledFeedbackHandler() +{ + if(msLedA > 0){ + msLedA--; + if(msLedA == 0) + ledOff(LED_A); + } + + if(msLedB > 0){ + msLedB--; + if(msLedB == 0) + ledOff(LED_B); + } + + if(msLedF > 0){ + msLedF--; + if(msLedF == 0) + ledOff(LED_F); + } + + if(msLedV > 0){ + msLedV--; + if(msLedV == 0) + ledOff(LED_V); + } + + if(msLedAP2P > 0){ + msLedAP2P--; + if(msLedAP2P == 0) + ledOff(LED_AP2P); + } +} diff --git a/src/hydranfc_v2/hal/src/logger.c b/src/hydranfc_v2/hal/src/logger.c new file mode 100644 index 0000000..e52a9a1 --- /dev/null +++ b/src/hydranfc_v2/hal/src/logger.c @@ -0,0 +1,197 @@ +/****************************************************************************** + * @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: + * $Revision: $ + * LANGUAGE: ANSI C + */ + +/*! \file + * + * \author + * + * \brief Debug log output utility implementation. + * + */ + +/* +****************************************************************************** +* INCLUDES +****************************************************************************** +*/ +#include "logger.h" +#include "st_errno.h" +#include +#include +#include +/* +****************************************************************************** +* LOCAL DEFINES +****************************************************************************** +*/ + + +#if (USE_LOGGER == LOGGER_ON) +#define MAX_HEX_STR 4 +#define MAX_HEX_STR_LENGTH 128 +char hexStr[MAX_HEX_STR][MAX_HEX_STR_LENGTH]; +uint8_t hexStrIdx = 0; +#endif /* #if USE_LOGGER == LOGGER_ON */ + + +#if (USE_LOGGER == LOGGER_OFF && !defined(HAL_UART_MODULE_ENABLED)) + #define UART_HandleTypeDef void +#endif + + +#define USART_TIMEOUT 1000 + +UART_HandleTypeDef *pLogUsart = 0; +uint8_t logUsartTx(uint8_t *data, uint16_t dataLen); + +/** + * @brief This function initalize the UART handle. + * @param husart : already initalized handle to USART HW + * @retval none : + */ +void logUsartInit(UART_HandleTypeDef *husart) +{ + pLogUsart = husart; +} + +/** + * @brief This function Transmit data via USART + * @param data : data to be transmitted + * @param dataLen : length of data to be transmitted + * @retval ERR_INVALID_HANDLE : in case the SPI HW is not initalized yet + * @retval others : HAL status + */ +uint8_t logUsartTx(uint8_t *data, uint16_t dataLen) +{ + if(pLogUsart == 0) + return ERR_INVALID_HANDLE; + #if (USE_LOGGER == LOGGER_ON) + { + return HAL_UART_Transmit(pLogUsart, data, dataLen, USART_TIMEOUT); + } + #else + { + return 0; + } + #endif /* #if USE_LOGGER == LOGGER_ON */ +} + +int logUsart(const char* format, ...) +{ + #if (USE_LOGGER == LOGGER_ON) + { + #define LOG_BUFFER_SIZE 256 + char buf[LOG_BUFFER_SIZE]; + va_list argptr; + va_start(argptr, format); + int cnt = vsnprintf(buf, LOG_BUFFER_SIZE, format, argptr); + va_end(argptr); + + /* */ + logUsartTx((uint8_t*)buf, strlen(buf)); + return cnt; + } + #else + { + return 0; + } + #endif /* #if USE_LOGGER == LOGGER_ON */ +} + +/* */ + +char* hex2Str(unsigned char * data, size_t dataLen) +{ + #if (USE_LOGGER == LOGGER_ON) + { + unsigned char * pin = data; + const char * hex = "0123456789ABCDEF"; + char * pout = hexStr[hexStrIdx]; + uint8_t i = 0; + uint8_t idx = hexStrIdx; + if(dataLen == 0) + { + pout[0] = 0; + } + else + { + for(; i < dataLen - 1; ++i) + { + *pout++ = hex[(*pin>>4)&0xF]; + *pout++ = hex[(*pin++)&0xF]; + } + *pout++ = hex[(*pin>>4)&0xF]; + *pout++ = hex[(*pin)&0xF]; + *pout = 0; + } + + hexStrIdx++; + hexStrIdx %= MAX_HEX_STR; + + return hexStr[idx]; + } + #else + { + return NULL; + } + #endif /* #if USE_LOGGER == LOGGER_ON */ +} + +void logITMTx(uint8_t *data, uint16_t dataLen) +{ + #if (USE_LOGGER == LOGGER_ON) + while (dataLen != 0) + { + ITM_SendChar(*data); + data++; + dataLen--; + } + #endif /* #if USE_LOGGER == LOGGER_ON */ + return; +} + +int logITM(const char* format, ...) +{ + #if (USE_LOGGER == LOGGER_ON) + { + #define LOG_BUFFER_SIZE 256 + char buf[LOG_BUFFER_SIZE]; + va_list argptr; + va_start(argptr, format); + int cnt = vsnprintf(buf, LOG_BUFFER_SIZE, format, argptr); + va_end(argptr); + + /* */ + logITMTx((uint8_t*)buf, strlen(buf)); + HAL_Delay((cnt + 9)/10); /* WA to avoid ITM overflow */ + return cnt; + } + #else + { + return 0; + } + #endif /* #if USE_LOGGER == LOGGER_ON */ +} diff --git a/src/hydranfc_v2/hal/src/rfal_analogConfigCustomTbl.c b/src/hydranfc_v2/hal/src/rfal_analogConfigCustomTbl.c new file mode 100644 index 0000000..a7f55a4 --- /dev/null +++ b/src/hydranfc_v2/hal/src/rfal_analogConfigCustomTbl.c @@ -0,0 +1,582 @@ + +/****************************************************************************** + * \attention + * + *

© COPYRIGHT 2020 STMicroelectronics

+ * Copyright (C) 2020 Benjamin VERNOUX + * Based on en.STSW-ST25RFAL002 V2.2.0 / 22-May-2020 https://www.st.com/en/embedded-software/stsw-st25rfal002.html + * + * 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. + * +******************************************************************************/ + +/* + ****************************************************************************** + * 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 */ +/* Benjamin VERNOUX Modified default Antenna Tuning (ST25R3916_REG_ANT_TUNE_A=0x49 & ST25R3916_REG_ANT_TUNE_B=0x45) for HydraNFC Shield V2 */ +const uint8_t rfalAnalogConfigCustom[] = { + + /****** 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< SPI_BUF_LEN) + { + return HAL_ERROR; + } + + /* Initialize Tx data*/ + if (txData != NULL) + { + memcpy(txBuf, txData, length); + } + else + { + memset(txBuf, 0x00, length); + } + + return HAL_SPI_TransmitReceive(pSpi, txBuf, + (rxData != NULL) ? rxData : rxBuf, length, SPI_TIMEOUT); +} + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/stm32_usb_device_library_class_customhid/inc/usbd_customhid.h b/src/hydranfc_v2/hal/src/stm32_usb_device_library_class_customhid/inc/usbd_customhid.h new file mode 100644 index 0000000..64b8536 --- /dev/null +++ b/src/hydranfc_v2/hal/src/stm32_usb_device_library_class_customhid/inc/usbd_customhid.h @@ -0,0 +1,161 @@ +/** + ****************************************************************************** + * @file usbd_customhid.h + * @author MCD Application Team + * @version V2.4.2 + * @date 11-December-2015 + * @brief header file for the usbd_customhid.c file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __USB_CUSTOMHID_H +#define __USB_CUSTOMHID_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_ioreq.h" + +/** @addtogroup STM32_USB_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USBD_CUSTOM_HID + * @brief This file is the Header file for USBD_customhid.c + * @{ + */ + + +/** @defgroup USBD_CUSTOM_HID_Exported_Defines + * @{ + */ +#define CUSTOM_HID_EPIN_ADDR 0x81 +#define CUSTOM_HID_EPIN_SIZE 0x40 + +#define CUSTOM_HID_EPOUT_ADDR 0x01 +#define CUSTOM_HID_EPOUT_SIZE 0x40 + +#define USB_CUSTOM_HID_CONFIG_DESC_SIZ 41 +#define USB_CUSTOM_HID_DESC_SIZ 9 + +#define CUSTOM_HID_DESCRIPTOR_TYPE 0x21 +#define CUSTOM_HID_REPORT_DESC 0x22 + + +#define CUSTOM_HID_REQ_SET_PROTOCOL 0x0B +#define CUSTOM_HID_REQ_GET_PROTOCOL 0x03 + +#define CUSTOM_HID_REQ_SET_IDLE 0x0A +#define CUSTOM_HID_REQ_GET_IDLE 0x02 + +#define CUSTOM_HID_REQ_SET_REPORT 0x09 +#define CUSTOM_HID_REQ_GET_REPORT 0x01 +/** + * @} + */ + + +/** @defgroup USBD_CORE_Exported_TypesDefinitions + * @{ + */ +typedef enum +{ + CUSTOM_HID_IDLE = 0, + CUSTOM_HID_BUSY, +} +CUSTOM_HID_StateTypeDef; + +typedef struct _USBD_CUSTOM_HID_Itf +{ + uint8_t *pReport; + int8_t (* Init) (void); + int8_t (* DeInit) (void); + int8_t (* OutEvent) (uint8_t, uint8_t ); + +}USBD_CUSTOM_HID_ItfTypeDef; + +typedef struct +{ + uint8_t Report_buf[USBD_CUSTOMHID_OUTREPORT_BUF_SIZE]; + uint32_t Protocol; + uint32_t IdleState; + uint32_t AltSetting; + uint32_t IsReportAvailable; + CUSTOM_HID_StateTypeDef state; +} +USBD_CUSTOM_HID_HandleTypeDef; +/** + * @} + */ + + + +/** @defgroup USBD_CORE_Exported_Macros + * @{ + */ + +/** + * @} + */ + +/** @defgroup USBD_CORE_Exported_Variables + * @{ + */ + +extern USBD_ClassTypeDef USBD_CUSTOM_HID; +#define USBD_CUSTOM_HID_CLASS &USBD_CUSTOM_HID +/** + * @} + */ + +/** @defgroup USB_CORE_Exported_Functions + * @{ + */ +uint8_t USBD_CUSTOM_HID_SendReport (USBD_HandleTypeDef *pdev, + uint8_t *report, + uint16_t len); + + + +uint8_t USBD_CUSTOM_HID_RegisterInterface (USBD_HandleTypeDef *pdev, + USBD_CUSTOM_HID_ItfTypeDef *fops); + +uint8_t USBD_CUSTOM_HID_ReceivePacket (USBD_HandleTypeDef *pdev); +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __USB_CUSTOMHID_H */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/stm32_usb_device_library_class_customhid/src/usbd_customhid.c b/src/hydranfc_v2/hal/src/stm32_usb_device_library_class_customhid/src/usbd_customhid.c new file mode 100644 index 0000000..b877f49 --- /dev/null +++ b/src/hydranfc_v2/hal/src/stm32_usb_device_library_class_customhid/src/usbd_customhid.c @@ -0,0 +1,565 @@ +/** + ****************************************************************************** + * @file usbd_customhid.c + * @author MCD Application Team + * @version V2.4.2 + * @date 11-December-2015 + * @brief This file provides the CUSTOM_HID core functions. + * + * @verbatim + * + * =================================================================== + * CUSTOM_HID Class Description + * =================================================================== + * This module manages the CUSTOM_HID class V1.11 following the "Device Class Definition + * for Human Interface Devices (CUSTOM_HID) Version 1.11 Jun 27, 2001". + * This driver implements the following aspects of the specification: + * - The Boot Interface Subclass + * - Usage Page : Generic Desktop + * - Usage : Vendor + * - Collection : Application + * + * @note In HS mode and when the DMA is used, all variables and data structures + * dealing with the DMA during the transaction process should be 32-bit aligned. + * + * + * @endverbatim + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_customhid.h" +#include "usbd_desc.h" +#include "usbd_ctlreq.h" + + +/** @addtogroup STM32_USB_DEVICE_LIBRARY + * @{ + */ + + +/** @defgroup USBD_CUSTOM_HID + * @brief usbd core module + * @{ + */ + +/** @defgroup USBD_CUSTOM_HID_Private_TypesDefinitions + * @{ + */ +/** + * @} + */ + + +/** @defgroup USBD_CUSTOM_HID_Private_Defines + * @{ + */ + +/** + * @} + */ + + +/** @defgroup USBD_CUSTOM_HID_Private_Macros + * @{ + */ +/** + * @} + */ +/** @defgroup USBD_CUSTOM_HID_Private_FunctionPrototypes + * @{ + */ + + +static uint8_t USBD_CUSTOM_HID_Init (USBD_HandleTypeDef *pdev, + uint8_t cfgidx); + +static uint8_t USBD_CUSTOM_HID_DeInit (USBD_HandleTypeDef *pdev, + uint8_t cfgidx); + +static uint8_t USBD_CUSTOM_HID_Setup (USBD_HandleTypeDef *pdev, + USBD_SetupReqTypedef *req); + +static uint8_t *USBD_CUSTOM_HID_GetCfgDesc (uint16_t *length); + +static uint8_t *USBD_CUSTOM_HID_GetDeviceQualifierDesc (uint16_t *length); + +static uint8_t USBD_CUSTOM_HID_DataIn (USBD_HandleTypeDef *pdev, uint8_t epnum); + +static uint8_t USBD_CUSTOM_HID_DataOut (USBD_HandleTypeDef *pdev, uint8_t epnum); +static uint8_t USBD_CUSTOM_HID_EP0_RxReady (USBD_HandleTypeDef *pdev); +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_Private_Variables + * @{ + */ + +USBD_ClassTypeDef USBD_CUSTOM_HID = +{ + USBD_CUSTOM_HID_Init, + USBD_CUSTOM_HID_DeInit, + USBD_CUSTOM_HID_Setup, + NULL, /*EP0_TxSent*/ + USBD_CUSTOM_HID_EP0_RxReady, /* STATUS STAGE IN */ + USBD_CUSTOM_HID_DataIn, + USBD_CUSTOM_HID_DataOut, + NULL, /*SOF */ + NULL, + NULL, + USBD_CUSTOM_HID_GetCfgDesc, + USBD_CUSTOM_HID_GetCfgDesc, + USBD_CUSTOM_HID_GetCfgDesc, + USBD_CUSTOM_HID_GetDeviceQualifierDesc, +}; + +/* USB CUSTOM_HID device Configuration Descriptor */ +__ALIGN_BEGIN static uint8_t USBD_CUSTOM_HID_CfgDesc[USB_CUSTOM_HID_CONFIG_DESC_SIZ] __ALIGN_END = +{ + /******************************************************************/ + /* 0 */ + 0x09, /* bLength: Configuration Descriptor size */ + USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */ + USB_CUSTOM_HID_CONFIG_DESC_SIZ, /* wTotalLength: Bytes returned */ + 0x00, + 0x01, /*bNumInterfaces: 1 interface*/ + 0x01, /*bConfigurationValue: Configuration value*/ + 0x00, /*iConfiguration: Index of string descriptor describing the configuration*/ + 0x80, /*bmAttributes: bus powered */ + 0xFA, /*MaxPower 500 mA (in unit of 2mA): this current is used for detecting Vbus*/ + + /******************************************************************/ + /* 09 */ + 0x09, /*bLength: Interface Descriptor size*/ + USB_DESC_TYPE_INTERFACE, /*bDescriptorType: Interface descriptor type*/ + 0x00, /*bInterfaceNumber: Number of Interface*/ + 0x00, /*bAlternateSetting: Alternate setting*/ + 0x02, /*bNumEndpoints*/ + 0x03, /*bInterfaceClass: CUSTOM_HID*/ + 0x00, /*bInterfaceSubClass : 1=BOOT, 0=no boot*/ + 0x00, /*nInterfaceProtocol : 0=none, 1=keyboard, 2=mouse*/ + 0, /*iInterface: Index of string descriptor*/ + + /******************************************************************/ + /* 18 */ + 0x09, /*bLength: CUSTOM_HID Descriptor size*/ + CUSTOM_HID_DESCRIPTOR_TYPE, /*bDescriptorType: CUSTOM_HID*/ + 0x11, /*bCUSTOM_HIDUSTOM_HID: CUSTOM_HID Class Spec release number*/ + 0x11, + 0x00, /*bCountryCode: Hardware target country*/ + 0x01, /*bNumDescriptors: Number of CUSTOM_HID class descriptors to follow*/ + 0x22, /*bDescriptorType*/ + USBD_CUSTOM_HID_REPORT_DESC_SIZE, + 0x00, /*wItemLength: Total length of Report descriptor*/ + /******************************************************************/ + /* 27 */ + 0x07, /*bLength: Endpoint Descriptor size*/ + USB_DESC_TYPE_ENDPOINT, /*bDescriptorType:*/ + CUSTOM_HID_EPIN_ADDR, /*bEndpointAddress*/ + 0x03, /*bmAttributes: Interrupt endpoint*/ + CUSTOM_HID_EPIN_SIZE, /*wMaxPacketSize*/ + 0x00, + 0x01, /*bInterval*/ + /* 34 */ + 0x07, /*bLength: Endpoint Descriptor size */ + USB_DESC_TYPE_ENDPOINT, /*bDescriptorType: */ + CUSTOM_HID_EPOUT_ADDR, /*bEndpointAddress*/ + 0x03, /*bmAttributes: Interrupt endpoint */ + CUSTOM_HID_EPOUT_SIZE, /*wMaxPacketSize*/ + 0x00, + 0x01, /*bInterval*/ + + /******************************************************************/ + /* 41 */ +} ; + +/* USB CUSTOM_HID device Configuration Descriptor */ +__ALIGN_BEGIN static uint8_t USBD_CUSTOM_HID_Desc[USB_CUSTOM_HID_DESC_SIZ] __ALIGN_END = +{ + /* 18 */ + 0x09, /*bLength: CUSTOM_HID Descriptor size*/ + CUSTOM_HID_DESCRIPTOR_TYPE, /*bDescriptorType: CUSTOM_HID*/ + 0x00, /*bCUSTOM_HIDUSTOM_HID: CUSTOM_HID Class Spec release number*/ + 0x02, + 0x00, /*bCountryCode: Hardware target country*/ + 0x01, /*bNumDescriptors: Number of CUSTOM_HID class descriptors to follow*/ + 0x22, /*bDescriptorType*/ + USBD_CUSTOM_HID_REPORT_DESC_SIZE,/*wItemLength: Total length of Report descriptor*/ + 0x00, + + +}; + +/* USB Standard Device Descriptor */ +__ALIGN_BEGIN static uint8_t USBD_CUSTOM_HID_DeviceQualifierDesc[USB_LEN_DEV_QUALIFIER_DESC] __ALIGN_END = +{ + USB_LEN_DEV_QUALIFIER_DESC, + USB_DESC_TYPE_DEVICE_QUALIFIER, + 0x00, + 0x02, + 0x00, + 0x00, + 0x00, + 0x40, + 0x01, + 0x00, +}; + +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_Private_Functions + * @{ + */ + +/** + * @brief USBD_CUSTOM_HID_Init + * Initialize the CUSTOM_HID interface + * @param pdev: device instance + * @param cfgidx: Configuration index + * @retval status + */ +static uint8_t USBD_CUSTOM_HID_Init (USBD_HandleTypeDef *pdev, + uint8_t cfgidx) +{ + uint8_t ret = 0; + USBD_CUSTOM_HID_HandleTypeDef *hhid; + /* Open EP IN */ + USBD_LL_OpenEP(pdev, + CUSTOM_HID_EPIN_ADDR, + USBD_EP_TYPE_INTR, + CUSTOM_HID_EPIN_SIZE); + + /* Open EP OUT */ + USBD_LL_OpenEP(pdev, + CUSTOM_HID_EPOUT_ADDR, + USBD_EP_TYPE_INTR, + CUSTOM_HID_EPOUT_SIZE); + + pdev->pClassData = USBD_malloc(sizeof (USBD_CUSTOM_HID_HandleTypeDef)); + + if(pdev->pClassData == NULL) + { + ret = 1; + } + else + { + hhid = (USBD_CUSTOM_HID_HandleTypeDef*) pdev->pClassData; + + hhid->state = CUSTOM_HID_IDLE; + ((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData)->Init(); + /* Prepare Out endpoint to receive 1st packet */ + USBD_LL_PrepareReceive(pdev, CUSTOM_HID_EPOUT_ADDR, hhid->Report_buf, + USBD_CUSTOMHID_OUTREPORT_BUF_SIZE); + } + + return ret; +} + +/** + * @brief USBD_CUSTOM_HID_Init + * DeInitialize the CUSTOM_HID layer + * @param pdev: device instance + * @param cfgidx: Configuration index + * @retval status + */ +static uint8_t USBD_CUSTOM_HID_DeInit (USBD_HandleTypeDef *pdev, + uint8_t cfgidx) +{ + /* Close CUSTOM_HID EP IN */ + USBD_LL_CloseEP(pdev, + CUSTOM_HID_EPIN_ADDR); + + /* Close CUSTOM_HID EP OUT */ + USBD_LL_CloseEP(pdev, + CUSTOM_HID_EPOUT_ADDR); + + /* FRee allocated memory */ + if(pdev->pClassData != NULL) + { + ((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData)->DeInit(); + USBD_free(pdev->pClassData); + pdev->pClassData = NULL; + } + return USBD_OK; +} + +/** + * @brief USBD_CUSTOM_HID_Setup + * Handle the CUSTOM_HID specific requests + * @param pdev: instance + * @param req: usb requests + * @retval status + */ +static uint8_t USBD_CUSTOM_HID_Setup (USBD_HandleTypeDef *pdev, + USBD_SetupReqTypedef *req) +{ + uint16_t len = 0; + uint8_t *pbuf = NULL; + USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef*)pdev->pClassData; + + switch (req->bmRequest & USB_REQ_TYPE_MASK) + { + case USB_REQ_TYPE_CLASS : + switch (req->bRequest) + { + + + case CUSTOM_HID_REQ_SET_PROTOCOL: + hhid->Protocol = (uint8_t)(req->wValue); + break; + + case CUSTOM_HID_REQ_GET_PROTOCOL: + USBD_CtlSendData (pdev, + (uint8_t *)&hhid->Protocol, + 1); + break; + + case CUSTOM_HID_REQ_SET_IDLE: + hhid->IdleState = (uint8_t)(req->wValue >> 8); + break; + + case CUSTOM_HID_REQ_GET_IDLE: + USBD_CtlSendData (pdev, + (uint8_t *)&hhid->IdleState, + 1); + break; + + case CUSTOM_HID_REQ_SET_REPORT: + hhid->IsReportAvailable = 1; + USBD_CtlPrepareRx (pdev, hhid->Report_buf, (uint8_t)(req->wLength)); + + break; + default: + USBD_CtlError (pdev, req); + return USBD_FAIL; + } + break; + + case USB_REQ_TYPE_STANDARD: + switch (req->bRequest) + { + case USB_REQ_GET_DESCRIPTOR: + if( req->wValue >> 8 == CUSTOM_HID_REPORT_DESC) + { + len = MIN(USBD_CUSTOM_HID_REPORT_DESC_SIZE , req->wLength); + pbuf = ((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData)->pReport; + } + else if( req->wValue >> 8 == CUSTOM_HID_DESCRIPTOR_TYPE) + { + pbuf = USBD_CUSTOM_HID_Desc; + len = MIN(USB_CUSTOM_HID_DESC_SIZ , req->wLength); + } + + USBD_CtlSendData (pdev, + pbuf, + len); + + break; + + case USB_REQ_GET_INTERFACE : + USBD_CtlSendData (pdev, + (uint8_t *)&hhid->AltSetting, + 1); + break; + + case USB_REQ_SET_INTERFACE : + hhid->AltSetting = (uint8_t)(req->wValue); + break; + } + } + return USBD_OK; +} + +/** + * @brief USBD_CUSTOM_HID_SendReport + * Send CUSTOM_HID Report + * @param pdev: device instance + * @param buff: pointer to report + * @retval status + */ +uint8_t USBD_CUSTOM_HID_SendReport (USBD_HandleTypeDef *pdev, + uint8_t *report, + uint16_t len) +{ + USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef*)pdev->pClassData; + + if (pdev->dev_state == USBD_STATE_CONFIGURED ) + { + if(hhid->state == CUSTOM_HID_IDLE) + { + hhid->state = CUSTOM_HID_BUSY; + USBD_LL_Transmit (pdev, + CUSTOM_HID_EPIN_ADDR, + report, + len); + } + } + return USBD_OK; +} + +/** + * @brief USBD_CUSTOM_HID_GetCfgDesc + * return configuration descriptor + * @param speed : current device speed + * @param length : pointer data length + * @retval pointer to descriptor buffer + */ +static uint8_t *USBD_CUSTOM_HID_GetCfgDesc (uint16_t *length) +{ + *length = sizeof (USBD_CUSTOM_HID_CfgDesc); + return USBD_CUSTOM_HID_CfgDesc; +} + +/** + * @brief USBD_CUSTOM_HID_DataIn + * handle data IN Stage + * @param pdev: device instance + * @param epnum: endpoint index + * @retval status + */ +static uint8_t USBD_CUSTOM_HID_DataIn (USBD_HandleTypeDef *pdev, + uint8_t epnum) +{ + + /* Ensure that the FIFO is empty before a new transfer, this condition could + be caused by a new transfer before the end of the previous transfer */ + ((USBD_CUSTOM_HID_HandleTypeDef *)pdev->pClassData)->state = CUSTOM_HID_IDLE; + + return USBD_OK; +} + +/** + * @brief USBD_CUSTOM_HID_DataOut + * handle data OUT Stage + * @param pdev: device instance + * @param epnum: endpoint index + * @retval status + */ +static uint8_t USBD_CUSTOM_HID_DataOut (USBD_HandleTypeDef *pdev, uint8_t epnum) +{ + USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef*)pdev->pClassData; + + /* USB data will be immediately processed, this allow next USB traffic being + NAKed till the end of the application processing */ + if(pdev->pClassData != NULL) + { + ((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData)->OutEvent(hhid->Report_buf[0], hhid->Report_buf[1]); + return USBD_OK; + } + else + { + return USBD_FAIL; + } +} +/** + * @brief USBD_CUSTOM_HID_EP0_RxReady + * Handles control request data. + * @param pdev: device instance + * @retval status + */ +uint8_t USBD_CUSTOM_HID_EP0_RxReady(USBD_HandleTypeDef *pdev) +{ + USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef*)pdev->pClassData; + + if (hhid->IsReportAvailable == 1) + { + ((USBD_CUSTOM_HID_ItfTypeDef *)pdev->pUserData)->OutEvent(hhid->Report_buf[0], + hhid->Report_buf[1]); + hhid->IsReportAvailable = 0; + } + + return USBD_OK; +} + +/** +* @brief DeviceQualifierDescriptor +* return Device Qualifier descriptor +* @param length : pointer data length +* @retval pointer to descriptor buffer +*/ +static uint8_t *USBD_CUSTOM_HID_GetDeviceQualifierDesc (uint16_t *length) +{ + *length = sizeof (USBD_CUSTOM_HID_DeviceQualifierDesc); + return USBD_CUSTOM_HID_DeviceQualifierDesc; +} + +/** +* @brief USBD_CUSTOM_HID_RegisterInterface + * @param pdev: device instance + * @param fops: CUSTOMHID Interface callback + * @retval status + */ +uint8_t USBD_CUSTOM_HID_RegisterInterface (USBD_HandleTypeDef *pdev, + USBD_CUSTOM_HID_ItfTypeDef *fops) +{ + uint8_t ret = USBD_FAIL; + + if(fops != NULL) + { + pdev->pUserData= fops; + ret = USBD_OK; + } + + return ret; +} + +/** + + * @brief USBD_CUSTOM_HID_ReceivePacket + * prepare OUT Endpoint for reception + * @param pdev: device instance + * @retval status + */ + +uint8_t USBD_CUSTOM_HID_ReceivePacket(USBD_HandleTypeDef *pdev) +{ + USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef*)pdev->pClassData; + /* Resume USB Out process */ + if(pdev->pClassData != NULL) + { + USBD_LL_PrepareReceive(pdev, CUSTOM_HID_EPOUT_ADDR , hhid->Report_buf, + USBD_CUSTOMHID_OUTREPORT_BUF_SIZE); + return USBD_OK; + } + else + { + return USBD_FAIL; + } +} + +/** + * @} + */ + + +/** + * @} + */ + + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_core.h b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_core.h new file mode 100644 index 0000000..013a5c1 --- /dev/null +++ b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_core.h @@ -0,0 +1,167 @@ +/** + ****************************************************************************** + * @file usbd_core.h + * @author MCD Application Team + * @version V2.4.2 + * @date 11-December-2015 + * @brief Header file for usbd_core.c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __USBD_CORE_H +#define __USBD_CORE_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_conf.h" +#include "usbd_def.h" +#include "usbd_ioreq.h" +#include "usbd_ctlreq.h" + +/** @addtogroup STM32_USB_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USBD_CORE + * @brief This file is the Header file for usbd_core.c file + * @{ + */ + + +/** @defgroup USBD_CORE_Exported_Defines + * @{ + */ + +/** + * @} + */ + + +/** @defgroup USBD_CORE_Exported_TypesDefinitions + * @{ + */ + + +/** + * @} + */ + + + +/** @defgroup USBD_CORE_Exported_Macros + * @{ + */ + +/** + * @} + */ + +/** @defgroup USBD_CORE_Exported_Variables + * @{ + */ +#define USBD_SOF USBD_LL_SOF +/** + * @} + */ + +/** @defgroup USBD_CORE_Exported_FunctionsPrototype + * @{ + */ +USBD_StatusTypeDef USBD_Init(USBD_HandleTypeDef *pdev, USBD_DescriptorsTypeDef *pdesc, uint8_t id); +USBD_StatusTypeDef USBD_DeInit(USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_Start (USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_Stop (USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_RegisterClass(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass); + +USBD_StatusTypeDef USBD_RunTestMode (USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_SetClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx); +USBD_StatusTypeDef USBD_ClrClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx); + +USBD_StatusTypeDef USBD_LL_SetupStage(USBD_HandleTypeDef *pdev, uint8_t *psetup); +USBD_StatusTypeDef USBD_LL_DataOutStage(USBD_HandleTypeDef *pdev , uint8_t epnum, uint8_t *pdata); +USBD_StatusTypeDef USBD_LL_DataInStage(USBD_HandleTypeDef *pdev , uint8_t epnum, uint8_t *pdata); + +USBD_StatusTypeDef USBD_LL_Reset(USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_LL_SetSpeed(USBD_HandleTypeDef *pdev, USBD_SpeedTypeDef speed); +USBD_StatusTypeDef USBD_LL_Suspend(USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_LL_Resume(USBD_HandleTypeDef *pdev); + +USBD_StatusTypeDef USBD_LL_SOF(USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_LL_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum); +USBD_StatusTypeDef USBD_LL_IsoOUTIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum); + +USBD_StatusTypeDef USBD_LL_DevConnected(USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_LL_DevDisconnected(USBD_HandleTypeDef *pdev); + +/* USBD Low Level Driver */ +USBD_StatusTypeDef USBD_LL_Init (USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_LL_DeInit (USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_LL_Stop (USBD_HandleTypeDef *pdev); +USBD_StatusTypeDef USBD_LL_OpenEP (USBD_HandleTypeDef *pdev, + uint8_t ep_addr, + uint8_t ep_type, + uint16_t ep_mps); + +USBD_StatusTypeDef USBD_LL_CloseEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); +USBD_StatusTypeDef USBD_LL_FlushEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); +USBD_StatusTypeDef USBD_LL_StallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); +USBD_StatusTypeDef USBD_LL_ClearStallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); +uint8_t USBD_LL_IsStallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr); +USBD_StatusTypeDef USBD_LL_SetUSBAddress (USBD_HandleTypeDef *pdev, uint8_t dev_addr); +USBD_StatusTypeDef USBD_LL_Transmit (USBD_HandleTypeDef *pdev, + uint8_t ep_addr, + uint8_t *pbuf, + uint16_t size); + +USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, + uint8_t ep_addr, + uint8_t *pbuf, + uint16_t size); + +uint32_t USBD_LL_GetRxDataSize (USBD_HandleTypeDef *pdev, uint8_t ep_addr); +void USBD_LL_Delay (uint32_t Delay); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __USBD_CORE_H */ + +/** + * @} + */ + +/** +* @} +*/ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ + + + diff --git a/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_ctlreq.h b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_ctlreq.h new file mode 100644 index 0000000..bf88252 --- /dev/null +++ b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_ctlreq.h @@ -0,0 +1,113 @@ +/** + ****************************************************************************** + * @file usbd_req.h + * @author MCD Application Team + * @version V2.4.2 + * @date 11-December-2015 + * @brief Header file for the usbd_req.c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __USB_REQUEST_H +#define __USB_REQUEST_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_def.h" + + +/** @addtogroup STM32_USB_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USBD_REQ + * @brief header file for the usbd_req.c file + * @{ + */ + +/** @defgroup USBD_REQ_Exported_Defines + * @{ + */ +/** + * @} + */ + + +/** @defgroup USBD_REQ_Exported_Types + * @{ + */ +/** + * @} + */ + + + +/** @defgroup USBD_REQ_Exported_Macros + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_REQ_Exported_Variables + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_REQ_Exported_FunctionsPrototype + * @{ + */ + +USBD_StatusTypeDef USBD_StdDevReq (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); +USBD_StatusTypeDef USBD_StdItfReq (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); +USBD_StatusTypeDef USBD_StdEPReq (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); + + +void USBD_CtlError (USBD_HandleTypeDef *pdev, USBD_SetupReqTypedef *req); + +void USBD_ParseSetupRequest (USBD_SetupReqTypedef *req, uint8_t *pdata); + +void USBD_GetString (uint8_t *desc, uint8_t *unicode, uint16_t *len); +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __USB_REQUEST_H */ + +/** + * @} + */ + +/** +* @} +*/ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_def.h b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_def.h new file mode 100644 index 0000000..a17a7dd --- /dev/null +++ b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_def.h @@ -0,0 +1,348 @@ +/** + ****************************************************************************** + * @file usbd_def.h + * @author MCD Application Team + * @author 2020 Benjamin VERNOUX modified for hydrafw + * @version V2.4.2 + * @date 11-December-2015 + * @brief General defines for the usb device library + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __USBD_DEF_H +#define __USBD_DEF_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_conf.h" + +#ifdef HAL_USB_H + #undef USB_REQ_GET_STATUS + #undef USB_REQ_CLEAR_FEATURE + #undef USB_REQ_SET_FEATURE + #undef USB_REQ_SET_ADDRESS + #undef USB_REQ_GET_DESCRIPTOR + #undef USB_REQ_SET_DESCRIPTOR + #undef USB_REQ_GET_CONFIGURATION + #undef USB_REQ_SET_CONFIGURATION + #undef USB_REQ_GET_INTERFACE + #undef USB_REQ_SET_INTERFACE + #undef USB_REQ_SYNCH_FRAME + + #undef USB_FEATURE_TEST_MODE +#endif + +/** @addtogroup STM32_USBD_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USB_DEF + * @brief general defines for the usb device library file + * @{ + */ + +/** @defgroup USB_DEF_Exported_Defines + * @{ + */ + +#ifndef NULL +#define NULL 0 +#endif + +#define USB_LEN_DEV_QUALIFIER_DESC 0x0A +#define USB_LEN_DEV_DESC 0x12 +#define USB_LEN_CFG_DESC 0x09 +#define USB_LEN_IF_DESC 0x09 +#define USB_LEN_EP_DESC 0x07 +#define USB_LEN_OTG_DESC 0x03 +#define USB_LEN_LANGID_STR_DESC 0x04 +#define USB_LEN_OTHER_SPEED_DESC_SIZ 0x09 + +#define USBD_IDX_LANGID_STR 0x00 +#define USBD_IDX_MFC_STR 0x01 +#define USBD_IDX_PRODUCT_STR 0x02 +#define USBD_IDX_SERIAL_STR 0x03 +#define USBD_IDX_CONFIG_STR 0x04 +#define USBD_IDX_INTERFACE_STR 0x05 + +#define USB_REQ_TYPE_STANDARD 0x00 +#define USB_REQ_TYPE_CLASS 0x20 +#define USB_REQ_TYPE_VENDOR 0x40 +#define USB_REQ_TYPE_MASK 0x60 + +#define USB_REQ_RECIPIENT_DEVICE 0x00 +#define USB_REQ_RECIPIENT_INTERFACE 0x01 +#define USB_REQ_RECIPIENT_ENDPOINT 0x02 +#define USB_REQ_RECIPIENT_MASK 0x03 + +#define USB_REQ_GET_STATUS 0x00 +#define USB_REQ_CLEAR_FEATURE 0x01 +#define USB_REQ_SET_FEATURE 0x03 +#define USB_REQ_SET_ADDRESS 0x05 +#define USB_REQ_GET_DESCRIPTOR 0x06 +#define USB_REQ_SET_DESCRIPTOR 0x07 +#define USB_REQ_GET_CONFIGURATION 0x08 +#define USB_REQ_SET_CONFIGURATION 0x09 +#define USB_REQ_GET_INTERFACE 0x0A +#define USB_REQ_SET_INTERFACE 0x0B +#define USB_REQ_SYNCH_FRAME 0x0C + +#define USB_DESC_TYPE_DEVICE 1 +#define USB_DESC_TYPE_CONFIGURATION 2 +#define USB_DESC_TYPE_STRING 3 +#define USB_DESC_TYPE_INTERFACE 4 +#define USB_DESC_TYPE_ENDPOINT 5 +#define USB_DESC_TYPE_DEVICE_QUALIFIER 6 +#define USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION 7 +#define USB_DESC_TYPE_BOS 0x0F + +#define USB_CONFIG_REMOTE_WAKEUP 2 +#define USB_CONFIG_SELF_POWERED 1 + +#define USB_FEATURE_EP_HALT 0 +#define USB_FEATURE_REMOTE_WAKEUP 1 +#define USB_FEATURE_TEST_MODE 2 + +#define USB_DEVICE_CAPABITY_TYPE 0x10 + +#define USB_HS_MAX_PACKET_SIZE 512 +#define USB_FS_MAX_PACKET_SIZE 64 +#define USB_MAX_EP0_SIZE 64 + +/* Device Status */ +#define USBD_STATE_DEFAULT 1 +#define USBD_STATE_ADDRESSED 2 +#define USBD_STATE_CONFIGURED 3 +#define USBD_STATE_SUSPENDED 4 + + +/* EP0 State */ +#define USBD_EP0_IDLE 0 +#define USBD_EP0_SETUP 1 +#define USBD_EP0_DATA_IN 2 +#define USBD_EP0_DATA_OUT 3 +#define USBD_EP0_STATUS_IN 4 +#define USBD_EP0_STATUS_OUT 5 +#define USBD_EP0_STALL 6 + +#define USBD_EP_TYPE_CTRL 0 +#define USBD_EP_TYPE_ISOC 1 +#define USBD_EP_TYPE_BULK 2 +#define USBD_EP_TYPE_INTR 3 + + +/** + * @} + */ + + +/** @defgroup USBD_DEF_Exported_TypesDefinitions + * @{ + */ + +typedef struct usb_setup_req +{ + + uint8_t bmRequest; + uint8_t bRequest; + uint16_t wValue; + uint16_t wIndex; + uint16_t wLength; +}USBD_SetupReqTypedef; + +struct _USBD_HandleTypeDef; + +typedef struct _Device_cb +{ + uint8_t (*Init) (struct _USBD_HandleTypeDef *pdev , uint8_t cfgidx); + uint8_t (*DeInit) (struct _USBD_HandleTypeDef *pdev , uint8_t cfgidx); + /* Control Endpoints*/ + uint8_t (*Setup) (struct _USBD_HandleTypeDef *pdev , USBD_SetupReqTypedef *req); + uint8_t (*EP0_TxSent) (struct _USBD_HandleTypeDef *pdev ); + uint8_t (*EP0_RxReady) (struct _USBD_HandleTypeDef *pdev ); + /* Class Specific Endpoints*/ + uint8_t (*DataIn) (struct _USBD_HandleTypeDef *pdev , uint8_t epnum); + uint8_t (*DataOut) (struct _USBD_HandleTypeDef *pdev , uint8_t epnum); + uint8_t (*SOF) (struct _USBD_HandleTypeDef *pdev); + uint8_t (*IsoINIncomplete) (struct _USBD_HandleTypeDef *pdev , uint8_t epnum); + uint8_t (*IsoOUTIncomplete) (struct _USBD_HandleTypeDef *pdev , uint8_t epnum); + + uint8_t *(*GetHSConfigDescriptor)(uint16_t *length); + uint8_t *(*GetFSConfigDescriptor)(uint16_t *length); + uint8_t *(*GetOtherSpeedConfigDescriptor)(uint16_t *length); + uint8_t *(*GetDeviceQualifierDescriptor)(uint16_t *length); +#if (USBD_SUPPORT_USER_STRING == 1) + uint8_t *(*GetUsrStrDescriptor)(struct _USBD_HandleTypeDef *pdev ,uint8_t index, uint16_t *length); +#endif + +} USBD_ClassTypeDef; + +/* Following USB Device Speed */ +typedef enum +{ + USBD_SPEED_HIGH = 0, + USBD_SPEED_FULL = 1, + USBD_SPEED_LOW = 2, +}USBD_SpeedTypeDef; + +/* Following USB Device status */ +typedef enum { + USBD_OK = 0, + USBD_BUSY, + USBD_FAIL, +}USBD_StatusTypeDef; + +/* USB Device descriptors structure */ +typedef struct +{ + uint8_t *(*GetDeviceDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); + uint8_t *(*GetLangIDStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); + uint8_t *(*GetManufacturerStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); + uint8_t *(*GetProductStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); + uint8_t *(*GetSerialStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); + uint8_t *(*GetConfigurationStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); + uint8_t *(*GetInterfaceStrDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); +#if (USBD_LPM_ENABLED == 1) + uint8_t *(*GetBOSDescriptor)( USBD_SpeedTypeDef speed , uint16_t *length); +#endif +} USBD_DescriptorsTypeDef; + +/* USB Device handle structure */ +typedef struct +{ + uint32_t status; + uint32_t total_length; + uint32_t rem_length; + uint32_t maxpacket; +} USBD_EndpointTypeDef; + +/* USB Device handle structure */ +typedef struct _USBD_HandleTypeDef +{ + uint8_t id; + uint32_t dev_config; + uint32_t dev_default_config; + uint32_t dev_config_status; + USBD_SpeedTypeDef dev_speed; + USBD_EndpointTypeDef ep_in[15]; + USBD_EndpointTypeDef ep_out[15]; + uint32_t ep0_state; + uint32_t ep0_data_len; + uint8_t dev_state; + uint8_t dev_old_state; + uint8_t dev_address; + uint8_t dev_connection_status; + uint8_t dev_test_mode; + uint32_t dev_remote_wakeup; + + USBD_SetupReqTypedef request; + USBD_DescriptorsTypeDef *pDesc; + USBD_ClassTypeDef *pClass; + void *pClassData; + void *pUserData; + void *pData; +} USBD_HandleTypeDef; + +/** + * @} + */ + + + +/** @defgroup USBD_DEF_Exported_Macros + * @{ + */ +#define SWAPBYTE(addr) (((uint16_t)(*((uint8_t *)(addr)))) + \ + (((uint16_t)(*(((uint8_t *)(addr)) + 1))) << 8)) + +#define LOBYTE(x) ((uint8_t)(x & 0x00FF)) +#define HIBYTE(x) ((uint8_t)((x & 0xFF00) >>8)) +#ifndef MIN +#define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) + + +#if defined ( __GNUC__ ) + #ifndef __weak + #define __weak __attribute__((weak)) + #endif /* __weak */ + #ifndef __packed + #define __packed __attribute__((__packed__)) + #endif /* __packed */ +#endif /* __GNUC__ */ + + +/* In HS mode and when the DMA is used, all variables and data structures dealing + with the DMA during the transaction process should be 4-bytes aligned */ + +#if defined (__GNUC__) /* GNU Compiler */ + #define __ALIGN_END __attribute__ ((aligned (4))) + #define __ALIGN_BEGIN +#else + #define __ALIGN_END + #if defined (__CC_ARM) /* ARM Compiler */ + #define __ALIGN_BEGIN __align(4) + #elif defined (__ICCARM__) /* IAR Compiler */ + #define __ALIGN_BEGIN + #elif defined (__TASKING__) /* TASKING Compiler */ + #define __ALIGN_BEGIN __align(4) + #endif /* __CC_ARM */ +#endif /* __GNUC__ */ + + +/** + * @} + */ + +/** @defgroup USBD_DEF_Exported_Variables + * @{ + */ + +/** + * @} + */ + +/** @defgroup USBD_DEF_Exported_FunctionsPrototype + * @{ + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __USBD_DEF_H */ + +/** + * @} + */ + +/** +* @} +*/ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_ioreq.h b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_ioreq.h new file mode 100644 index 0000000..b476307 --- /dev/null +++ b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/inc/usbd_ioreq.h @@ -0,0 +1,128 @@ +/** + ****************************************************************************** + * @file usbd_ioreq.h + * @author MCD Application Team + * @version V2.4.2 + * @date 11-December-2015 + * @brief Header file for the usbd_ioreq.c file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __USBD_IOREQ_H +#define __USBD_IOREQ_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_def.h" +#include "usbd_core.h" + +/** @addtogroup STM32_USB_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USBD_IOREQ + * @brief header file for the usbd_ioreq.c file + * @{ + */ + +/** @defgroup USBD_IOREQ_Exported_Defines + * @{ + */ +/** + * @} + */ + + +/** @defgroup USBD_IOREQ_Exported_Types + * @{ + */ + + +/** + * @} + */ + + + +/** @defgroup USBD_IOREQ_Exported_Macros + * @{ + */ + +/** + * @} + */ + +/** @defgroup USBD_IOREQ_Exported_Variables + * @{ + */ + +/** + * @} + */ + +/** @defgroup USBD_IOREQ_Exported_FunctionsPrototype + * @{ + */ + +USBD_StatusTypeDef USBD_CtlSendData (USBD_HandleTypeDef *pdev, + uint8_t *buf, + uint16_t len); + +USBD_StatusTypeDef USBD_CtlContinueSendData (USBD_HandleTypeDef *pdev, + uint8_t *pbuf, + uint16_t len); + +USBD_StatusTypeDef USBD_CtlPrepareRx (USBD_HandleTypeDef *pdev, + uint8_t *pbuf, + uint16_t len); + +USBD_StatusTypeDef USBD_CtlContinueRx (USBD_HandleTypeDef *pdev, + uint8_t *pbuf, + uint16_t len); + +USBD_StatusTypeDef USBD_CtlSendStatus (USBD_HandleTypeDef *pdev); + +USBD_StatusTypeDef USBD_CtlReceiveStatus (USBD_HandleTypeDef *pdev); + +uint16_t USBD_GetRxCount (USBD_HandleTypeDef *pdev , + uint8_t epnum); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __USBD_IOREQ_H */ + +/** + * @} + */ + +/** +* @} +*/ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_core.c b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_core.c new file mode 100644 index 0000000..0158829 --- /dev/null +++ b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_core.c @@ -0,0 +1,565 @@ +/** + ****************************************************************************** + * @file usbd_core.c + * @author MCD Application Team + * @version V2.4.2 + * @date 11-December-2015 + * @brief This file provides all the USBD core functions. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_core.h" + +/** @addtogroup STM32_USBD_DEVICE_LIBRARY +* @{ +*/ + + +/** @defgroup USBD_CORE +* @brief usbd core module +* @{ +*/ + +/** @defgroup USBD_CORE_Private_TypesDefinitions +* @{ +*/ +/** +* @} +*/ + + +/** @defgroup USBD_CORE_Private_Defines +* @{ +*/ + +/** +* @} +*/ + + +/** @defgroup USBD_CORE_Private_Macros +* @{ +*/ +/** +* @} +*/ + + + + +/** @defgroup USBD_CORE_Private_FunctionPrototypes +* @{ +*/ + +/** +* @} +*/ + +/** @defgroup USBD_CORE_Private_Variables +* @{ +*/ + +/** +* @} +*/ + +/** @defgroup USBD_CORE_Private_Functions +* @{ +*/ + +/** +* @brief USBD_Init +* Initializes the device stack and load the class driver +* @param pdev: device instance +* @param pdesc: Descriptor structure address +* @param id: Low level core index +* @retval None +*/ +USBD_StatusTypeDef USBD_Init(USBD_HandleTypeDef *pdev, USBD_DescriptorsTypeDef *pdesc, uint8_t id) +{ + /* Check whether the USB Host handle is valid */ + if(pdev == NULL) + { + USBD_ErrLog("Invalid Device handle"); + return USBD_FAIL; + } + + /* Unlink previous class*/ + if(pdev->pClass != NULL) + { + pdev->pClass = NULL; + } + + /* Assign USBD Descriptors */ + if(pdesc != NULL) + { + pdev->pDesc = pdesc; + } + + /* Set Device initial State */ + pdev->dev_state = USBD_STATE_DEFAULT; + pdev->id = id; + /* Initialize low level driver */ + USBD_LL_Init(pdev); + + return USBD_OK; +} + +/** +* @brief USBD_DeInit +* Re-Initialize th device library +* @param pdev: device instance +* @retval status: status +*/ +USBD_StatusTypeDef USBD_DeInit(USBD_HandleTypeDef *pdev) +{ + /* Set Default State */ + pdev->dev_state = USBD_STATE_DEFAULT; + + /* Free Class Resources */ + pdev->pClass->DeInit(pdev, pdev->dev_config); + + /* Stop the low level driver */ + USBD_LL_Stop(pdev); + + /* Initialize low level driver */ + USBD_LL_DeInit(pdev); + + return USBD_OK; +} + + +/** + * @brief USBD_RegisterClass + * Link class driver to Device Core. + * @param pDevice : Device Handle + * @param pclass: Class handle + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_RegisterClass(USBD_HandleTypeDef *pdev, USBD_ClassTypeDef *pclass) +{ + USBD_StatusTypeDef status = USBD_OK; + if(pclass != 0) + { + /* link the class to the USB Device handle */ + pdev->pClass = pclass; + status = USBD_OK; + } + else + { + USBD_ErrLog("Invalid Class handle"); + status = USBD_FAIL; + } + + return status; +} + +/** + * @brief USBD_Start + * Start the USB Device Core. + * @param pdev: Device Handle + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_Start (USBD_HandleTypeDef *pdev) +{ + + /* Start the low level driver */ + USBD_LL_Start(pdev); + + return USBD_OK; +} + +/** + * @brief USBD_Stop + * Stop the USB Device Core. + * @param pdev: Device Handle + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_Stop (USBD_HandleTypeDef *pdev) +{ + /* Free Class Resources */ + pdev->pClass->DeInit(pdev, pdev->dev_config); + + /* Stop the low level driver */ + USBD_LL_Stop(pdev); + + return USBD_OK; +} + +/** +* @brief USBD_RunTestMode +* Launch test mode process +* @param pdev: device instance +* @retval status +*/ +USBD_StatusTypeDef USBD_RunTestMode (USBD_HandleTypeDef *pdev) +{ + return USBD_OK; +} + + +/** +* @brief USBD_SetClassConfig +* Configure device and start the interface +* @param pdev: device instance +* @param cfgidx: configuration index +* @retval status +*/ + +USBD_StatusTypeDef USBD_SetClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx) +{ + USBD_StatusTypeDef ret = USBD_FAIL; + + if(pdev->pClass != NULL) + { + /* Set configuration and Start the Class*/ + if(pdev->pClass->Init(pdev, cfgidx) == 0) + { + ret = USBD_OK; + } + } + return ret; +} + +/** +* @brief USBD_ClrClassConfig +* Clear current configuration +* @param pdev: device instance +* @param cfgidx: configuration index +* @retval status: USBD_StatusTypeDef +*/ +USBD_StatusTypeDef USBD_ClrClassConfig(USBD_HandleTypeDef *pdev, uint8_t cfgidx) +{ + /* Clear configuration and De-initialize the Class process*/ + pdev->pClass->DeInit(pdev, cfgidx); + return USBD_OK; +} + + +/** +* @brief USBD_SetupStage +* Handle the setup stage +* @param pdev: device instance +* @retval status +*/ +USBD_StatusTypeDef USBD_LL_SetupStage(USBD_HandleTypeDef *pdev, uint8_t *psetup) +{ + + USBD_ParseSetupRequest(&pdev->request, psetup); + + pdev->ep0_state = USBD_EP0_SETUP; + pdev->ep0_data_len = pdev->request.wLength; + + switch (pdev->request.bmRequest & 0x1F) + { + case USB_REQ_RECIPIENT_DEVICE: + USBD_StdDevReq (pdev, &pdev->request); + break; + + case USB_REQ_RECIPIENT_INTERFACE: + USBD_StdItfReq(pdev, &pdev->request); + break; + + case USB_REQ_RECIPIENT_ENDPOINT: + USBD_StdEPReq(pdev, &pdev->request); + break; + + default: + USBD_LL_StallEP(pdev , pdev->request.bmRequest & 0x80); + break; + } + return USBD_OK; +} + +/** +* @brief USBD_DataOutStage +* Handle data OUT stage +* @param pdev: device instance +* @param epnum: endpoint index +* @retval status +*/ +USBD_StatusTypeDef USBD_LL_DataOutStage(USBD_HandleTypeDef *pdev , uint8_t epnum, uint8_t *pdata) +{ + USBD_EndpointTypeDef *pep; + + if(epnum == 0) + { + pep = &pdev->ep_out[0]; + + if ( pdev->ep0_state == USBD_EP0_DATA_OUT) + { + if(pep->rem_length > pep->maxpacket) + { + pep->rem_length -= pep->maxpacket; + + USBD_CtlContinueRx (pdev, + pdata, + MIN(pep->rem_length ,pep->maxpacket)); + } + else + { + if((pdev->pClass->EP0_RxReady != NULL)&& + (pdev->dev_state == USBD_STATE_CONFIGURED)) + { + pdev->pClass->EP0_RxReady(pdev); + } + USBD_CtlSendStatus(pdev); + } + } + } + else if((pdev->pClass->DataOut != NULL)&& + (pdev->dev_state == USBD_STATE_CONFIGURED)) + { + pdev->pClass->DataOut(pdev, epnum); + } + return USBD_OK; +} + +/** +* @brief USBD_DataInStage +* Handle data in stage +* @param pdev: device instance +* @param epnum: endpoint index +* @retval status +*/ +USBD_StatusTypeDef USBD_LL_DataInStage(USBD_HandleTypeDef *pdev ,uint8_t epnum, uint8_t *pdata) +{ + USBD_EndpointTypeDef *pep; + + if(epnum == 0) + { + pep = &pdev->ep_in[0]; + + if ( pdev->ep0_state == USBD_EP0_DATA_IN) + { + if(pep->rem_length > pep->maxpacket) + { + pep->rem_length -= pep->maxpacket; + + USBD_CtlContinueSendData (pdev, + pdata, + pep->rem_length); + + /* Prepare endpoint for premature end of transfer */ + USBD_LL_PrepareReceive (pdev, + 0, + NULL, + 0); + } + else + { /* last packet is MPS multiple, so send ZLP packet */ + if((pep->total_length % pep->maxpacket == 0) && + (pep->total_length >= pep->maxpacket) && + (pep->total_length < pdev->ep0_data_len )) + { + + USBD_CtlContinueSendData(pdev , NULL, 0); + pdev->ep0_data_len = 0; + + /* Prepare endpoint for premature end of transfer */ + USBD_LL_PrepareReceive (pdev, + 0, + NULL, + 0); + } + else + { + if((pdev->pClass->EP0_TxSent != NULL)&& + (pdev->dev_state == USBD_STATE_CONFIGURED)) + { + pdev->pClass->EP0_TxSent(pdev); + } + USBD_CtlReceiveStatus(pdev); + } + } + } + if (pdev->dev_test_mode == 1) + { + USBD_RunTestMode(pdev); + pdev->dev_test_mode = 0; + } + } + else if((pdev->pClass->DataIn != NULL)&& + (pdev->dev_state == USBD_STATE_CONFIGURED)) + { + pdev->pClass->DataIn(pdev, epnum); + } + return USBD_OK; +} + +/** +* @brief USBD_LL_Reset +* Handle Reset event +* @param pdev: device instance +* @retval status +*/ + +USBD_StatusTypeDef USBD_LL_Reset(USBD_HandleTypeDef *pdev) +{ + /* Open EP0 OUT */ + USBD_LL_OpenEP(pdev, + 0x00, + USBD_EP_TYPE_CTRL, + USB_MAX_EP0_SIZE); + + pdev->ep_out[0].maxpacket = USB_MAX_EP0_SIZE; + + /* Open EP0 IN */ + USBD_LL_OpenEP(pdev, + 0x80, + USBD_EP_TYPE_CTRL, + USB_MAX_EP0_SIZE); + + pdev->ep_in[0].maxpacket = USB_MAX_EP0_SIZE; + /* Upon Reset call user call back */ + pdev->dev_state = USBD_STATE_DEFAULT; + + if (pdev->pClassData) + pdev->pClass->DeInit(pdev, pdev->dev_config); + + + return USBD_OK; +} + + + + +/** +* @brief USBD_LL_Reset +* Handle Reset event +* @param pdev: device instance +* @retval status +*/ +USBD_StatusTypeDef USBD_LL_SetSpeed(USBD_HandleTypeDef *pdev, USBD_SpeedTypeDef speed) +{ + pdev->dev_speed = speed; + return USBD_OK; +} + +/** +* @brief USBD_Suspend +* Handle Suspend event +* @param pdev: device instance +* @retval status +*/ + +USBD_StatusTypeDef USBD_LL_Suspend(USBD_HandleTypeDef *pdev) +{ + pdev->dev_old_state = pdev->dev_state; + pdev->dev_state = USBD_STATE_SUSPENDED; + return USBD_OK; +} + +/** +* @brief USBD_Resume +* Handle Resume event +* @param pdev: device instance +* @retval status +*/ + +USBD_StatusTypeDef USBD_LL_Resume(USBD_HandleTypeDef *pdev) +{ + pdev->dev_state = pdev->dev_old_state; + return USBD_OK; +} + +/** +* @brief USBD_SOF +* Handle SOF event +* @param pdev: device instance +* @retval status +*/ + +USBD_StatusTypeDef USBD_LL_SOF(USBD_HandleTypeDef *pdev) +{ + if(pdev->dev_state == USBD_STATE_CONFIGURED) + { + if(pdev->pClass->SOF != NULL) + { + pdev->pClass->SOF(pdev); + } + } + return USBD_OK; +} + +/** +* @brief USBD_IsoINIncomplete +* Handle iso in incomplete event +* @param pdev: device instance +* @retval status +*/ +USBD_StatusTypeDef USBD_LL_IsoINIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum) +{ + return USBD_OK; +} + +/** +* @brief USBD_IsoOUTIncomplete +* Handle iso out incomplete event +* @param pdev: device instance +* @retval status +*/ +USBD_StatusTypeDef USBD_LL_IsoOUTIncomplete(USBD_HandleTypeDef *pdev, uint8_t epnum) +{ + return USBD_OK; +} + +/** +* @brief USBD_DevConnected +* Handle device connection event +* @param pdev: device instance +* @retval status +*/ +USBD_StatusTypeDef USBD_LL_DevConnected(USBD_HandleTypeDef *pdev) +{ + return USBD_OK; +} + +/** +* @brief USBD_DevDisconnected +* Handle device disconnection event +* @param pdev: device instance +* @retval status +*/ +USBD_StatusTypeDef USBD_LL_DevDisconnected(USBD_HandleTypeDef *pdev) +{ + /* Free Class Resources */ + pdev->dev_state = USBD_STATE_DEFAULT; + pdev->pClass->DeInit(pdev, pdev->dev_config); + + return USBD_OK; +} +/** +* @} +*/ + + +/** +* @} +*/ + + +/** +* @} +*/ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ + diff --git a/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_ctlreq.c b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_ctlreq.c new file mode 100644 index 0000000..49330c6 --- /dev/null +++ b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_ctlreq.c @@ -0,0 +1,782 @@ +/** + ****************************************************************************** + * @file usbd_req.c + * @author MCD Application Team + * @version V2.4.2 + * @date 11-December-2015 + * @brief This file provides the standard USB requests following chapter 9. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_ctlreq.h" +#include "usbd_ioreq.h" + + +/** @addtogroup STM32_USBD_STATE_DEVICE_LIBRARY + * @{ + */ + + +/** @defgroup USBD_REQ + * @brief USB standard requests module + * @{ + */ + +/** @defgroup USBD_REQ_Private_TypesDefinitions + * @{ + */ +/** + * @} + */ + + +/** @defgroup USBD_REQ_Private_Defines + * @{ + */ + +/** + * @} + */ + + +/** @defgroup USBD_REQ_Private_Macros + * @{ + */ +/** + * @} + */ + + +/** @defgroup USBD_REQ_Private_Variables + * @{ + */ +/** + * @} + */ + + +/** @defgroup USBD_REQ_Private_FunctionPrototypes + * @{ + */ +static void USBD_GetDescriptor(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req); + +static void USBD_SetAddress(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req); + +static void USBD_SetConfig(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req); + +static void USBD_GetConfig(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req); + +static void USBD_GetStatus(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req); + +static void USBD_SetFeature(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req); + +static void USBD_ClrFeature(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req); + +static uint8_t USBD_GetLen(uint8_t *buf); + +/** + * @} + */ + + +/** @defgroup USBD_REQ_Private_Functions + * @{ + */ + + +/** +* @brief USBD_StdDevReq +* Handle standard usb device requests +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +USBD_StatusTypeDef USBD_StdDevReq (USBD_HandleTypeDef *pdev , USBD_SetupReqTypedef *req) +{ + USBD_StatusTypeDef ret = USBD_OK; + + switch (req->bRequest) + { + case USB_REQ_GET_DESCRIPTOR: + + USBD_GetDescriptor (pdev, req) ; + break; + + case USB_REQ_SET_ADDRESS: + USBD_SetAddress(pdev, req); + break; + + case USB_REQ_SET_CONFIGURATION: + USBD_SetConfig (pdev , req); + break; + + case USB_REQ_GET_CONFIGURATION: + USBD_GetConfig (pdev , req); + break; + + case USB_REQ_GET_STATUS: + USBD_GetStatus (pdev , req); + break; + + + case USB_REQ_SET_FEATURE: + USBD_SetFeature (pdev , req); + break; + + case USB_REQ_CLEAR_FEATURE: + USBD_ClrFeature (pdev , req); + break; + + default: + USBD_CtlError(pdev , req); + break; + } + + return ret; +} + +/** +* @brief USBD_StdItfReq +* Handle standard usb interface requests +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +USBD_StatusTypeDef USBD_StdItfReq (USBD_HandleTypeDef *pdev , USBD_SetupReqTypedef *req) +{ + USBD_StatusTypeDef ret = USBD_OK; + + switch (pdev->dev_state) + { + case USBD_STATE_CONFIGURED: + + if (LOBYTE(req->wIndex) <= USBD_MAX_NUM_INTERFACES) + { + pdev->pClass->Setup (pdev, req); + + if((req->wLength == 0)&& (ret == USBD_OK)) + { + USBD_CtlSendStatus(pdev); + } + } + else + { + USBD_CtlError(pdev , req); + } + break; + + default: + USBD_CtlError(pdev , req); + break; + } + return USBD_OK; +} + +/** +* @brief USBD_StdEPReq +* Handle standard usb endpoint requests +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +USBD_StatusTypeDef USBD_StdEPReq (USBD_HandleTypeDef *pdev , USBD_SetupReqTypedef *req) +{ + + uint8_t ep_addr; + USBD_StatusTypeDef ret = USBD_OK; + USBD_EndpointTypeDef *pep; + ep_addr = LOBYTE(req->wIndex); + + /* Check if it is a class request */ + if ((req->bmRequest & 0x60) == 0x20) + { + pdev->pClass->Setup (pdev, req); + + return USBD_OK; + } + + switch (req->bRequest) + { + + case USB_REQ_SET_FEATURE : + + switch (pdev->dev_state) + { + case USBD_STATE_ADDRESSED: + if ((ep_addr != 0x00) && (ep_addr != 0x80)) + { + USBD_LL_StallEP(pdev , ep_addr); + } + break; + + case USBD_STATE_CONFIGURED: + if (req->wValue == USB_FEATURE_EP_HALT) + { + if ((ep_addr != 0x00) && (ep_addr != 0x80)) + { + USBD_LL_StallEP(pdev , ep_addr); + + } + } + pdev->pClass->Setup (pdev, req); + USBD_CtlSendStatus(pdev); + + break; + + default: + USBD_CtlError(pdev , req); + break; + } + break; + + case USB_REQ_CLEAR_FEATURE : + + switch (pdev->dev_state) + { + case USBD_STATE_ADDRESSED: + if ((ep_addr != 0x00) && (ep_addr != 0x80)) + { + USBD_LL_StallEP(pdev , ep_addr); + } + break; + + case USBD_STATE_CONFIGURED: + if (req->wValue == USB_FEATURE_EP_HALT) + { + if ((ep_addr & 0x7F) != 0x00) + { + USBD_LL_ClearStallEP(pdev , ep_addr); + pdev->pClass->Setup (pdev, req); + } + USBD_CtlSendStatus(pdev); + } + break; + + default: + USBD_CtlError(pdev , req); + break; + } + break; + + case USB_REQ_GET_STATUS: + switch (pdev->dev_state) + { + case USBD_STATE_ADDRESSED: + if ((ep_addr & 0x7F) != 0x00) + { + USBD_LL_StallEP(pdev , ep_addr); + } + break; + + case USBD_STATE_CONFIGURED: + pep = ((ep_addr & 0x80) == 0x80) ? &pdev->ep_in[ep_addr & 0x7F]:\ + &pdev->ep_out[ep_addr & 0x7F]; + if(USBD_LL_IsStallEP(pdev, ep_addr)) + { + pep->status = 0x0001; + } + else + { + pep->status = 0x0000; + } + + USBD_CtlSendData (pdev, + (uint8_t *)&pep->status, + 2); + break; + + default: + USBD_CtlError(pdev , req); + break; + } + break; + + default: + break; + } + return ret; +} +/** +* @brief USBD_GetDescriptor +* Handle Get Descriptor requests +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +static void USBD_GetDescriptor(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req) +{ + uint16_t len; + uint8_t *pbuf; + + + switch (req->wValue >> 8) + { +#if (USBD_LPM_ENABLED == 1) + case USB_DESC_TYPE_BOS: + pbuf = pdev->pDesc->GetBOSDescriptor(pdev->dev_speed, &len); + break; +#endif + case USB_DESC_TYPE_DEVICE: + pbuf = pdev->pDesc->GetDeviceDescriptor(pdev->dev_speed, &len); + break; + + case USB_DESC_TYPE_CONFIGURATION: + if(pdev->dev_speed == USBD_SPEED_HIGH ) + { + pbuf = (uint8_t *)pdev->pClass->GetHSConfigDescriptor(&len); + pbuf[1] = USB_DESC_TYPE_CONFIGURATION; + } + else + { + pbuf = (uint8_t *)pdev->pClass->GetFSConfigDescriptor(&len); + pbuf[1] = USB_DESC_TYPE_CONFIGURATION; + } + break; + + case USB_DESC_TYPE_STRING: + switch ((uint8_t)(req->wValue)) + { + case USBD_IDX_LANGID_STR: + pbuf = pdev->pDesc->GetLangIDStrDescriptor(pdev->dev_speed, &len); + break; + + case USBD_IDX_MFC_STR: + pbuf = pdev->pDesc->GetManufacturerStrDescriptor(pdev->dev_speed, &len); + break; + + case USBD_IDX_PRODUCT_STR: + pbuf = pdev->pDesc->GetProductStrDescriptor(pdev->dev_speed, &len); + break; + + case USBD_IDX_SERIAL_STR: + pbuf = pdev->pDesc->GetSerialStrDescriptor(pdev->dev_speed, &len); + break; + + case USBD_IDX_CONFIG_STR: + pbuf = pdev->pDesc->GetConfigurationStrDescriptor(pdev->dev_speed, &len); + break; + + case USBD_IDX_INTERFACE_STR: + pbuf = pdev->pDesc->GetInterfaceStrDescriptor(pdev->dev_speed, &len); + break; + + default: +#if (USBD_SUPPORT_USER_STRING == 1) + pbuf = pdev->pClass->GetUsrStrDescriptor(pdev, (req->wValue) , &len); + break; +#else + USBD_CtlError(pdev , req); + return; +#endif + } + break; + case USB_DESC_TYPE_DEVICE_QUALIFIER: + + if(pdev->dev_speed == USBD_SPEED_HIGH ) + { + pbuf = (uint8_t *)pdev->pClass->GetDeviceQualifierDescriptor(&len); + break; + } + else + { + USBD_CtlError(pdev , req); + return; + } + + case USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION: + if(pdev->dev_speed == USBD_SPEED_HIGH ) + { + pbuf = (uint8_t *)pdev->pClass->GetOtherSpeedConfigDescriptor(&len); + pbuf[1] = USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION; + break; + } + else + { + USBD_CtlError(pdev , req); + return; + } + + default: + USBD_CtlError(pdev , req); + return; + } + + if((len != 0)&& (req->wLength != 0)) + { + + len = MIN(len , req->wLength); + + USBD_CtlSendData (pdev, + pbuf, + len); + } + +} + +/** +* @brief USBD_SetAddress +* Set device address +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +static void USBD_SetAddress(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req) +{ + uint8_t dev_addr; + + if ((req->wIndex == 0) && (req->wLength == 0)) + { + dev_addr = (uint8_t)(req->wValue) & 0x7F; + + if (pdev->dev_state == USBD_STATE_CONFIGURED) + { + USBD_CtlError(pdev , req); + } + else + { + pdev->dev_address = dev_addr; + USBD_LL_SetUSBAddress(pdev, dev_addr); + USBD_CtlSendStatus(pdev); + + if (dev_addr != 0) + { + pdev->dev_state = USBD_STATE_ADDRESSED; + } + else + { + pdev->dev_state = USBD_STATE_DEFAULT; + } + } + } + else + { + USBD_CtlError(pdev , req); + } +} + +/** +* @brief USBD_SetConfig +* Handle Set device configuration request +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +static void USBD_SetConfig(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req) +{ + + static uint8_t cfgidx; + + cfgidx = (uint8_t)(req->wValue); + + if (cfgidx > USBD_MAX_NUM_CONFIGURATION ) + { + USBD_CtlError(pdev , req); + } + else + { + switch (pdev->dev_state) + { + case USBD_STATE_ADDRESSED: + if (cfgidx) + { + pdev->dev_config = cfgidx; + pdev->dev_state = USBD_STATE_CONFIGURED; + if(USBD_SetClassConfig(pdev , cfgidx) == USBD_FAIL) + { + USBD_CtlError(pdev , req); + return; + } + USBD_CtlSendStatus(pdev); + } + else + { + USBD_CtlSendStatus(pdev); + } + break; + + case USBD_STATE_CONFIGURED: + if (cfgidx == 0) + { + pdev->dev_state = USBD_STATE_ADDRESSED; + pdev->dev_config = cfgidx; + USBD_ClrClassConfig(pdev , cfgidx); + USBD_CtlSendStatus(pdev); + + } + else if (cfgidx != pdev->dev_config) + { + /* Clear old configuration */ + USBD_ClrClassConfig(pdev , pdev->dev_config); + + /* set new configuration */ + pdev->dev_config = cfgidx; + if(USBD_SetClassConfig(pdev , cfgidx) == USBD_FAIL) + { + USBD_CtlError(pdev , req); + return; + } + USBD_CtlSendStatus(pdev); + } + else + { + USBD_CtlSendStatus(pdev); + } + break; + + default: + USBD_CtlError(pdev , req); + break; + } + } +} + +/** +* @brief USBD_GetConfig +* Handle Get device configuration request +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +static void USBD_GetConfig(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req) +{ + + if (req->wLength != 1) + { + USBD_CtlError(pdev , req); + } + else + { + switch (pdev->dev_state ) + { + case USBD_STATE_ADDRESSED: + pdev->dev_default_config = 0; + USBD_CtlSendData (pdev, + (uint8_t *)&pdev->dev_default_config, + 1); + break; + + case USBD_STATE_CONFIGURED: + + USBD_CtlSendData (pdev, + (uint8_t *)&pdev->dev_config, + 1); + break; + + default: + USBD_CtlError(pdev , req); + break; + } + } +} + +/** +* @brief USBD_GetStatus +* Handle Get Status request +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +static void USBD_GetStatus(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req) +{ + + + switch (pdev->dev_state) + { + case USBD_STATE_ADDRESSED: + case USBD_STATE_CONFIGURED: + +#if ( USBD_SELF_POWERED == 1) + pdev->dev_config_status = USB_CONFIG_SELF_POWERED; +#else + pdev->dev_config_status = 0; +#endif + + if (pdev->dev_remote_wakeup) + { + pdev->dev_config_status |= USB_CONFIG_REMOTE_WAKEUP; + } + + USBD_CtlSendData (pdev, + (uint8_t *)& pdev->dev_config_status, + 2); + break; + + default : + USBD_CtlError(pdev , req); + break; + } +} + + +/** +* @brief USBD_SetFeature +* Handle Set device feature request +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +static void USBD_SetFeature(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req) +{ + + if (req->wValue == USB_FEATURE_REMOTE_WAKEUP) + { + pdev->dev_remote_wakeup = 1; + pdev->pClass->Setup (pdev, req); + USBD_CtlSendStatus(pdev); + } + +} + + +/** +* @brief USBD_ClrFeature +* Handle clear device feature request +* @param pdev: device instance +* @param req: usb request +* @retval status +*/ +static void USBD_ClrFeature(USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req) +{ + switch (pdev->dev_state) + { + case USBD_STATE_ADDRESSED: + case USBD_STATE_CONFIGURED: + if (req->wValue == USB_FEATURE_REMOTE_WAKEUP) + { + pdev->dev_remote_wakeup = 0; + pdev->pClass->Setup (pdev, req); + USBD_CtlSendStatus(pdev); + } + break; + + default : + USBD_CtlError(pdev , req); + break; + } +} + +/** +* @brief USBD_ParseSetupRequest +* Copy buffer into setup structure +* @param pdev: device instance +* @param req: usb request +* @retval None +*/ + +void USBD_ParseSetupRequest(USBD_SetupReqTypedef *req, uint8_t *pdata) +{ + req->bmRequest = *(uint8_t *) (pdata); + req->bRequest = *(uint8_t *) (pdata + 1); + req->wValue = SWAPBYTE (pdata + 2); + req->wIndex = SWAPBYTE (pdata + 4); + req->wLength = SWAPBYTE (pdata + 6); + +} + +/** +* @brief USBD_CtlError +* Handle USB low level Error +* @param pdev: device instance +* @param req: usb request +* @retval None +*/ + +void USBD_CtlError( USBD_HandleTypeDef *pdev , + USBD_SetupReqTypedef *req) +{ + USBD_LL_StallEP(pdev , 0x80); + USBD_LL_StallEP(pdev , 0); +} + + +/** + * @brief USBD_GetString + * Convert Ascii string into unicode one + * @param desc : descriptor buffer + * @param unicode : Formatted string buffer (unicode) + * @param len : descriptor length + * @retval None + */ +void USBD_GetString(uint8_t *desc, uint8_t *unicode, uint16_t *len) +{ + uint8_t idx = 0; + + if (desc != NULL) + { + *len = USBD_GetLen(desc) * 2 + 2; + unicode[idx++] = *len; + unicode[idx++] = USB_DESC_TYPE_STRING; + + while (*desc != '\0') + { + unicode[idx++] = *desc++; + unicode[idx++] = 0x00; + } + } +} + +/** + * @brief USBD_GetLen + * return the string length + * @param buf : pointer to the ascii string buffer + * @retval string length + */ +static uint8_t USBD_GetLen(uint8_t *buf) +{ + uint8_t len = 0; + + while (*buf != '\0') + { + len++; + buf++; + } + + return len; +} +/** + * @} + */ + + +/** + * @} + */ + + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_ioreq.c b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_ioreq.c new file mode 100644 index 0000000..093afad --- /dev/null +++ b/src/hydranfc_v2/hal/src/stm32_usb_device_library_core/src/usbd_ioreq.c @@ -0,0 +1,236 @@ +/** + ****************************************************************************** + * @file usbd_ioreq.c + * @author MCD Application Team + * @version V2.4.2 + * @date 11-December-2015 + * @brief This file provides the IO requests APIs for control endpoints. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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/software_license_agreement_liberty_v2 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_ioreq.h" + +/** @addtogroup STM32_USB_DEVICE_LIBRARY + * @{ + */ + + +/** @defgroup USBD_IOREQ + * @brief control I/O requests module + * @{ + */ + +/** @defgroup USBD_IOREQ_Private_TypesDefinitions + * @{ + */ +/** + * @} + */ + + +/** @defgroup USBD_IOREQ_Private_Defines + * @{ + */ + +/** + * @} + */ + + +/** @defgroup USBD_IOREQ_Private_Macros + * @{ + */ +/** + * @} + */ + + +/** @defgroup USBD_IOREQ_Private_Variables + * @{ + */ + +/** + * @} + */ + + +/** @defgroup USBD_IOREQ_Private_FunctionPrototypes + * @{ + */ +/** + * @} + */ + + +/** @defgroup USBD_IOREQ_Private_Functions + * @{ + */ + +/** +* @brief USBD_CtlSendData +* send data on the ctl pipe +* @param pdev: device instance +* @param buff: pointer to data buffer +* @param len: length of data to be sent +* @retval status +*/ +USBD_StatusTypeDef USBD_CtlSendData (USBD_HandleTypeDef *pdev, + uint8_t *pbuf, + uint16_t len) +{ + /* Set EP0 State */ + pdev->ep0_state = USBD_EP0_DATA_IN; + pdev->ep_in[0].total_length = len; + pdev->ep_in[0].rem_length = len; + /* Start the transfer */ + USBD_LL_Transmit (pdev, 0x00, pbuf, len); + + return USBD_OK; +} + +/** +* @brief USBD_CtlContinueSendData +* continue sending data on the ctl pipe +* @param pdev: device instance +* @param buff: pointer to data buffer +* @param len: length of data to be sent +* @retval status +*/ +USBD_StatusTypeDef USBD_CtlContinueSendData (USBD_HandleTypeDef *pdev, + uint8_t *pbuf, + uint16_t len) +{ + /* Start the next transfer */ + USBD_LL_Transmit (pdev, 0x00, pbuf, len); + + return USBD_OK; +} + +/** +* @brief USBD_CtlPrepareRx +* receive data on the ctl pipe +* @param pdev: device instance +* @param buff: pointer to data buffer +* @param len: length of data to be received +* @retval status +*/ +USBD_StatusTypeDef USBD_CtlPrepareRx (USBD_HandleTypeDef *pdev, + uint8_t *pbuf, + uint16_t len) +{ + /* Set EP0 State */ + pdev->ep0_state = USBD_EP0_DATA_OUT; + pdev->ep_out[0].total_length = len; + pdev->ep_out[0].rem_length = len; + /* Start the transfer */ + USBD_LL_PrepareReceive (pdev, + 0, + pbuf, + len); + + return USBD_OK; +} + +/** +* @brief USBD_CtlContinueRx +* continue receive data on the ctl pipe +* @param pdev: device instance +* @param buff: pointer to data buffer +* @param len: length of data to be received +* @retval status +*/ +USBD_StatusTypeDef USBD_CtlContinueRx (USBD_HandleTypeDef *pdev, + uint8_t *pbuf, + uint16_t len) +{ + + USBD_LL_PrepareReceive (pdev, + 0, + pbuf, + len); + return USBD_OK; +} +/** +* @brief USBD_CtlSendStatus +* send zero lzngth packet on the ctl pipe +* @param pdev: device instance +* @retval status +*/ +USBD_StatusTypeDef USBD_CtlSendStatus (USBD_HandleTypeDef *pdev) +{ + + /* Set EP0 State */ + pdev->ep0_state = USBD_EP0_STATUS_IN; + + /* Start the transfer */ + USBD_LL_Transmit (pdev, 0x00, NULL, 0); + + return USBD_OK; +} + +/** +* @brief USBD_CtlReceiveStatus +* receive zero lzngth packet on the ctl pipe +* @param pdev: device instance +* @retval status +*/ +USBD_StatusTypeDef USBD_CtlReceiveStatus (USBD_HandleTypeDef *pdev) +{ + /* Set EP0 State */ + pdev->ep0_state = USBD_EP0_STATUS_OUT; + + /* Start the transfer */ + USBD_LL_PrepareReceive ( pdev, + 0, + NULL, + 0); + + return USBD_OK; +} + + +/** +* @brief USBD_GetRxCount +* returns the received data length +* @param pdev: device instance +* @param ep_addr: endpoint address +* @retval Rx Data blength +*/ +uint16_t USBD_GetRxCount (USBD_HandleTypeDef *pdev , uint8_t ep_addr) +{ + return USBD_LL_GetRxDataSize(pdev, ep_addr); +} + +/** + * @} + */ + + +/** + * @} + */ + + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/stream_dispatcher.c b/src/hydranfc_v2/hal/src/stream_dispatcher.c new file mode 100644 index 0000000..97b16d5 --- /dev/null +++ b/src/hydranfc_v2/hal/src/stream_dispatcher.c @@ -0,0 +1,232 @@ +/****************************************************************************** + * @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: ASxxxx firmware + * $Revision: $ + * LANGUAGE: ANSI C + */ + +/*! \file + * + * \author M. Arpa originated by W. Reichart + * \author 2020 Benjamin VERNOUX modified for hydrafw + * + * \brief main dispatcher for streaming protocol uses a stream_driver + * for the io. + * + */ + +/* --------- includes ------------------------------------------------------- */ + +#include +#include +#include "st_stream.h" +#include "stream_dispatcher.h" +#include "stream_driver.h" +#include "logger.h" +#include "platform.h" + +/* ------------- local variables -------------------------------------------- */ +static uint8_t rxBuffer[ST_STREAM_BUFFER_SIZE]; /*! buffer to store protocol packets received from the Host */ +static uint8_t txBuffer[ST_STREAM_BUFFER_SIZE]; /*! buffer to store protocol packets which are transmitted to the Host */ + +static uint8_t lastError; /* flag indicating different types of errors that cannot be reported in the protocol status field */ + +static uint8_t handleFirmwareInformation(uint16_t *toTx, uint8_t *txData) +{ + uint16_t size = strlen(applFirmwareInformation()); + if (size >= *toTx - 1) { + size = *toTx - 1; + } + if (size >= ST_STREAM_SHORT_STRING - 1) { + size = ST_STREAM_SHORT_STRING - 1; + } + *toTx = size + 1; /* for zero terminator */ + memcpy(txData, applFirmwareInformation(), size + 1); + return ST_STREAM_NO_ERROR; +} + +static uint8_t handleFirmwareNumber(uint16_t *toTx, uint8_t *txData) +{ + *toTx = 3; /* 1-byte major, 1-byte minor, 1-byte release marker */ + txData[0] = (firmwareNumber >> 16) & 0xFF; + txData[1] = (firmwareNumber >> 8) & 0xFF; + txData[2] = firmwareNumber & 0xFF; + return ST_STREAM_NO_ERROR; +} + +static uint16_t processReceivedPackets(void) +{ + /* every time we enter this function, the last txBuffer was already sent. + So we fill a new transfer buffer */ + uint8_t *txEnd = txBuffer; /* the txEnd always points to the next position to be filled with data */ + uint16_t txSize = 0; + + while ( StreamHasAnotherPacket()) { + /* read out protocol header data */ + uint8_t protocol = ST_STREAM_DR_GET_PROTOCOL(rxBuffer); + uint16_t rxed = ST_STREAM_DR_GET_RX_LENGTH(rxBuffer); + uint16_t toTx = ST_STREAM_DR_GET_TX_LENGTH(rxBuffer); + uint8_t *rxData = ST_STREAM_PAYLOAD(rxBuffer); + /* set up tx pointer for any data to be transmitted back to the host */ + uint8_t *txData = ST_STREAM_PAYLOAD(txEnd); + uint8_t status = ST_STREAM_NO_ERROR; + int8_t isReadCommand = !(protocol & ST_COM_WRITE_READ_NOT); + protocol &= ~ST_COM_WRITE_READ_NOT; /* remove direction flag */ + + if (rxed > ST_STREAM_MAX_DATA_SIZE) { + /* package is damaged or comes from an unknown source */ + lastError = ST_STREAM_SIZE_ERROR; + /* truncate received packet - will most likely cause problems + at the receiving function, but the size is out of bounds */ + rxed = ST_STREAM_MAX_DATA_SIZE; + } + + /* decide which protocol to execute */ + + switch (protocol) { + case ST_COM_CTRL_CMD_FW_INFORMATION: + status = handleFirmwareInformation(&toTx, txData); + break; + case ST_COM_CTRL_CMD_FW_NUMBER: + status = handleFirmwareNumber(&toTx, txData); + break; + case ST_COM_CTRL_CMD_ENTER_BOOTLOADER: + //bootloaderReboot( ); + break; + case ST_COM_WRITE_REG: + status = applWriteReg(rxed, rxData, &toTx, txData); + break; + case ST_COM_READ_REG: + status = applReadReg(rxed, rxData, &toTx, txData); + break; + default: + if (protocol > ST_COM_CONFIG) { + /* reserved protocol value and not handled so far */ + status = ST_STREAM_UNHANDLED_PROTOCOL; + } else { /* application protocol */ + status = applProcessCmd(protocol, rxed, rxData, + &toTx, txData); + } + break; + } + + /* fill out transmit packet header if any data was produced */ + if (toTx > 0 || isReadCommand) { + ST_STREAM_DT_SET_PROTOCOL(txEnd, protocol); + ST_STREAM_DT_SET_STATUS(txEnd, status); + ST_STREAM_DT_SET_TX_LENGTH(txEnd, toTx); + + /* adjust pointer to the enter next data, and total size */ + txEnd += (toTx + ST_STREAM_HEADER_SIZE); + txSize += (toTx + ST_STREAM_HEADER_SIZE); + } else if (status != ST_STREAM_NO_ERROR) { /* protocol failed, we indicate an error if command itself does not send back */ + lastError = status; + } + + /* remove the handled packet, and move on to next packet */ + StreamPacketProcessed(rxed); + } + + return txSize; +} + +static uint16_t processCyclic(void) +{ + /* every time we enter this function, the last txBuffer was already sent. + So we fill a new transfer buffer */ + uint8_t *txEnd = txBuffer; /* the txEnd always points to the next position to be filled with data */ + uint16_t txSize = 0; + uint16_t toTx; + uint8_t protocol; + uint8_t status = ST_STREAM_NO_ERROR; + + do { + /* set up tx pointer for any data to be transmitted back to the host */ + uint8_t *txData = ST_STREAM_PAYLOAD(txEnd); + toTx = 0; + status = applProcessCyclic(&protocol, &toTx, txData, + ST_STREAM_MAX_DATA_SIZE - txSize); + + /* fill out transmit packet header if any data was produced */ + if (toTx > 0) { + ST_STREAM_DT_SET_PROTOCOL(txEnd, protocol); + ST_STREAM_DT_SET_STATUS(txEnd, status); + ST_STREAM_DT_SET_TX_LENGTH(txEnd, toTx); + + /* adjust pointer to the enter next data, and total size */ + txEnd += (toTx + ST_STREAM_HEADER_SIZE); + txSize += (toTx + ST_STREAM_HEADER_SIZE); + } else if (status != ST_STREAM_NO_ERROR) { /* protocol failed, we indicate an error if command itself does not send back */ + lastError = status; + } + } while (toTx > 0); + + return txSize; +} + +/* --------- global functions ------------------------------------------------------------- */ + +void StreamDispatcherInitAndConnect(void) +{ + StreamDispatcherInit(); + StreamConnect(); +} + +void StreamDispatcherInit(void) +{ + StreamDispatcherGetLastError(); + StreamInitialize(rxBuffer, txBuffer); +} + +uint8_t StreamDispatcherGetLastError(void) +{ + uint8_t temp = lastError; + lastError = ST_STREAM_NO_ERROR; + return temp; +} + +void ProcessIO(void) +{ + uint16_t txSize; + + if ( StreamReady()) { + /* read out data from stream driver, and move it to module-local buffer */ + if ( StreamReceive() > 0) { + /* if we have at least one fully received packet, we start execution */ + + /* interpret one (or more) packets in the module-local buffer */ + txSize = processReceivedPackets(); + + /* transmit any data waiting in the module-local buffer */ + StreamTransmit(txSize); + } + + /* we need to call the processCyclic function for all applications that + have any data to send (without receiving a hid packet). The data to + be sent is written into the module-local buffer */ + txSize = processCyclic(); + + /* transmit any data waiting in the module-local buffer */ + StreamTransmit(txSize); + } +} + diff --git a/src/hydranfc_v2/hal/src/timer.c b/src/hydranfc_v2/hal/src/timer.c new file mode 100644 index 0000000..30d69ed --- /dev/null +++ b/src/hydranfc_v2/hal/src/timer.c @@ -0,0 +1,113 @@ +/****************************************************************************** + * @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: + * + * 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" + +/* +****************************************************************************** +* LOCAL DEFINES +****************************************************************************** +*/ + +/* +****************************************************************************** +* LOCAL VARIABLES +****************************************************************************** +*/ +static uint32_t timerStopwatchTick; + +/* +****************************************************************************** +* GLOBAL FUNCTIONS +****************************************************************************** +*/ + +/*******************************************************************************/ +uint32_t timerCalculateTimer( uint16_t time ) +{ + return (platformGetSysTick() + time); +} + +/*******************************************************************************/ +bool timerIsExpired( uint32_t timer ) +{ + uint32_t uDiff; + int32_t sDiff; + + uDiff = (timer - platformGetSysTick()); /* Calculate the diff between the timers */ + sDiff = uDiff; /* Convert the diff to a signed var */ + /* Having done this has two side effects: + * 1) all differences smaller than -(2^31) ms (~25d) will become positive + * Signaling not expired: acceptable! + * 2) Time roll-over case will be handled correctly: super! + */ + + /* 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 = platformGetSysTick(); +} + +/*******************************************************************************/ +uint32_t timerStopwatchMeasure( void ) +{ + return (uint32_t)(platformGetSysTick() - timerStopwatchTick); +} diff --git a/src/hydranfc_v2/hal/src/usb_device.c b/src/hydranfc_v2/hal/src/usb_device.c new file mode 100644 index 0000000..77b9ed6 --- /dev/null +++ b/src/hydranfc_v2/hal/src/usb_device.c @@ -0,0 +1,135 @@ +/** + ****************************************************************************** + * @file : USB_DEVICE + * @version : v2.0_Cube + * @brief : This file implements the USB Device + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution 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 other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS 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. + * + ****************************************************************************** +*/ + +/* Includes ------------------------------------------------------------------*/ + +#include "usb_device.h" +#include "usbd_core.h" +#include "usbd_desc.h" +#include "usbd_customhid.h" +#include "usbd_custom_hid_if.h" + +/* Return USBD_OK if the Battery Charging Detection mode (BCD) is used, else USBD_FAIL */ +extern USBD_StatusTypeDef USBD_LL_BatteryCharging(USBD_HandleTypeDef *pdev); +/* USB Device Core handle declaration */ +USBD_HandleTypeDef hUsbDeviceFS; + +/* init function */ +void MX_USB_DEVICE_Init(void) +{ + /* USER CODE BEGIN USB_DEVICE_Init_PreTreatment */ + + /* USER CODE END USB_DEVICE_Init_PreTreatment */ + + /* Init Device Library,Add Supported Class and Start the library*/ + USBD_Init(&hUsbDeviceFS, &FS_Desc, DEVICE_FS); + USBD_RegisterClass(&hUsbDeviceFS, &USBD_CUSTOM_HID); + USBD_CUSTOM_HID_RegisterInterface(&hUsbDeviceFS, &USBD_CustomHID_fops_FS); + /* Verify if the Battery Charging Detection mode (BCD) is used : */ + /* If yes, the USB device is started in the HAL_PCDEx_BCD_Callback */ + /* upon reception of PCD_BCD_DISCOVERY_COMPLETED message. */ + /* If no, the USB device is started now. */ + if (USBD_LL_BatteryCharging(&hUsbDeviceFS) != USBD_OK) { + USBD_Start(&hUsbDeviceFS); + } /* USER CODE BEGIN USB_DEVICE_Init_PostTreatment */ + + /* USER CODE END USB_DEVICE_Init_PostTreatment */ + +} + +/** + * @brief HAL_PCDEx_BCD_Callback : Send BCD message to user layer + * @param hpcd: PCD handle + * @param msg: LPM message + * @retval HAL status + */ +void HAL_PCDEx_BCD_Callback(PCD_HandleTypeDef *hpcd, PCD_BCD_MsgTypeDef msg) +{ + USBD_HandleTypeDef usbdHandle = hUsbDeviceFS; + /* USER CODE BEGIN 7 */ + if (hpcd->battery_charging_active == ENABLE) + { + switch(msg) + { + case PCD_BCD_CONTACT_DETECTION: + + break; + + case PCD_BCD_STD_DOWNSTREAM_PORT: + + break; + + case PCD_BCD_CHARGING_DOWNSTREAM_PORT: + + break; + + case PCD_BCD_DEDICATED_CHARGING_PORT: + + break; + + case PCD_BCD_DISCOVERY_COMPLETED: + USBD_Start(&usbdHandle); + break; + + case PCD_BCD_ERROR: + default: + break; + } + } + /* USER CODE END 7 */ +} +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/usb_hid_stream_driver.c b/src/hydranfc_v2/hal/src/usb_hid_stream_driver.c new file mode 100644 index 0000000..5d00b0b --- /dev/null +++ b/src/hydranfc_v2/hal/src/usb_hid_stream_driver.c @@ -0,0 +1,237 @@ +/****************************************************************************** + * @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: + * $Revision: $ + * LANGUAGE: ANSI C + */ + +/*! \file + * + * \author Wolfgang Reichart + * M. Arpa + * + * \brief USB HID streaming driver implementation. + * + */ + +/* + ****************************************************************************** + * INCLUDES + ****************************************************************************** + */ +#include +#include +#include +#include +#include "st_stream.h" +#include "st_errno.h" +#include "stream_driver.h" +#include "stream_dispatcher.h" +#include "usb_hid_stream_driver.h" +#include "logger.h" +#include "usbd_custom_hid_if.h" + +/* + ****************************************************************************** + * LOCAL VARIABLES + ****************************************************************************** + */ +static uint8_t initalized = false; +static uint8_t usbRxBuffer[USB_HID_REPORT_SIZE]; +static uint8_t usbTxBuffer[USB_HID_REPORT_SIZE]; + +static uint8_t * rxBuffer; /* INFO: buffer location is set in StreamInitialize */ +static uint8_t * txBuffer; /* INFO: buffer location is set in StreamInitialize */ + +static uint8_t txTid; +static uint8_t rxTid; +static uint16_t rxSize; +static uint8_t * rxEnd; /* pointer to next position where to copy the received data */ + + +#define ioLedOn() ; +#define ioLedOff() ; + + +/* + ****************************************************************************** + * GLOBAL FUNCTIONS + ****************************************************************************** + */ + +void usbStreamInitialize (uint8_t * rxBuf, uint8_t * txBuf) +{ + + /* setup pointers to buffers */ + rxBuffer = rxBuf; + txBuffer = txBuf; + /* so far we have received nothing */ + txTid = 0; + rxTid = 0; + rxSize = 0; + rxEnd = rxBuffer; + initalized = true; +} + +void usbStreamConnect (void) +{ + /* dummy implementation */ +} + +void usbStreamDisconnect (void) +{ + /* dummy implementation */ +} + +uint8_t usbStreamReady (void) +{ + return initalized; +} + +void usbStreamPacketProcessed ( uint16_t rxed ) +{ + /* + * FIXME: knowing that a memmove() is not the most performant variant, + * it is used here to keep the code simpler. + * If we run into performance issues on the PIC, this can be replaced + * by pointer operations. + */ + rxed += ST_STREAM_HEADER_SIZE; + /* decrease remaining data length by length of consumed packet */ + rxSize -= rxed; + + memmove( rxBuffer, rxBuffer + rxed, rxSize ); + /* correct end pointer to the new end of the buffer */ + rxEnd = rxBuffer + rxSize; +} + +int8_t usbStreamHasAnotherPacket ( ) +{ + return ( rxSize >= ST_STREAM_HEADER_SIZE + && rxSize >= ( ST_STREAM_DR_GET_RX_LENGTH( rxBuffer ) + ST_STREAM_HEADER_SIZE ) + ); +} + +uint16_t usbStreamOldFormatRequest ( ) +{ + uint8_t protocol = usbRxBuffer[ 2 ]; + uint8_t toTx = usbRxBuffer[ 3 ]; + + ioLedOn(); + + /* send back the special answer */ + if ( toTx > 0 || ( protocol & 0x40 ) ) { /* response was required */ + + /* wait here (and before copying the IN-buffer) until the USBInHandle is free again */ + + + usbTxBuffer[ 0 ] = ST_STREAM_COMPATIBILITY_TID; + usbTxBuffer[ 1 ] = 0x03; /* payload */ + usbTxBuffer[ 2 ] = protocol; + usbTxBuffer[ 3 ] = 0xFF; /* status = failed -> wrong protocol version */ + usbTxBuffer[ 4 ] = 0x00; /* no data will be sent back */ + + /* initiate transfer now */ + UsbTransmit(usbTxBuffer, USB_HID_REPORT_SIZE); + } + + return 0; +} + +uint16_t usbStreamReceive ( ) +{ + uint16_t rxLen = 0; + if( USBD_OK == UsbReceive(usbRxBuffer, &rxLen) ) { + + /* + * Read the usb hid buffer into the local buffer. + * When the RX-Length within the first streaming packet is + * longer than the HID payload, we have to concatenate several + * packets (up to max. 256 u8s) + */ + + uint16_t packetSize; + uint8_t payload = USB_HID_PAYLOAD_SIZE( usbRxBuffer ); + + if ( USB_HID_STATUS( usbRxBuffer ) != 0 ) { + /* this is a request in the old format */ + /* in the old format at this position we had the protocol id - which was never 0 + in the new format here this uint8_t is resered and 0 when sent from host to device */ + return usbStreamOldFormatRequest( ); + } + + ioLedOn(); + + rxTid = USB_HID_TID( usbRxBuffer ); + /* adjust number of totally received u8s */ + rxSize += payload; + + /* add the new data at the end of the data in the rxBuffer (i.e. where rxEnd points to) */ + memcpy( rxEnd, USB_HID_PAYLOAD( usbRxBuffer ), payload ); + rxEnd += payload; + packetSize = ST_STREAM_DR_GET_RX_LENGTH( rxBuffer ) + ST_STREAM_HEADER_SIZE; + + ioLedOff(); + + if ( packetSize > rxSize ) { + /* indicate that we must continue receiving */ + return 0; + } + rxEnd = rxBuffer; /* next time we receive new data, we start over at buffer start */ + return rxSize; + } + /* indicate that we did not receive anything - try next time again */ + return 0; +} + +void usbStreamTransmit ( uint16_t totalTxSize ) +{ + uint16_t offset = 0; + + while ( totalTxSize > 0 ) { + uint8_t payload = ( totalTxSize > USB_HID_MAX_PAYLOAD_SIZE ? USB_HID_MAX_PAYLOAD_SIZE : totalTxSize ); + ioLedOn( ); + + /* wait here (and before copying the IN-buffer) until the USBInHandle is free again */ + while ( !UsbTransmitReady() ) + ; + + /* generate a new tid for tx */ + USB_HID_GENERATE_TID_FOR_TX( rxTid, txTid ); + + /* TX-packet setup */ + USB_HID_TID( usbTxBuffer ) = txTid; + USB_HID_PAYLOAD_SIZE( usbTxBuffer ) = payload; + USB_HID_STATUS( usbTxBuffer ) = StreamDispatcherGetLastError(); + + /* copy data to usb buffer */ + memcpy( USB_HID_PAYLOAD( usbTxBuffer ), txBuffer + offset, payload ); + + totalTxSize -= payload; + offset += payload; + + /* initiate transfer now */ + UsbTransmit(usbTxBuffer, USB_HID_REPORT_SIZE); + + ioLedOff( ); + } +} diff --git a/src/hydranfc_v2/hal/src/usbd_conf.c b/src/hydranfc_v2/hal/src/usbd_conf.c new file mode 100644 index 0000000..383bfd0 --- /dev/null +++ b/src/hydranfc_v2/hal/src/usbd_conf.c @@ -0,0 +1,895 @@ +/** + ****************************************************************************** + * @file : usbd_conf.c + * @brief : This file implements the board support package for the USB device library + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution 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 other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS 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. + * + ****************************************************************************** +*/ +/* Includes ------------------------------------------------------------------*/ +#include "stm32.h" +#include "usbd_def.h" +#include "usbd_core.h" +#include "usbd_customhid.h" +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +PCD_HandleTypeDef hpcd_USB_OTG_FS; +void _Error_Handler(char * file, int line); + +/* USER CODE BEGIN 0 */ +/* USER CODE END 0 */ +/* Exported function prototypes -----------------------------------------------*/ +extern USBD_StatusTypeDef USBD_LL_BatteryCharging(USBD_HandleTypeDef *pdev); +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* USER CODE BEGIN 1 */ +static void SystemClockConfig_Resume(void); +/* USER CODE END 1 */ +void HAL_PCDEx_SetConnectionState(PCD_HandleTypeDef *hpcd, uint8_t state); +extern void SystemClock_Config(void); + +/******************************************************************************* + LL Driver Callbacks (PCD -> USB Device Library) +*******************************************************************************/ +/* MSP Init */ + +void HAL_PCD_MspInit(PCD_HandleTypeDef* pcdHandle) +{ + GPIO_InitTypeDef GPIO_InitStruct; + if(pcdHandle->Instance==USB_OTG_FS) + { + /* USER CODE BEGIN USB_OTG_FS_MspInit 0 */ + + /* USER CODE END USB_OTG_FS_MspInit 0 */ + + /**USB_OTG_FS GPIO Configuration + PA11 ------> USB_OTG_FS_DM + PA12 ------> USB_OTG_FS_DP + */ + GPIO_InitStruct.Pin = GPIO_PIN_11|GPIO_PIN_12; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* Peripheral clock enable */ + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + /* Enable VDDUSB */ + if(__HAL_RCC_PWR_IS_CLK_DISABLED()) + { + __HAL_RCC_PWR_CLK_ENABLE(); + HAL_PWREx_EnableVddUSB(); + __HAL_RCC_PWR_CLK_DISABLE(); + } + else + { + HAL_PWREx_EnableVddUSB(); + } + + /* Peripheral interrupt init */ + HAL_NVIC_SetPriority(OTG_FS_IRQn, 0, 0); + HAL_NVIC_EnableIRQ(OTG_FS_IRQn); + /* USER CODE BEGIN USB_OTG_FS_MspInit 1 */ + + /* USER CODE END USB_OTG_FS_MspInit 1 */ + } +} + +void HAL_PCD_MspDeInit(PCD_HandleTypeDef* pcdHandle) +{ + if(pcdHandle->Instance==USB_OTG_FS) + { + /* USER CODE BEGIN USB_OTG_FS_MspDeInit 0 */ + + /* USER CODE END USB_OTG_FS_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_USB_OTG_FS_CLK_DISABLE(); + + /**USB_OTG_FS GPIO Configuration + PA11 ------> USB_OTG_FS_DM + PA12 ------> USB_OTG_FS_DP + */ + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_11|GPIO_PIN_12); + + /* Disable VDDUSB */ + if(__HAL_RCC_PWR_IS_CLK_DISABLED()) + { + __HAL_RCC_PWR_CLK_ENABLE(); + HAL_PWREx_DisableVddUSB(); + __HAL_RCC_PWR_CLK_DISABLE(); + } + else + { + HAL_PWREx_DisableVddUSB(); + } + + /* Peripheral interrupt Deinit*/ + HAL_NVIC_DisableIRQ(OTG_FS_IRQn); + + /* USER CODE BEGIN USB_OTG_FS_MspDeInit 1 */ + + /* USER CODE END USB_OTG_FS_MspDeInit 1 */ + } +} + +/** + * @brief Setup Stage callback + * @param hpcd: PCD handle + * @retval None + */ +void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) +{ + USBD_LL_SetupStage((USBD_HandleTypeDef*)hpcd->pData, (uint8_t *)hpcd->Setup); +} + +/** + * @brief Data Out Stage callback. + * @param hpcd: PCD handle + * @param epnum: Endpoint Number + * @retval None + */ +void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + USBD_LL_DataOutStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->OUT_ep[epnum].xfer_buff); +} + +/** + * @brief Data In Stage callback.. + * @param hpcd: PCD handle + * @param epnum: Endpoint Number + * @retval None + */ +void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + USBD_LL_DataInStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->IN_ep[epnum].xfer_buff); +} + +/** + * @brief SOF callback. + * @param hpcd: PCD handle + * @retval None + */ +void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) +{ + USBD_LL_SOF((USBD_HandleTypeDef*)hpcd->pData); +} + +/** + * @brief Reset callback. + * @param hpcd: PCD handle + * @retval None + */ +void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) +{ + USBD_SpeedTypeDef speed = USBD_SPEED_FULL; + + /*Set USB Current Speed*/ + switch (hpcd->Init.speed) + { + case PCD_SPEED_FULL: + speed = USBD_SPEED_FULL; + break; + + default: + speed = USBD_SPEED_FULL; + break; + } + USBD_LL_SetSpeed((USBD_HandleTypeDef*)hpcd->pData, speed); + + /*Reset Device*/ + USBD_LL_Reset((USBD_HandleTypeDef*)hpcd->pData); +} + +/** + * @brief Suspend callback. + * When Low power mode is enabled the debug cannot be used (IAR, Keil doesn't support it) + * @param hpcd: PCD handle + * @retval None + */ +void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) +{ + __HAL_PCD_GATE_PHYCLOCK(hpcd); + /* Inform USB library that core enters in suspend Mode */ + USBD_LL_Suspend((USBD_HandleTypeDef*)hpcd->pData); + /*Enter in STOP mode */ + /* USER CODE BEGIN 2 */ + if (hpcd->Init.low_power_enable) + { + /* Set SLEEPDEEP bit and SleepOnExit of Cortex System Control Register */ + SCB->SCR |= (uint32_t)((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); + } + /* USER CODE END 2 */ +} + +/** + * @brief Resume callback. + * When Low power mode is enabled the debug cannot be used (IAR, Keil doesn't support it) + * @param hpcd: PCD handle + * @retval None + */ +void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) +{ + __HAL_PCD_UNGATE_PHYCLOCK(hpcd); + /* USER CODE BEGIN 3 */ + if (hpcd->Init.low_power_enable) + { + /* Reset SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR &= (uint32_t)~((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); + SystemClockConfig_Resume(); + } + /* USER CODE END 3 */ + USBD_LL_Resume((USBD_HandleTypeDef*)hpcd->pData); + +} + +/** + * @brief ISOOUTIncomplete callback. + * @param hpcd: PCD handle + * @param epnum: Endpoint Number + * @retval None + */ +void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + USBD_LL_IsoOUTIncomplete((USBD_HandleTypeDef*)hpcd->pData, epnum); +} + +/** + * @brief ISOINIncomplete callback. + * @param hpcd: PCD handle + * @param epnum: Endpoint Number + * @retval None + */ +void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + USBD_LL_IsoINIncomplete((USBD_HandleTypeDef*)hpcd->pData, epnum); +} + +/** + * @brief ConnectCallback callback. + * @param hpcd: PCD handle + * @retval None + */ +void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) +{ + USBD_LL_DevConnected((USBD_HandleTypeDef*)hpcd->pData); +} + +/** + * @brief Disconnect callback. + * @param hpcd: PCD handle + * @retval None + */ +void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) +{ + USBD_LL_DevDisconnected((USBD_HandleTypeDef*)hpcd->pData); +} + +/******************************************************************************* + LL Driver Interface (USB Device Library --> PCD) +*******************************************************************************/ +/** + * @brief Initializes the Low Level portion of the Device driver. + * @param pdev: Device handle + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_Init (USBD_HandleTypeDef *pdev) +{ + /* Init USB_IP */ + if (pdev->id == DEVICE_FS) { + /* enable USB power on Pwrctrl CR2 register */ + /* Link The driver to the stack */ + hpcd_USB_OTG_FS.pData = pdev; + pdev->pData = &hpcd_USB_OTG_FS; + + hpcd_USB_OTG_FS.Instance = USB_OTG_FS; + hpcd_USB_OTG_FS.Init.dev_endpoints = 6; + hpcd_USB_OTG_FS.Init.speed = PCD_SPEED_FULL; + hpcd_USB_OTG_FS.Init.ep0_mps = DEP0CTL_MPS_64; + hpcd_USB_OTG_FS.Init.phy_itface = PCD_PHY_EMBEDDED; + hpcd_USB_OTG_FS.Init.Sof_enable = DISABLE; + hpcd_USB_OTG_FS.Init.low_power_enable = DISABLE; + hpcd_USB_OTG_FS.Init.lpm_enable = DISABLE; + hpcd_USB_OTG_FS.Init.battery_charging_enable = DISABLE; + hpcd_USB_OTG_FS.Init.use_dedicated_ep1 = DISABLE; + hpcd_USB_OTG_FS.Init.vbus_sensing_enable = DISABLE; + if (HAL_PCD_Init(&hpcd_USB_OTG_FS) != HAL_OK) + { + _Error_Handler(__FILE__, __LINE__); + } + + HAL_PCDEx_SetRxFiFo(&hpcd_USB_OTG_FS, 0x80); + HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 0, 0x40); + HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 1, 0x80); + } + return USBD_OK; +} + +/** + * @brief De-Initializes the Low Level portion of the Device driver. + * @param pdev: Device handle + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_DeInit (USBD_HandleTypeDef *pdev) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_DeInit(pdev->pData); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Starts the Low Level portion of the Device driver. + * @param pdev: Device handle + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_Start(pdev->pData); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Stops the Low Level portion of the Device driver. + * @param pdev: Device handle + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_Stop (USBD_HandleTypeDef *pdev) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_Stop(pdev->pData); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Opens an endpoint of the Low Level Driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @param ep_type: Endpoint Type + * @param ep_mps: Endpoint Max Packet Size + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_OpenEP (USBD_HandleTypeDef *pdev, + uint8_t ep_addr, + uint8_t ep_type, + uint16_t ep_mps) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Open(pdev->pData, + ep_addr, + ep_mps, + ep_type); + + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Closes an endpoint of the Low Level Driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_CloseEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Close(pdev->pData, ep_addr); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Flushes an endpoint of the Low Level Driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_FlushEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Flush(pdev->pData, ep_addr); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Sets a Stall condition on an endpoint of the Low Level Driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_StallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_SetStall(pdev->pData, ep_addr); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Clears a Stall condition on an endpoint of the Low Level Driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_ClearStallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_ClrStall(pdev->pData, ep_addr); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Returns Stall condition. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @retval Stall (1: Yes, 0: No) + */ +uint8_t USBD_LL_IsStallEP (USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef*) pdev->pData; + + if((ep_addr & 0x80) == 0x80) + { + return hpcd->IN_ep[ep_addr & 0x7F].is_stall; + } + else + { + return hpcd->OUT_ep[ep_addr & 0x7F].is_stall; + } +} +/** + * @brief Assigns a USB address to the device. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_SetUSBAddress (USBD_HandleTypeDef *pdev, uint8_t dev_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_SetAddress(pdev->pData, dev_addr); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Transmits data over an endpoint. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @param pbuf: Pointer to data to be sent + * @param size: Data size + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_Transmit (USBD_HandleTypeDef *pdev, + uint8_t ep_addr, + uint8_t *pbuf, + uint16_t size) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Transmit(pdev->pData, ep_addr, pbuf, size); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Prepares an endpoint for reception. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @param pbuf: Pointer to data to be received + * @param size: Data size + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, + uint8_t ep_addr, + uint8_t *pbuf, + uint16_t size) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Receive(pdev->pData, ep_addr, pbuf, size); + + switch (hal_status) { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} + +/** + * @brief Returns the last transfered packet size. + * @param pdev: Device handle + * @param ep_addr: Endpoint Number + * @retval Recived Data Size + */ +uint32_t USBD_LL_GetRxDataSize (USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + return HAL_PCD_EP_GetRxCount((PCD_HandleTypeDef*) pdev->pData, ep_addr); +} +/** + * @brief GPIO EXTI Callback function + * Handle USB VBUS detection upon External interrupt + * @param GPIO_Pin + * @retval None + */ +void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) +{ + if (GPIO_Pin == GPIO_PIN_9) + { + HAL_PCDEx_BCD_VBUSDetect (&hpcd_USB_OTG_FS); + } +} + +#if (USBD_LPM_ENABLED == 1) +/** + * @brief HAL_PCDEx_LPM_Callback : Send LPM message to user layer + * @param hpcd: PCD handle + * @param msg: LPM message + * @retval HAL status + */ +void HAL_PCDEx_LPM_Callback(PCD_HandleTypeDef *hpcd, PCD_LPM_MsgTypeDef msg) +{ + switch ( msg) + { + case PCD_LPM_L0_ACTIVE: + if (hpcd->Init.low_power_enable) + { + SystemClock_Config(); + + /* Reset SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR &= (uint32_t)~((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); + } + __HAL_PCD_UNGATE_PHYCLOCK(hpcd); + USBD_LL_Resume(hpcd->pData); + break; + + case PCD_LPM_L1_ACTIVE: + __HAL_PCD_GATE_PHYCLOCK(hpcd); + USBD_LL_Suspend(hpcd->pData); + + /*Enter in STOP mode */ + if (hpcd->Init.low_power_enable) + { + /* Set SLEEPDEEP bit and SleepOnExit of Cortex System Control Register */ + SCB->SCR |= (uint32_t)((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); + } + break; + } +} +#endif +/** + * @brief Delays routine for the USB Device Library. + * @param Delay: Delay in ms + * @retval None + */ +void USBD_LL_Delay (uint32_t Delay) +{ + HAL_Delay(Delay); +} + +/** + * @brief static single allocation. + * @param size: size of allocated memory + * @retval None + */ +void *USBD_static_malloc(uint32_t size) +{ + static uint32_t mem[(sizeof(USBD_CUSTOM_HID_HandleTypeDef)/4+1)];/* On 32-bit boundary */ + return mem; +} + +/** + * @brief Dummy memory free + * @param *p pointer to allocated memory address + * @retval None + */ +void USBD_static_free(void *p) +{ + +} + +/* USER CODE BEGIN 5 */ +/** + * @brief Configures system clock after wake-up from USB Resume CallBack: + * enable HSI, PLL and select PLL as system clock source. + * @param None + * @retval None + */ +static void SystemClockConfig_Resume(void) +{ + SystemClock_Config(); +} +/* USER CODE END 5 */ + +/** +* @brief Software Device Connection +* @param hpcd: PCD handle +* @param state: connection state (0 : disconnected / 1: connected) +* @retval None +*/ +void HAL_PCDEx_SetConnectionState(PCD_HandleTypeDef *hpcd, uint8_t state) +{ +/* USER CODE BEGIN 6 */ + if (state == 1) + { + /* Configure Low Connection State */ + + } + else + { + /* Configure High Connection State */ + + } +/* USER CODE END 6 */ +} + +/** + * @brief Verify if the Battery Charging Detection mode (BCD) is used : + * return USBD_OK if true + * else return USBD_FAIL if false + * @param pdev: Device handle + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_BatteryCharging(USBD_HandleTypeDef *pdev) +{ + PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef*)pdev->pData; + if (hpcd->Init.battery_charging_enable == ENABLE) + { + return USBD_OK; + } + else + { + return USBD_FAIL; + } +} + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/usbd_custom_hid_if.c b/src/hydranfc_v2/hal/src/usbd_custom_hid_if.c new file mode 100644 index 0000000..16783f8 --- /dev/null +++ b/src/hydranfc_v2/hal/src/usbd_custom_hid_if.c @@ -0,0 +1,250 @@ +/** + ****************************************************************************** + * @file : usbd_custom_hid_if.c + * @brief : USB Device Custom HID interface file. + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution 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 other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS 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. + * + ****************************************************************************** +*/ + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_custom_hid_if.h" +/* USER CODE BEGIN INCLUDE */ +/* USER CODE END INCLUDE */ +/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USBD_CUSTOM_HID + * @brief usbd core module + * @{ + */ + +/** @defgroup USBD_CUSTOM_HID_Private_TypesDefinitions + * @{ + */ +/* USER CODE BEGIN PRIVATE_TYPES */ +static uint8_t *usbRx; +/* USER CODE END PRIVATE_TYPES */ +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_Private_Defines + * @{ + */ +/* USER CODE BEGIN PRIVATE_DEFINES */ +/* USER CODE END PRIVATE_DEFINES */ + +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_Private_Macros + * @{ + */ +/* USER CODE BEGIN PRIVATE_MACRO */ +/* USER CODE END PRIVATE_MACRO */ + +/** + * @} + */ + +/** @defgroup USBD_AUDIO_IF_Private_Variables + * @{ + */ +__ALIGN_BEGIN static uint8_t CUSTOM_HID_ReportDesc_FS[USBD_CUSTOM_HID_REPORT_DESC_SIZE] __ALIGN_END = +{ + /* USER CODE BEGIN 0 */ + 0x06, 0x00, 0xFF, /* USAGE_PAGE (Vendor Defined Page 1) */ + 0x09, 0x01, /* USAGE (Vendor Usage 1) */ + + 0xa1, 0x01, /* COLLECTION (Application) */ + 0x19, 0x01, /* USAGE_MINIMUM (0) */ + 0x29, 0x40, /* USAGE_MAXIMUM (64) */ + 0x15, 0x00, /* LOGICAL_MINIMUM (0) */ + 0x26, 0xFF, 0x00, /* LOGICAL_MAXIMUM (255) */ + 0x75, 0x08, /* REPORT_SIZE (8) */ + 0x95, 0x40, /* REPORT_COUNT (64) */ + 0x81, 0x00, /* */ + 0x19, 0x01, /* USAGE MINIMUM */ + 0x29, 0x40, /* USAGE_MAXIMUM */ + 0x91, 0x00, /* OUTPUT (Data,Var,Abs) (note: output from host) */ + /* USER CODE END 0 */ + 0xC0 /* END_COLLECTION */ + +}; + +/* USER CODE BEGIN PRIVATE_VARIABLES */ +/* USER CODE END PRIVATE_VARIABLES */ +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_IF_Exported_Variables + * @{ + */ + extern USBD_HandleTypeDef hUsbDeviceFS; +/* USER CODE BEGIN EXPORTED_VARIABLES */ +/* USER CODE END EXPORTED_VARIABLES */ + +/** + * @} + */ + +/** @defgroup USBD_CUSTOM_HID_Private_FunctionPrototypes + * @{ + */ +static int8_t CUSTOM_HID_Init_FS (void); +static int8_t CUSTOM_HID_DeInit_FS (void); +static int8_t CUSTOM_HID_OutEvent_FS (uint8_t event_idx, uint8_t state); + + +USBD_CUSTOM_HID_ItfTypeDef USBD_CustomHID_fops_FS = +{ + CUSTOM_HID_ReportDesc_FS, + CUSTOM_HID_Init_FS, + CUSTOM_HID_DeInit_FS, + CUSTOM_HID_OutEvent_FS, +}; + +/* Private functions ---------------------------------------------------------*/ +/** + * @brief CUSTOM_HID_Init_FS + * Initializes the CUSTOM HID media low layer + * @param None + * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL + */ +static int8_t CUSTOM_HID_Init_FS(void) +{ + /* USER CODE BEGIN 4 */ + return (0); + /* USER CODE END 4 */ +} + +/** + * @brief CUSTOM_HID_DeInit_FS + * DeInitializes the CUSTOM HID media low layer + * @param None + * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL + */ +static int8_t CUSTOM_HID_DeInit_FS(void) +{ + /* USER CODE BEGIN 5 */ + return (0); + /* USER CODE END 5 */ +} + +/** + * @brief CUSTOM_HID_OutEvent_FS + * Manage the CUSTOM HID class events + * @param event_idx: event index + * @param state: event state + * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL + */ +static int8_t CUSTOM_HID_OutEvent_FS (uint8_t event_idx, uint8_t state) +{ + /* USER CODE BEGIN 6 */ + /* store received data into our FIFO */ + USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef*)hUsbDeviceFS.pClassData; + usbRx = hhid->Report_buf; + return (0); + /* USER CODE END 6 */ +} + +/* USER CODE BEGIN 7 */ +/** + * @brief USBD_CUSTOM_HID_SendReport_FS + * Send the report to the Host + * @param report: the report to be sent + * @param len: the report length + * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL + */ +/* +static int8_t USBD_CUSTOM_HID_SendReport_FS ( uint8_t *report,uint16_t len) +{ + return USBD_CUSTOM_HID_SendReport(&hUsbDeviceFS, report, len); +} +*/ +/* USER CODE END 7 */ + +/* USER CODE BEGIN PRIVATE_FUNCTIONS_IMPLEMENTATION */ + +uint8_t UsbTransmitReady() +{ + USBD_CUSTOM_HID_HandleTypeDef *hhid = (USBD_CUSTOM_HID_HandleTypeDef*)hUsbDeviceFS.pClassData; + return (hhid->state == CUSTOM_HID_IDLE) ? 1 : 0; +} + +uint8_t UsbTransmit(uint8_t *data, uint16_t dataLen) +{ + return USBD_CUSTOM_HID_SendReport(&hUsbDeviceFS, data, dataLen); +} + +uint8_t UsbReceive(uint8_t *data, uint16_t *dataLen) +{ + uint8_t status = USBD_FAIL; + *dataLen = 0; + + if (NULL == usbRx) return USBD_FAIL; + + for(uint8_t i = 0; i < USBD_CUSTOMHID_OUTREPORT_BUF_SIZE; i++) + { + data[i] = usbRx[i]; + } + *dataLen = USBD_CUSTOMHID_OUTREPORT_BUF_SIZE; + USBD_CUSTOM_HID_ReceivePacket(&hUsbDeviceFS); + usbRx = NULL; + status = USBD_OK; + + return status; +} +/* USER CODE END PRIVATE_FUNCTIONS_IMPLEMENTATION */ + +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hal/src/usbd_desc.c b/src/hydranfc_v2/hal/src/usbd_desc.c new file mode 100644 index 0000000..a43148c --- /dev/null +++ b/src/hydranfc_v2/hal/src/usbd_desc.c @@ -0,0 +1,395 @@ +/** + ****************************************************************************** + * @file : usbd_desc.c + * @version : v2.0_Cube + * @brief : This file implements the USB Device descriptors + ****************************************************************************** + * This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * Copyright (c) 2018 STMicroelectronics International N.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted, provided that the following conditions are met: + * + * 1. Redistribution 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 other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS 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. + * + ****************************************************************************** +*/ + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_core.h" +#include "usbd_desc.h" +#include "usbd_conf.h" + +/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY + * @{ + */ + +/** @defgroup USBD_DESC + * @brief USBD descriptors module + * @{ + */ + +/** @defgroup USBD_DESC_Private_TypesDefinitions + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_Defines + * @{ + */ +#define USBD_VID 0x483 +#define USBD_LANGID_STRING 1033 +#define USBD_MANUFACTURER_STRING "STMicroelectronics" +#define USBD_PID_FS 0x3724 +#ifndef _NUCLEO_ +#define USBD_PRODUCT_STRING_FS "ST25R3916 DISCO-MB1396" +#else +#define USBD_PRODUCT_STRING_FS "ST25R3916 DISCO-Nucleo" +#endif +#define USBD_SERIALNUMBER_STRING_FS "00000000001A" +#define USBD_CONFIGURATION_STRING_FS "Custom HID Config" +#define USBD_INTERFACE_STRING_FS "Custom HID Interface" + +#define USB_SIZ_BOS_DESC 0x0C + +/* USER CODE BEGIN 0 */ +#define USB_SIZ_USR_DESC 0x08 + +#ifdef USB_SUPPORT_USER_STRING_DESC +/* USR descriptor */ +#if defined ( __ICCARM__ ) /*!< IAR Compiler */ +#pragma data_alignment=4 +#endif +__ALIGN_BEGIN uint8_t USBD_FS_USRStringDesc[USB_SIZ_USR_DESC] __ALIGN_END = { + 0x08, /* bLength */ + USB_DESC_TYPE_STRING, /* bDescriptorType */ + 'H',0, + 'I',0, + 'D',0, +}; + +/** + * @brief USBD_FS_USR_BOSDescriptor + * return the BOS descriptor + * @param speed : current device speed + * @param length : pointer to data length variable + * @retval pointer to descriptor buffer + */ +uint8_t *USBD_FS_USRStringDesc(USBD_SpeedTypeDef speed, uint8_t idx , uint16_t *length) +{ + *length = sizeof(USBD_FS_USRStringDesc); + return (uint8_t*)USBD_FS_USRStringDesc; +} +#endif /* USB_SUPPORT_USER_STRING_DESC */ + +/* USER CODE END 0*/ +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_Macros + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_Variables + * @{ + */ +uint8_t * USBD_FS_DeviceDescriptor( USBD_SpeedTypeDef speed , uint16_t *length); +uint8_t * USBD_FS_LangIDStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length); +uint8_t * USBD_FS_ManufacturerStrDescriptor ( USBD_SpeedTypeDef speed , uint16_t *length); +uint8_t * USBD_FS_ProductStrDescriptor ( USBD_SpeedTypeDef speed , uint16_t *length); +uint8_t * USBD_FS_SerialStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length); +uint8_t * USBD_FS_ConfigStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length); +uint8_t * USBD_FS_InterfaceStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length); + +#ifdef USB_SUPPORT_USER_STRING_DESC +uint8_t * USBD_FS_USRStringDesc (USBD_SpeedTypeDef speed, uint8_t idx , uint16_t *length); +#endif /* USB_SUPPORT_USER_STRING_DESC */ + +#if (USBD_LPM_ENABLED == 1) +uint8_t *USBD_FS_USR_BOSDescriptor(USBD_SpeedTypeDef speed , uint16_t *length); +#endif + +USBD_DescriptorsTypeDef FS_Desc = +{ + USBD_FS_DeviceDescriptor, + USBD_FS_LangIDStrDescriptor, + USBD_FS_ManufacturerStrDescriptor, + USBD_FS_ProductStrDescriptor, + USBD_FS_SerialStrDescriptor, + USBD_FS_ConfigStrDescriptor, + USBD_FS_InterfaceStrDescriptor, +#if (USBD_LPM_ENABLED == 1) + USBD_FS_USR_BOSDescriptor, +#endif +}; + +#if defined ( __ICCARM__ ) /*!< IAR Compiler */ + #pragma data_alignment=4 +#endif +/* USB Standard Device Descriptor */ +__ALIGN_BEGIN uint8_t USBD_FS_DeviceDesc[USB_LEN_DEV_DESC] __ALIGN_END = + { + 0x12, /*bLength */ + USB_DESC_TYPE_DEVICE, /*bDescriptorType*/ +#if (USBD_LPM_ENABLED == 1) + 0x01, /*bcdUSB */ /* changed to USB version 2.01 + in order to support LPM L1 suspend + resume test of USBCV3.0*/ +#else + 0x00, /* bcdUSB */ +#endif + 0x02, + 0x00, /*bDeviceClass*/ + 0x00, /*bDeviceSubClass*/ + 0x00, /*bDeviceProtocol*/ + USB_MAX_EP0_SIZE, /*bMaxPacketSize*/ + LOBYTE(USBD_VID), /*idVendor*/ + HIBYTE(USBD_VID), /*idVendor*/ + LOBYTE(USBD_PID_FS), /*idVendor*/ + HIBYTE(USBD_PID_FS), /*idVendor*/ + 0x00, /*bcdDevice rel. 2.00*/ + 0x02, + USBD_IDX_MFC_STR, /*Index of manufacturer string*/ + USBD_IDX_PRODUCT_STR, /*Index of product string*/ + USBD_IDX_SERIAL_STR, /*Index of serial number string*/ + USBD_MAX_NUM_CONFIGURATION /*bNumConfigurations*/ + } ; +/* USB_DeviceDescriptor */ +/* BOS descriptor */ +#if (USBD_LPM_ENABLED == 1) +#if defined ( __ICCARM__ ) /*!< IAR Compiler */ + #pragma data_alignment=4 +#endif +__ALIGN_BEGIN uint8_t USBD_FS_BOSDesc[USB_SIZ_BOS_DESC] __ALIGN_END = +{ + 0x5, + USB_DESC_TYPE_BOS, + 0xC, + 0x0, + 0x1, /* 1 device capability */ + /* device capability*/ + 0x7, + USB_DEVICE_CAPABITY_TYPE, + 0x2, + 0x2, /*LPM capability bit set */ + 0x0, + 0x0, + 0x0 +}; +#endif + +#if defined ( __ICCARM__ ) /*!< IAR Compiler */ + #pragma data_alignment=4 +#endif + +/* USB Standard Device Descriptor */ +__ALIGN_BEGIN uint8_t USBD_LangIDDesc[USB_LEN_LANGID_STR_DESC] __ALIGN_END = +{ + USB_LEN_LANGID_STR_DESC, + USB_DESC_TYPE_STRING, + LOBYTE(USBD_LANGID_STRING), + HIBYTE(USBD_LANGID_STRING), +}; + +#if defined ( __ICCARM__ ) /*!< IAR Compiler */ + #pragma data_alignment=4 +#endif +__ALIGN_BEGIN uint8_t USBD_StrDesc[USBD_MAX_STR_DESC_SIZ] __ALIGN_END; +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_FunctionPrototypes + * @{ + */ +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_Functions + * @{ + */ + +/** +* @brief USBD_FS_DeviceDescriptor +* return the device descriptor +* @param speed : current device speed +* @param length : pointer to data length variable +* @retval pointer to descriptor buffer +*/ +uint8_t * USBD_FS_DeviceDescriptor( USBD_SpeedTypeDef speed , uint16_t *length) +{ + *length = sizeof(USBD_FS_DeviceDesc); + return USBD_FS_DeviceDesc; +} + +/** +* @brief USBD_FS_LangIDStrDescriptor +* return the LangID string descriptor +* @param speed : current device speed +* @param length : pointer to data length variable +* @retval pointer to descriptor buffer +*/ +uint8_t * USBD_FS_LangIDStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length) +{ + *length = sizeof(USBD_LangIDDesc); + return USBD_LangIDDesc; +} + +/** +* @brief USBD_FS_ProductStrDescriptor +* return the product string descriptor +* @param speed : current device speed +* @param length : pointer to data length variable +* @retval pointer to descriptor buffer +*/ +uint8_t * USBD_FS_ProductStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length) +{ + if(speed == 0) + { + USBD_GetString (USBD_PRODUCT_STRING_FS, USBD_StrDesc, length); + } + else + { + USBD_GetString (USBD_PRODUCT_STRING_FS, USBD_StrDesc, length); + } + return USBD_StrDesc; +} + +/** +* @brief USBD_FS_ManufacturerStrDescriptor +* return the manufacturer string descriptor +* @param speed : current device speed +* @param length : pointer to data length variable +* @retval pointer to descriptor buffer +*/ +uint8_t * USBD_FS_ManufacturerStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length) +{ + USBD_GetString (USBD_MANUFACTURER_STRING, USBD_StrDesc, length); + return USBD_StrDesc; +} + +/** +* @brief USBD_FS_SerialStrDescriptor +* return the serial number string descriptor +* @param speed : current device speed +* @param length : pointer to data length variable +* @retval pointer to descriptor buffer +*/ +uint8_t * USBD_FS_SerialStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length) +{ + if(speed == USBD_SPEED_HIGH) + { + USBD_GetString (USBD_SERIALNUMBER_STRING_FS, USBD_StrDesc, length); + } + else + { + USBD_GetString (USBD_SERIALNUMBER_STRING_FS, USBD_StrDesc, length); + } + return USBD_StrDesc; +} + +/** +* @brief USBD_FS_ConfigStrDescriptor +* return the configuration string descriptor +* @param speed : current device speed +* @param length : pointer to data length variable +* @retval pointer to descriptor buffer +*/ +uint8_t * USBD_FS_ConfigStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length) +{ + if(speed == USBD_SPEED_HIGH) + { + USBD_GetString (USBD_CONFIGURATION_STRING_FS, USBD_StrDesc, length); + } + else + { + USBD_GetString (USBD_CONFIGURATION_STRING_FS, USBD_StrDesc, length); + } + return USBD_StrDesc; +} + +/** +* @brief USBD_HS_InterfaceStrDescriptor +* return the interface string descriptor +* @param speed : current device speed +* @param length : pointer to data length variable +* @retval pointer to descriptor buffer +*/ +uint8_t * USBD_FS_InterfaceStrDescriptor( USBD_SpeedTypeDef speed , uint16_t *length) +{ + if(speed == 0) + { + USBD_GetString (USBD_INTERFACE_STRING_FS, USBD_StrDesc, length); + } + else + { + USBD_GetString (USBD_INTERFACE_STRING_FS, USBD_StrDesc, length); + } + return USBD_StrDesc; +} +#if (USBD_LPM_ENABLED == 1) +/** + * @brief USBD_FS_USR_BOSDescriptor + * return the BOS descriptor + * @param speed : current device speed + * @param length : pointer to data length variable + * @retval pointer to descriptor buffer + */ +uint8_t *USBD_FS_USR_BOSDescriptor(USBD_SpeedTypeDef speed , uint16_t *length) +{ + *length = sizeof(USBD_FS_BOSDesc); + return (uint8_t*)USBD_FS_BOSDesc; +} +#endif +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/hydranfc_rfal_poller.c b/src/hydranfc_v2/hydranfc_rfal_poller.c new file mode 100644 index 0000000..1af62c5 --- /dev/null +++ b/src/hydranfc_v2/hydranfc_rfal_poller.c @@ -0,0 +1,1526 @@ +/* + * HydraBus/HydraNFC v2 + * + * Copyright (C) 2020 Benjamin VERNOUX + * + * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Generic includes +#include /* sprintf */ +#include +#include +#include +#include + +// reader includes +#include "st_errno.h" +#include "platform.h" +#include "st25r.h" +/* +#include "rfal_nfca.h" +#include "rfal_nfcb.h" +#include "rfal_nfcf.h" +#include "rfal_nfcv.h" +#include "rfal_st25tb.h" +#include "rfal_isoDep.h" +#include "rfal_nfcDep.h" +*/ +#include "rfal_analogConfig.h" +#include "lib_wrapper.h" + + +#include "utils.h" +#include "st25r3916.h" +#include "rfal_dpo.h" + +#include "bsp_uart.h" +#include "common.h" +/* +// tag content +#include "lib_NDEF.h" +#include "lib_NDEF_URI.h" + +#include "st25r.h" +#include "TruST25.h" +#include "ndef_display.h" +*/ + +#define FREEZE_DISPLAY 1 +/* +****************************************************************************** +* GLOBAL DEFINES +****************************************************************************** +*/ +#define RFAL_POLLER_DEVICES 4 /* Number of devices supported */ + +#define RFAL_POLLER_FOUND_NONE 0x00 /* No device found Flag */ +#define RFAL_POLLER_FOUND_A 0x01 /* NFC-A device found Flag */ +#define RFAL_POLLER_FOUND_B 0x02 /* NFC-B device found Flag */ +#define RFAL_POLLER_FOUND_F 0x04 /* NFC-F device found Flag */ +#define RFAL_POLLER_FOUND_V 0x08 /* NFC-V device Flag */ +#define RFAL_POLLER_FOUND_ST25TB 0x10 /* ST25TB device found flag */ + +/* +****************************************************************************** +* GLOBAL TYPES +****************************************************************************** +*/ + +/*! Main state */ +typedef enum{ + RFAL_POLLER_STATE_INIT = 0, /* Initialize state */ + RFAL_POLLER_STATE_TECHDETECT = 1, /* Technology Detection state */ + RFAL_POLLER_STATE_COLAVOIDANCE = 2, /* Collision Avoidance state */ + RFAL_POLLER_STATE_DEACTIVATION = 9 /* Deactivation state */ +}RfalPollerState; + +/*! Device interface */ +typedef enum{ + RFAL_POLLER_INTERFACE_RF = 0, /* RF Frame interface */ + RFAL_POLLER_INTERFACE_ISODEP = 1, /* ISO-DEP interface */ + RFAL_POLLER_INTERFACE_NFCDEP = 2 /* NFC-DEP interface */ +}RfalPollerRfInterfaceEnum_t; + +/*! Device struct containing all its details */ +typedef struct { + BSP_NFCTAG_Protocol_Id_t type; /* Device's type */ + union{ + 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; /* NFC-V Listen Device instance */ + }dev; /* Device's instance */ + union{ + rfalIsoDepDevice isoDep; /* ISO-DEP instance */ + rfalNfcDepDevice nfcDep; /* NFC-DEP instance */ + }proto; /* Device's protocol */ + uint8_t NdefSupport; + RfalPollerRfInterfaceEnum_t rfInterface; /* Device's interface */ +} RfalPollerRfInterfaceDevice_t; + +/** Detection mode for the demo */ +typedef enum { + DETECT_MODE_POLL = 0, /** Continuous polling for tags */ + DETECT_MODE_WAKEUP = 1, /** Waiting for the ST25R3916 wakeup detection */ + DETECT_MODE_AWAKEN = 2 /** Awaken by the ST25R3916 wakeup feature */ +} detectMode_t; + +/* + ****************************************************************************** + * LOCAL VARIABLES + ****************************************************************************** + */ +static uint8_t gDevCnt; /* Number of devices found */ +static RfalPollerRfInterfaceDevice_t gDevList[RFAL_POLLER_DEVICES]; /* Device List */ +static RfalPollerState gState; /* Main state */ +static uint8_t gTechsFound; /* Technologies found bitmask */ +RfalPollerRfInterfaceDevice_t *gActiveDev; /* Active device pointer */ + +static bool instructionsDisplayed = false; /* Keep track of demo instruction display */ +static detectMode_t detectMode = DETECT_MODE_POLL; /* Current tag detection method */ + +#if 0 +static rfalBitRate rxbr,txbr; /* Detected tag bitrate information */ +static const uint16_t yBox = 24; /* Detected tag box margin*/ +static const uint16_t boxHeight = 45; /* Detected tag box height */ +static const uint16_t boxSpace = 4; /* Detected tag box spacing */ +static uint16_t lineY[] = {75, 100, 116, 141, 157, 182, 192}; /* Tag information line position */ + +static char type1Str[] = "Type 1 Tag"; /* NFC Forum Tag Type1 string */ +static char type2Str[] = "Type 2 Tag"; /* NFC Forum Tag Type2 string */ +static char type3Str[] = "Type 3 Tag"; /* NFC Forum Tag Type3 string */ +static char type4aStr[] = "Type 4A Tag"; /* NFC Forum Tag Type4A string */ +static char type4bStr[] = "Type 4B Tag"; /* NFC Forum Tag Type4B string */ +static char type5Str[] = "Type 5 Tag"; /* NFC Forum Tag Type5string */ +static char iso15693Str[] = "Iso15693 Tag"; /* iso15693 Tag string */ +static char st25tbStr[] = "ST25TB Tag"; /* ST25TB tag string */ +static char iso14443aStr[] = "Iso14443A Tag"; /* Iso14443A tag string */ +static char felicaStr[] = "Felica Tag"; /* Felica tag string */ + +static const char *dpoProfile[] = {"Full power", "Med. power", "Low power "}; /* Dynamic Power Output profile strings*/ +static uint16_t lastRssi; /* RSSI history value */ +static uint16_t uidLine = 1; /* Line Id to display Tag UID */ +static uint16_t hbrLine = 3; /* Line Id to display High Bitrate info */ +static uint16_t rssiLine = 5; /* Line Id to display RSSI info */ +static uint16_t rssiBarLine = 6; /* Line Id to display RSSI info as a bar */ +static uint16_t xMargin = 15; /* Tag information margin */ +static uint32_t timeRssi = 0; /* Use to detect long latency in tag response */ +#endif + +/* +****************************************************************************** +* LOCAL FUNCTION PROTOTYPES +****************************************************************************** +*/ +static bool RfalPollerTechDetection(t_hydra_console *con); +static bool RfalPollerCollResolution(t_hydra_console *con); +static bool RfalPollerDeactivate( void ); +static void RfalPollerRun(t_hydra_console *con); + +/* +void cprintf(t_hydra_console *con, const char *fmt, ...) +{ + mode_config_proto_t* proto = &con->mode->proto; + va_list va_args; + int real_size; +#define cprintf_BUFF_SIZE (511) + char cprintf_buff[cprintf_BUFF_SIZE+1]; + + va_start(va_args, fmt); + real_size = vsnprintf(cprintf_buff, cprintf_BUFF_SIZE, fmt, va_args); + va_end(va_args); + + bsp_uart_write_u8(proto->dev_num, cprintf_buff, real_size); +} +*/ + +/* Compute detected tag Y position */ +#ifndef FREEZE_DISPLAY +static uint16_t getTagBoxY(int index) +{ + return yBox + index*(boxHeight + boxSpace); +} +#endif + +/* Display a detected tag on the LCD screen (max: 4 tags detected) */ +static void displayTag(int index, char* type, uint8_t *uid) +{ + int c; +#ifndef FREEZE_DISPLAY + const uint16_t xBox = 8; + const uint16_t boxWidth = 304; + const uint16_t boxCornerRadius = 10; + const uint16_t yText = 15; +#endif + + char str[30] = ""; + char uid_str[30] = ""; + if (index > 3) + return; + + if(uid != NULL) + { + strcat(str,type); + for(c = strlen(type); c < 7; c++) + strcat(str," "); + sprintf(uid_str,"%02X:%02X:%02X:%02X",uid[0],uid[1],uid[2],uid[3]); + strcat(str,uid_str); + } else { + strcpy(str, " "); + } + +#ifndef FREEZE_DISPLAY + BSP_LCD_DrawRectangleWithRoundCorner(xBox,getTagBoxY(index),boxWidth,boxHeight,boxCornerRadius); + Menu_DisplayStringAt(Menu_GetFontWidth(),yText + Menu_GetFontHeight() + index * (boxHeight + boxSpace), str); +#endif +} + +/* Control Radio Button display */ +static void setRadio(t_hydra_console *con) +{ + (void)(con); +#ifndef FREEZE_DISPLAY + if(detectMode == DETECT_MODE_POLL) + { + BSP_LCD_SetColors(LCD_COLOR_BLUE2,0xFFFF); + BSP_LCD_FillCircle(RADIO_X,RADIO_Y, 5); + BSP_LCD_SetColors(0xFFFF,0xFFFF); + BSP_LCD_FillCircle(RADIO_X,RADIO_Y+40, 5); + } else { + BSP_LCD_SetColors(LCD_COLOR_BLUE2,0xFFFF); + BSP_LCD_FillCircle(RADIO_X,RADIO_Y+40, 5); + BSP_LCD_SetColors(0xFFFF,0xFFFF); + BSP_LCD_FillCircle(RADIO_X,RADIO_Y, 5); + } +#else + /* + if(detectMode == DETECT_MODE_POLL) + { + cprintf(con, "detectMode=DETECT_MODE_POLL=%d\r\n", detectMode); + } else { + cprintf(con, "detectMode=%d\r\n", detectMode); + } + */ +#endif +} + +/* Control display when no tag is detected (instruction + radio button) */ +void tagDetectionNoTag(t_hydra_console *con) +{ +#ifndef FREEZE_DISPLAY + BSP_LCD_SetColors(0x0000,0xFFFF); + + BSP_LCD_FillCircle(RADIO_X,RADIO_Y, 10); + BSP_LCD_SetColors(0xFFFF,0x0000); + BSP_LCD_FillCircle(RADIO_X,RADIO_Y, 7); + + + BSP_LCD_SetColors(0x0000,0xFFFF); + BSP_LCD_FillCircle(RADIO_X,RADIO_Y+40, 10); + BSP_LCD_SetColors(0xFFFF,0x0000); + BSP_LCD_FillCircle(RADIO_X,RADIO_Y+40, 7); +#endif + setRadio(con); +#ifndef FREEZE_DISPLAY + Menu_SetStyle(PLAIN); + BSP_LCD_DisplayStringAt(RADIO_X + 20,RADIO_Y-10,(uint8_t*)"Continuous Poll",LEFT_MODE); + BSP_LCD_DisplayStringAt(RADIO_X + 20,RADIO_Y+30,(uint8_t*)"Wake-up",LEFT_MODE); + Menu_DisplayCenterString(6,"Place tags above"); + Menu_DisplayCenterString(7,"the antenna..."); +#endif + instructionsDisplayed = true; + cprintf(con, "Place tags above the antenna...(or press UBTN to exit)\r\n"); +} + +/* Helper method to retrieve UID from a tag structure */ +/* +static bool getDevUid(uint8_t** uid, uint8_t* uidLen) +{ + switch (gActiveDev->type) + { + case BSP_NFCTAG_NFCA: + *uid = gActiveDev->dev.nfca.nfcId1; + *uidLen = gActiveDev->dev.nfca.nfcId1Len; + break; + + case BSP_NFCTAG_NFCB: + *uid = gActiveDev->dev.nfcb.sensbRes.nfcid0; + *uidLen = RFAL_NFCB_NFCID0_LEN; + break; + + case BSP_NFCTAG_ST25TB: + *uid = gActiveDev->dev.st25tb.UID; + *uidLen = RFAL_ST25TB_UID_LEN; + break; + + case BSP_NFCTAG_NFCF: + *uid = gActiveDev->dev.nfcf.sensfRes.NFCID2; + *uidLen = RFAL_NFCF_NFCID2_LEN; + break; + + case BSP_NFCTAG_NFCV: + *uid = gActiveDev->dev.nfcv.InvRes.UID; + *uidLen = RFAL_NFCV_UID_LEN; + break; + + default: + return false; + } + return true; +} +*/ +#if 0 +/* Helper method to define tag information position */ +uint16_t yLine(uint8_t l) +{ + return lineY[l]; +} + +/* Helper method to get the tag type as a string */ +static char* getTypeStr(void) +{ + char* retPtr = NULL; + // only for Felica check + uint8_t buffer[16]; + switch(gActiveDev->type) + { + case BSP_NFCTAG_NFCA: + switch (gActiveDev->dev.nfca.type) + { + case RFAL_NFCA_T1T: + retPtr = type1Str; + break; + case RFAL_NFCA_T2T: + retPtr = type2Str; + break; + case RFAL_NFCA_T4T: + if(gActiveDev->NdefSupport) + retPtr = type4aStr; + else + retPtr = iso14443aStr; + case RFAL_NFCA_NFCDEP: + /* TODO RFAL_NFCA_NFCDEP */ + break; + case RFAL_NFCA_T4T_NFCDEP: + /* TODO RFAL_NFCA_T4T_NFCDEP */ + break; + } + break; + case BSP_NFCTAG_NFCB: + retPtr = type4bStr; + break; + case BSP_NFCTAG_ST25TB: + retPtr = st25tbStr; + break; + case BSP_NFCTAG_NFCF: + if(BSP_NFCTAG_ReadData(buffer,0,1) == ERR_NONE) + retPtr = type3Str; + else + retPtr = felicaStr; + break; + case BSP_NFCTAG_NFCV: + if((!gActiveDev->NdefSupport) || (BSP_NFCTAG_CheckVicinity())) + { + retPtr = iso15693Str; + } else { + retPtr = type5Str; + } + break; + } + return retPtr; +} + + +/* Helper method to get the current tag bitrate as numerical b/s */ +static uint16_t getSpeedVal(rfalBitRate br) +{ + if(br <= RFAL_BR_848) + return 106 * (int)pow(2,br); + else if (br == RFAL_BR_52p97 ) + return 52; + else if (br == RFAL_BR_26p48) + return 26; + else + return 00; +} + +/* Helper method to get the current tag bitrate as a string */ +static void getSpeedStr(char *retPtr) +{ + rfalGetBitRate(&txbr,&rxbr); + + sprintf(retPtr, "%d-%d kb/s", + getSpeedVal(rxbr), + getSpeedVal(txbr)); +} +#endif + +/* When a tag is slected, dispays the current DPO profile */ +#ifndef FREEZE_DISPLAY +static void displayDpo(rfalDpoEntry *currentDpo) +{ + const char *txt; + uint16_t rfoX = 170; + BSP_LCD_SetFont(&Font16); + uint16_t rfoWidth = 10*BSP_LCD_GetFont()->Width +20; + uint16_t rfoTxtX; + + if(currentDpo != NULL) + { + BSP_LCD_SetColors(BSP_LCD_FadeColor(LCD_COLOR_BLUEST,LCD_COLOR_LIGHTBLUE,4,currentDpo->rfoRes),LCD_COLOR_WHITE); + txt = dpoProfile[currentDpo->rfoRes]; + rfoTxtX = rfoX + (rfoWidth - strlen(txt)*BSP_LCD_GetFont()->Width) / 2; + + BSP_LCD_DrawRectangleWithRoundCorner(rfoX, + yLine(0)-4 - 5, + rfoWidth, + BSP_LCD_GetFont()->Height+14, + 10); + BSP_LCD_DisplayStringAt(rfoTxtX,yLine(0),(uint8_t*)txt,LEFT_MODE); + + BSP_LCD_SetFont(&Font22); + Menu_SetStyle(PLAIN); + } +} +#endif + +/* Callback function used to detect long latenncy in tag response, displays "Wait..." and avoid display freeze */ +#ifndef FREEZE_DISPLAY +static uint8_t waitRssi(void) +{ + static uint8_t checkTouch = 0; + Menu_Position_t touch; + + uint16_t rssiX = xMargin + 5 * BSP_LCD_GetFont()->Width; + uint32_t delay = ((int32_t) HAL_GetTick() - (int32_t)timeRssi); + if(delay > 1000) + { + BSP_LCD_DisplayStringAt(rssiX,yLine(rssiLine),(uint8_t*)"Wait... ",LEFT_MODE); + lastRssi = 0; + } + if(checkTouch++ > 50) + { + checkTouch = 0; + Menu_ReadPosition(&touch); + if((touch.Sel) && (touch.Y > 60) ) + // exit + return 0; + } + // continue + return 1; +} +#endif + +/* Tag information Tab initial callback function */ +#ifndef FREEZE_DISPLAY +static Menu_Callback_Status_t tabFirstTagReadInfo(void) +{ + char line[40] = ""; + + clearTab(); + uint8_t nbUidDigit = 8; + uint8_t *devUid; + + char speedStr[20]; + // re-init lastRssi at dummy value != 0 + lastRssi = 1; + BSP_NFCTAG_WaitingCb = &waitRssi; + + getDevUid(&devUid,&nbUidDigit); + for(int d = 0; d < nbUidDigit; d++) + { + if(gActiveDev-> type != BSP_NFCTAG_NFCV) + sprintf(line,"%s%02X:",line,devUid[d]); + else + // for type V invert UID + sprintf(line,"%s%02X:",line,devUid[nbUidDigit - d - 1]); + } + // remove last colon + line[strlen(line)-1] = '\0'; + + Menu_SetStyle(PLAIN); + BSP_LCD_SetFont(&Font16); + + BSP_LCD_DisplayStringAt(xMargin,yLine(0), (uint8_t*)getTypeStr(),LEFT_MODE); + + BSP_LCD_DisplayStringAt(xMargin,yLine(uidLine),(uint8_t*)"UID:",LEFT_MODE); + BSP_LCD_DisplayStringAt(xMargin + 1 * Menu_GetFontWidth(),yLine(uidLine+1),(uint8_t*)line,LEFT_MODE); + + + BSP_LCD_DisplayStringAt(xMargin,yLine(hbrLine),(uint8_t*)"Speed:",LEFT_MODE); + getSpeedStr(speedStr); + BSP_LCD_DisplayStringAt(xMargin + 1 * Menu_GetFontWidth(),yLine(hbrLine+1),(uint8_t*)speedStr,LEFT_MODE); + + + BSP_LCD_DisplayStringAt(xMargin,yLine(rssiLine),(uint8_t*)"RSSI:",LEFT_MODE); + +#ifdef ENABLE_TRUST25_SIGNATURE_VERIFICATION + uint16_t trust25Line = 3; + TruST25_Status_t TruST25_valid = TruST25_SignatureVerification(gActiveDev->type,gActiveDev->dev.nfca.type,devUid,nbUidDigit); + if(TruST25_valid == TRUST25_VALID) + { + BSP_LCD_SetBackColor(LCD_COLOR_WHITE); + BSP_LCD_SetTextColor(LCD_COLOR_DARKGREEN); + BSP_LCD_DisplayPicture(170,yLine(trust25Line),Success); + BSP_LCD_DisplayStringAt(205,yLine(trust25Line),(uint8_t*)"TruST25",LEFT_MODE); + BSP_LCD_DisplayStringAt(205,yLine(trust25Line)+16,(uint8_t*)"Validated",LEFT_MODE); + Menu_SetStyle(PLAIN); + } else if (TruST25_valid == TRUST25_INVALID) { + BSP_LCD_SetBackColor(LCD_COLOR_WHITE); + BSP_LCD_SetTextColor(LCD_COLOR_RED); + BSP_LCD_DisplayPicture(170+10,yLine(trust25Line),Error); + BSP_LCD_DisplayStringAt(205+10,yLine(trust25Line),(uint8_t*)"TruST25",LEFT_MODE); + BSP_LCD_DisplayStringAt(205+10,yLine(trust25Line)+16,(uint8_t*)"Error!",LEFT_MODE); + Menu_SetStyle(PLAIN); + } +#endif + + BSP_LCD_SetFont(&Font22); + + return MENU_CALLBACK_CONTINUE; +} +#endif + +/* Tag Information Tab callback: displays the RSSI & DPO profile */ +#ifndef FREEZE_DISPLAY +static Menu_Callback_Status_t tabTagReadInfo(void) +{ + uint8_t buffer[4]; + uint16_t rssi = 0; + uint16_t rssiLen = 0; + uint16_t front,back; + static uint16_t execCount = 0; + uint8_t status; + + + if(execCount++ > 100) + { + execCount = 0; + return MENU_CALLBACK_CONTINUE; + } + BSP_LCD_SetFont(&Font16); + uint16_t rssiX = xMargin + BSP_LCD_GetFont()->Width; + uint16_t rssi_max = 280 - 2*BSP_LCD_GetFont()->Width; + + + timeRssi = HAL_GetTick(); + status = BSP_NFCTAG_ReadData(buffer,0,1); + rfalGetTransceiveRSSI( &rssi ); + // with short frames, at High Bit Rate, rssi computation may not be relevant + if((status == NFCTAG_OK) && (rssi == 0)) + { + status = BSP_NFCTAG_ReadData(buffer,0,8); + rfalGetTransceiveRSSI( &rssi ); + } + if((status != NFCTAG_OK) && (status != NFCTAG_RESPONSE_ERROR)) + { + // try to re-activate + rfalFieldOff(); + HAL_Delay(5); + timeRssi = HAL_GetTick(); + BSP_NFCTAG_Activate((BSP_NFCTAG_Device_t *)gActiveDev); + rfalGetTransceiveRSSI( &rssi ); + } + + rssiLen = ceil ( (float)(rssi_max * rssi) / (float)0x550); + rssiLen = rssiLen > rssi_max ? rssi_max : rssiLen; + + // don't update rssi display if rssi has not been measured + if ((status == NFCTAG_OK) && (rssi == 0)) { + rssiLen = lastRssi; + } + + + Menu_SetStyle(PLAIN); + if((rssiLen == 0) && (lastRssi != 0)) + { + BSP_LCD_GetColors(&front,&back); + BSP_LCD_SetColors(back,front); + BSP_LCD_FillRect(rssiX + 6,yLine(rssiBarLine) + 6,rssi_max,2); + BSP_LCD_SetColors(front,back); + BSP_LCD_DisplayStringAt(rssiX+ 4 * BSP_LCD_GetFont()->Width,yLine(rssiLine),(uint8_t*)"Link lost",LEFT_MODE); + } else if (rssiLen != 0) { + if(lastRssi == 0) + BSP_LCD_DisplayStringAt(rssiX+ 4 * BSP_LCD_GetFont()->Width,yLine(rssiLine),(uint8_t*)" ",LEFT_MODE); + char rssiTxt[50]; + sprintf(rssiTxt," "); + BSP_LCD_DisplayStringAt(rssiX+ 4 * BSP_LCD_GetFont()->Width,yLine(rssiLine),(uint8_t*)rssiTxt,LEFT_MODE); + + BSP_LCD_GetColors(&front,&back); + BSP_LCD_SetColors(back,front); + BSP_LCD_FillRect(BSP_LCD_GetXSize()/2 - rssi_max/2,yLine(rssiBarLine) + 6,rssi_max/2 - lastRssi/2,2); + BSP_LCD_FillRect(BSP_LCD_GetXSize()/2 + lastRssi/2 + 6,yLine(rssiBarLine) + 6,rssi_max/2 - lastRssi/2,2); + BSP_LCD_SetColors(front,back); + BSP_LCD_FillRect(BSP_LCD_GetXSize()/2 - rssiLen/2,yLine(rssiBarLine) + 6, rssiLen,2); + } + + lastRssi = rssiLen; + + /* DPO */ + displayDpo(rfalDpoGetCurrentTableEntry()); + + BSP_LCD_SetFont(&Font22); + + return MENU_CALLBACK_CONTINUE; +} +#endif + +/* Tag content Tab initial callback: display NDEF tag content*/ +#ifndef FREEZE_DISPLAY +static Menu_Callback_Status_t tabFirstTagReadNdef(void) +{ + char txt[50] = {0}; + + uint8_t status; + uint16_t ndefLen = 0; + uint8_t* ndefBuffer = NULL; + clearTab(); + + Menu_SetStyle(PLAIN); + BSP_LCD_SetFont(&Font16); + + // disable NFCTAG loop callback + BSP_NFCTAG_WaitingCb = NULL; + + // reset start of NDEF buffer + NDEF_getNDEFSize(&ndefLen); + if(ndefLen > sizeof(NDEF_Buffer)) + { + ndefBuffer = (uint8_t *)malloc(ndefLen+2); + if(ndefBuffer == NULL) + { + sprintf(txt, "NDEF is too big!"); + BSP_LCD_DisplayStringAt(0,102,(uint8_t*)txt,CENTER_MODE); + status = NDEF_ERROR; + } + } else { + ndefBuffer = NDEF_Buffer; + } + memset(ndefBuffer,0,100); + status = NDEF_ReadNDEF(ndefBuffer); + if((status == NDEF_OK) && ndefLen) + { + if(displayNdef(ndefBuffer) != NDEF_OK) + { + sprintf(txt, "Cannot identify NDEF record"); + Menu_SetStyle(PLAIN); + BSP_LCD_SetFont(&Font16); + BSP_LCD_DisplayStringAt(0,70,(uint8_t*)txt,CENTER_MODE); + char data_str[30] = {0}; + status = BSP_NFCTAG_ReadData(ndefBuffer,0,16); + if(status == NFCTAG_OK) + { + for(int data_index = 0; data_index < 4 ; data_index++) + { + sprintf(data_str,"0x%02X, 0x%02X, 0x%02X, 0x%02X",ndefBuffer[data_index*4], + ndefBuffer[data_index*4+1], + ndefBuffer[data_index*4+2], + ndefBuffer[data_index*4+3]); + BSP_LCD_DisplayStringAt(0,86 + (data_index * 16),(uint8_t*)data_str,CENTER_MODE); + } + } else { + sprintf(txt, "Cannot read data"); + BSP_LCD_DisplayStringAt(0,102,(uint8_t*)txt,CENTER_MODE); + } + } + + } else { + if(status == NDEF_ERROR_MEMORY_INTERNAL) + { + sprintf(txt, "NDEF is too big"); + } else { + sprintf(txt, "Cannot read NDEF"); + } + + char data_str[30] = {0}; + status = BSP_NFCTAG_ReadData(NDEF_Buffer,0,16); + + Menu_SetStyle(PLAIN); + BSP_LCD_SetFont(&Font16); + BSP_LCD_DisplayStringAt(0,70,(uint8_t*)txt,CENTER_MODE); + + if(status == NFCTAG_OK) + { + for(int data_index = 0; data_index < 4 ; data_index++) + { + sprintf(data_str,"0x%02X, 0x%02X, 0x%02X, 0x%02X",NDEF_Buffer[data_index*4], + NDEF_Buffer[data_index*4+1], + NDEF_Buffer[data_index*4+2], + NDEF_Buffer[data_index*4+3]); + BSP_LCD_DisplayStringAt(0,86 + (data_index * 16),(uint8_t*)data_str,CENTER_MODE); + } + } else { + sprintf(txt, "Cannot read data"); + BSP_LCD_DisplayStringAt(0,102,(uint8_t*)txt,CENTER_MODE); + } + + BSP_LCD_SetFont(&Font22); + } + + // write ndef icon + if(gActiveDev->NdefSupport) + BSP_LCD_DisplayPicture(260,160, send_icon); + + if((ndefBuffer != NDEF_Buffer) && (ndefBuffer != NULL)) + { + free(ndefBuffer); + ndefBuffer = NULL; + } + return MENU_CALLBACK_CONTINUE; + +} +#endif + +/* Tag content Tab callback: manage NDEF message write */ +#ifndef FREEZE_DISPLAY +static Menu_Callback_Status_t tabTagReadNdef(void) +{ + Menu_Position_t touch; + + if(!gActiveDev->NdefSupport) + return MENU_CALLBACK_CONTINUE; + + if(Menu_ReadPosition(&touch)) + { + if((touch.X > 250) && (touch.Y > 150)) + { + uint16_t length = 0; + sURI_Info w_uri = {URI_ID_0x01_STRING, "st.com/st25r3916-demo" ,""}; + NDEF_PrepareURIMessage(&w_uri,NDEF_Buffer,&length); + if(NfcTag_WriteNDEF(length,NDEF_Buffer) == NFCTAG_OK) + { + clearTab(); + Menu_SetStyle(PLAIN); + BSP_LCD_SetFont(&Font16); + BSP_LCD_DisplayStringAt(0,120, (uint8_t*)"NDEF write success!", CENTER_MODE); + HAL_Delay(500); + tabFirstTagReadNdef(); + } else { + clearTab(); + Menu_SetStyle(PLAIN); + BSP_LCD_SetFont(&Font16); + BSP_LCD_DisplayStringAt(0,120, (uint8_t*)"NDEF write error!", CENTER_MODE); + HAL_Delay(500); + } + BSP_LCD_SetFont(&Font22); + } // else { + // return MENU_CALLBACK_CONTINUE; + //} + + } + return MENU_CALLBACK_CONTINUE; +} + +/* Helper function to setup BSP with correct NFC protocol */ +static void SelectNDEFProtocol(uint8_t devId) +{ + switch (gDevList[devId].type) + { + case BSP_NFCTAG_NFCA: + switch (gDevList[devId].dev.nfca.type) + { + case RFAL_NFCA_T1T: + NfcTag_SelectProtocol(NFCTAG_TYPE1); + break; + case RFAL_NFCA_T2T: + NfcTag_SelectProtocol(NFCTAG_TYPE2); + break; + case RFAL_NFCA_T4T: + NfcTag_SelectProtocol(NFCTAG_TYPE4); + break; + case RFAL_NFCA_NFCDEP: + /* TODO RFAL_NFCA_NFCDEP */ + break; + case RFAL_NFCA_T4T_NFCDEP: + /* TODO RFAL_NFCA_T4T_NFCDEP */ + break; + } + break; + case BSP_NFCTAG_NFCB: + NfcTag_SelectProtocol(NFCTAG_TYPE4); + break; + case BSP_NFCTAG_ST25TB: + NfcTag_SelectProtocol(NFCTAG_TYPE4); + break; + case BSP_NFCTAG_NFCF: + NfcTag_SelectProtocol(NFCTAG_TYPE3); + break; + case BSP_NFCTAG_NFCV: + NfcTag_SelectProtocol(NFCTAG_TYPE5); + break; + default: + return; + } +} +#endif + +/* Tag Tab setup */ +#ifndef FREEZE_DISPLAY +static Menu_Tab_Setup_t tabSetup[] = { +{"Tag Info", &tabFirstTagReadInfo, &tabTagReadInfo}, /* Tag information Tab */ +{"NDEF", &tabFirstTagReadNdef, &tabTagReadNdef}, /* Tag content Tab */ +}; +#endif + +/* Helper function to manage user touchscreen interface */ +static uint8_t manageInput(t_hydra_console *con) +{ +#ifndef FREEZE_DISPLAY + Menu_Position_t touch; + if(Menu_ReadPosition(&touch)) + { + if(touch.Y > 200) + { + // make sure the Wakeup mode is deactivated + rfalWakeUpModeStop(); + // switch the field off before leaving the demo + rfalFieldOff(); + return 1; + } else if (instructionsDisplayed) { + if(touch.Y < 60) + { + if(detectMode != DETECT_MODE_POLL) + { + detectMode = DETECT_MODE_POLL; + rfalWakeUpModeStop(); + setRadio(); + } + } else { + if(detectMode != DETECT_MODE_WAKEUP) + { + detectMode = DETECT_MODE_WAKEUP; + rfalFieldOff(); /* Turns the Field On and starts GT timer */ + HAL_Delay(100); + rfalWakeUpModeStart(NULL); + setRadio(); + } + } + } else + { + uint8_t devId = 0xFF; + // tags are in the field + if((touch.Y < getTagBoxY(1)) && (gDevCnt >= 1)) + { + devId = 0; + } else if ((touch.Y < getTagBoxY(2)) && (gDevCnt >= 2)) + { + devId = 1; + } else if ((touch.Y < getTagBoxY(3)) && (gDevCnt >= 3)) + { + devId = 2; + } else if (gDevCnt >= 4){ + devId = 3; + } + if (devId != 0xFF) + { + SelectNDEFProtocol(devId); + gActiveDev = &gDevList[devId]; + + /* Specific implementation for Random UIDs, as the selected UID has probably changed since last inventory */ + /* So re-run inventory and select the another random UID */ + if((gActiveDev->type == BSP_NFCTAG_NFCA) && + (gActiveDev->dev.nfca.type == RFAL_NFCA_T4T) && + (gActiveDev->dev.nfca.nfcId1Len == 4) && + (gActiveDev->dev.nfca.nfcId1[0] == 0x08)) + { + int err; + uint8_t devCnt; + // this is a random UID, need to refresh it + rfalNfcaListenDevice nfcaDevList[RFAL_POLLER_DEVICES]; + + rfalNfcaPollerInitialize(); + rfalFieldOnAndStartGT(); /* Turns the Field On and starts GT timer */ + err = rfalNfcaPollerFullCollisionResolution( RFAL_COMPLIANCE_MODE_NFC, RFAL_POLLER_DEVICES, nfcaDevList, &devCnt ); + if( (err == ERR_NONE) && (devCnt != 0) ) + { + int searchIndex; + for(searchIndex = 0; searchIndex < RFAL_POLLER_DEVICES ; searchIndex++ ) + { + if( (nfcaDevList[searchIndex].type == RFAL_NFCA_T4T) && + (nfcaDevList[searchIndex].nfcId1Len == 4) && + (nfcaDevList[searchIndex].nfcId1[0] == 0x08)) + { + // this is a random UID, select this one + devId = 0; + gDevList[devId].type = BSP_NFCTAG_NFCA; + gDevList[devId].dev.nfca = nfcaDevList[searchIndex]; + gActiveDev = &gDevList[devId]; + gDevCnt = 1; + // stop searching random uid + break; + } + } + } + } + // be carefull this cast has not the same size!!! + int status = BSP_NFCTAG_Activate((BSP_NFCTAG_Device_t *)&gDevList[devId]); + + Menu_MsgStatus("Tag read","",MSG_INFO); + Menu_DisplayCenterString(10, "Touch here to exit"); + Menu_TabLoop(tabSetup,sizeof(tabSetup)/sizeof(Menu_Tab_Setup_t)); + + BSP_LCD_SetFont(&Font22); + Menu_SetStyle(CLEAR_PLAIN); + Menu_FillRectangle(0,22,320,196); + Menu_Delay(200); + gActiveDev = NULL; + gState = RFAL_POLLER_STATE_DEACTIVATION; + } + } + } +#else + if(hydrabus_ubtn()) + { + cprintf(con, "UBTN pressed exit\r\n"); + // make sure the Wakeup mode is deactivated + rfalWakeUpModeStop(); + // switch the field off before leaving the demo + rfalFieldOff(); + return 1; + } + + if (instructionsDisplayed) + { + if(detectMode != DETECT_MODE_POLL) + { + detectMode = DETECT_MODE_POLL; + rfalWakeUpModeStop(); + setRadio(con); + } + }else + { +#if 0 + uint8_t devId = 0xFF; + // tags are in the field + if( (gDevCnt >= 1)) + { + devId = 0; + } else if ((gDevCnt >= 2)) + { + devId = 1; + } else if ((gDevCnt >= 3)) + { + devId = 2; + } else if (gDevCnt >= 4){ + devId = 3; + } + if (devId != 0xFF) + { + SelectNDEFProtocol(devId); + gActiveDev = &gDevList[devId]; + + /* Specific implementation for Random UIDs, as the selected UID has probably changed since last inventory */ + /* So re-run inventory and select the another random UID */ + if((gActiveDev->type == BSP_NFCTAG_NFCA) && + (gActiveDev->dev.nfca.type == RFAL_NFCA_T4T) && + (gActiveDev->dev.nfca.nfcId1Len == 4) && + (gActiveDev->dev.nfca.nfcId1[0] == 0x08)) + { + int err; + uint8_t devCnt; + // this is a random UID, need to refresh it + rfalNfcaListenDevice nfcaDevList[RFAL_POLLER_DEVICES]; + + err = rfalNfcaPollerInitialize(); + if( err != ERR_NONE ) + { + cprintf(con, "manageInput rfalNfcaPollerInitialize err=%d\r\n", err); + } + rfalFieldOnAndStartGT(); /* Turns the Field On and starts GT timer */ + err = rfalNfcaPollerFullCollisionResolution( RFAL_COMPLIANCE_MODE_NFC, RFAL_POLLER_DEVICES, nfcaDevList, &devCnt ); + if( (err == ERR_NONE) && (devCnt != 0) ) + { + int searchIndex; + for(searchIndex = 0; searchIndex < RFAL_POLLER_DEVICES ; searchIndex++ ) + { + if( (nfcaDevList[searchIndex].type == RFAL_NFCA_T4T) && + (nfcaDevList[searchIndex].nfcId1Len == 4) && + (nfcaDevList[searchIndex].nfcId1[0] == 0x08)) + { + // this is a random UID, select this one + devId = 0; + gDevList[devId].type = BSP_NFCTAG_NFCA; + gDevList[devId].dev.nfca = nfcaDevList[searchIndex]; + gActiveDev = &gDevList[devId]; + gDevCnt = 1; + // stop searching random uid + break; + } + } + } + } + // be carefull this cast has not the same size!!! + int status = BSP_NFCTAG_Activate((BSP_NFCTAG_Device_t *)&gDevList[devId]); + gActiveDev = NULL; + gState = RFAL_POLLER_STATE_DEACTIVATION; + } +#endif + } +#endif + return 0; +} + +/** @brief Scan Tags + * Detect and display tags in the field. + */ +void ScanTags(t_hydra_console *con) +{ +#ifndef FREEZE_DISPLAY + Menu_MsgStatus("Tag detection","",MSG_INFO); + Menu_SetStyle(CLEAR_PLAIN); + Menu_DisplayCenterString(10,"Touch here to exit"); +#endif +// cprintf(con, "Tag detection\r\nPress UBTN to exit\r\n"); + instructionsDisplayed = false; + + //Menu_SetStyle(PLAIN); + detectMode = DETECT_MODE_POLL; + tagDetectionNoTag(con); + + RfalPollerRun(con); +} + +/*! + ****************************************************************************** + * \brief Passive Poller Run + * + * This method implements the main state machine going thought all the + * different activities that a Reader/Poller device (PCD) needs to perform. + * + * + ****************************************************************************** + */ +static void RfalPollerRun(t_hydra_console *con) +{ + /* Initialize RFAL */ + platformLog("\n\r RFAL Poller started \r\n"); + //cprintf(con, "\n\r RFAL Poller started \r\n"); + gState = RFAL_POLLER_STATE_INIT; + + do + { + rfalWorker(); /* Execute RFAL process */ + if (detectMode == DETECT_MODE_WAKEUP) + { + if(!rfalWakeUpModeHasWoke()) + { + if(manageInput(con)) + { + return; + } + // still sleeping, don't do nothing... + continue; + } + // exit wake up mode + detectMode = DETECT_MODE_AWAKEN; + rfalWakeUpModeStop(); + } + + //cprintf(con, "gState=%d\r\n", gState); + switch( gState ) + { + /*******************************************************************************/ + case RFAL_POLLER_STATE_INIT: + { + gTechsFound = RFAL_POLLER_FOUND_NONE; + gActiveDev = NULL; + gDevCnt = 0; + + gState = RFAL_POLLER_STATE_TECHDETECT; + break; + } + /*******************************************************************************/ + case RFAL_POLLER_STATE_TECHDETECT: + { + if( !RfalPollerTechDetection(con) ) /* Poll for nearby devices in different technologies */ + { + gState = RFAL_POLLER_STATE_DEACTIVATION; /* If no device was found, restart loop */ + break; + } + + gState = RFAL_POLLER_STATE_COLAVOIDANCE; /* One or more devices found, go to Collision Avoidance */ + break; + } + /*******************************************************************************/ + case RFAL_POLLER_STATE_COLAVOIDANCE: + { + + if(instructionsDisplayed) + { +#ifndef FREEZE_DISPLAY + int clearline; + for(clearline = 1;clearline<9;clearline++) + BSP_LCD_ClearStringLine(clearline); +#endif + instructionsDisplayed = false; + } + + // add delay to avoid NFC-V Anticol frames back to back + if( !RfalPollerCollResolution(con) ) /* Resolve any eventual collision */ + { + gState = RFAL_POLLER_STATE_DEACTIVATION; /* If Collision Resolution was unable to retrieve any device, restart loop */ + break; + } + + platformLog("Device(s) found: %d \r\n", gDevCnt); + //cprintf(con, "Device(s) found: %d\r\n", gDevCnt); + + gState = RFAL_POLLER_STATE_DEACTIVATION; + break; + } + /*******************************************************************************/ + case RFAL_POLLER_STATE_DEACTIVATION: + { + int i, delay; + if(!instructionsDisplayed) + { +#ifndef FREEZE_DISPLAY + BSP_LCD_SetTextColor(LCD_COLOR_WHITE); + BSP_LCD_SetBackColor(LCD_COLOR_WHITE); +#endif + for(i = gDevCnt; i < 4; i++) + displayTag(i, "", NULL); + if(gDevCnt == 0) + { + tagDetectionNoTag(con); + instructionsDisplayed = true; + } + } + RfalPollerDeactivate(); /* If a card has been activated, properly deactivate the device */ + rfalFieldOff(); /* Turn the Field Off powering down any device nearby */ + for(delay = 0; delay < 100; delay++) + { + if(manageInput(con)) + { + return; + } + platformDelay( 1 ); /* Remain a certain period with field off */ + } + if( (detectMode == DETECT_MODE_AWAKEN) && (gDevCnt == 0) ) + { + // no more tags, restart wakeup mode + detectMode = DETECT_MODE_WAKEUP; + rfalFieldOff(); /* Turns the Field On and starts GT timer */ + HAL_Delay(100); + rfalWakeUpModeStart(NULL); + setRadio(con); + } + + gState = RFAL_POLLER_STATE_INIT; /* Restart the loop */ + break; + } + /*******************************************************************************/ + default: + return; + } + if(manageInput(con)) + { + return; + } + /* Wait a bit in order to display all text */ + chThdYield(); + chThdSleepMilliseconds(10); + } while(1); +} + +/*! + ****************************************************************************** + * \brief Poller Technology Detection + * + * This method implements the Technology Detection / Poll for different + * device technologies. + * + * \return true : One or more devices have been detected + * \return false : No device have been detected + * + ****************************************************************************** + */ +static bool RfalPollerTechDetection(t_hydra_console *con) +{ + (void)(con); + ReturnCode err; + rfalNfcaSensRes sensRes; + rfalNfcbSensbRes sensbRes; + rfalNfcvInventoryRes invRes; + uint8_t sensbResLen; + uint8_t chipId; + + gTechsFound = RFAL_POLLER_FOUND_NONE; + /*******************************************************************************/ + /* NFC-A Technology Detection */ + /*******************************************************************************/ + err = rfalNfcaPollerInitialize(); /* Initialize RFAL for NFC-A */ + if( err != ERR_NONE ) + { + //cprintf(con, "RfalPollerTechDetection rfalNfcaPollerInitialize err=%d\r\n", err); + } + rfalFieldOnAndStartGT(); /* Turns the Field On and starts GT timer */ + err = rfalNfcaPollerTechnologyDetection(RFAL_COMPLIANCE_MODE_NFC, &sensRes ); /* Poll for NFC-A devices */ + if( err == ERR_NONE ) + { + gTechsFound |= RFAL_POLLER_FOUND_A; + } else + { + //cprintf(con, "RfalPollerTechDetection rfalNfcaPollerTechnologyDetection err=%d\r\n", err); + } + + /*******************************************************************************/ + /* NFC-B Technology Detection */ + /*******************************************************************************/ + err = rfalNfcbPollerInitialize(); /* Initialize RFAL for NFC-B */ + if( err != ERR_NONE ) + { + //cprintf(con, "RfalPollerTechDetection rfalNfcbPollerInitialize err=%d\r\n", err); + } + rfalFieldOnAndStartGT(); /* As field is already On only starts GT timer */ + err = rfalNfcbPollerTechnologyDetection(RFAL_COMPLIANCE_MODE_NFC, &sensbRes, &sensbResLen ); /* Poll for NFC-B devices */ + if( err == ERR_NONE ) + { + gTechsFound |= RFAL_POLLER_FOUND_B; + } else + { + //cprintf(con, "RfalPollerTechDetection rfalNfcbPollerTechnologyDetection err=%d\r\n", err); + } + + /*******************************************************************************/ + /* ST25TB Technology Detection */ + /*******************************************************************************/ + err = rfalSt25tbPollerInitialize(); /* Initialize RFAL for NFC-B */ + if( err != ERR_NONE ) + { + //cprintf(con, "RfalPollerTechDetection rfalSt25tbPollerInitialize err=%d\r\n", err); + } + rfalFieldOnAndStartGT(); + /* As field is already On only starts GT timer */ + err = rfalSt25tbPollerCheckPresence( &chipId); + if( err == ERR_NONE ) + { + gTechsFound |= RFAL_POLLER_FOUND_ST25TB; + } else + { + //cprintf(con, "RfalPollerTechDetection rfalSt25tbPollerCheckPresence err=%d\r\n", err); + } + + /*******************************************************************************/ + /* NFC-F Technology Detection */ + /*******************************************************************************/ + err = rfalNfcfPollerInitialize( RFAL_BR_212 ); /* Initialize RFAL for NFC-F */ + if( err != ERR_NONE ) + { + //cprintf(con, "RfalPollerTechDetection rfalNfcfPollerInitialize err=%d\r\n", err); + } + rfalFieldOnAndStartGT(); /* As field is already On only starts GT timer */ + err = rfalNfcfPollerCheckPresence(); /* Poll for NFC-F devices */ + if( err == ERR_NONE ) + { + gTechsFound |= RFAL_POLLER_FOUND_F; + } else + { + //cprintf(con, "RfalPollerTechDetection rfalNfcfPollerCheckPresence err=%d\r\n", err); + } + + /*******************************************************************************/ + /* NFC-V Technology Detection */ + /*******************************************************************************/ + err = rfalNfcvPollerInitialize(); /* Initialize RFAL for NFC-V */ + if( err != ERR_NONE ) + { + //cprintf(con, "RfalPollerTechDetection rfalNfcvPollerInitialize err=%d\r\n", err); + } + rfalFieldOnAndStartGT(); /* As field is already On only starts GT timer */ + err = rfalNfcvPollerCheckPresence( &invRes ); /* Poll for NFC-V devices */ + if( err == ERR_NONE ) + { + gTechsFound |= RFAL_POLLER_FOUND_V; + } else + { + //cprintf(con, "RfalPollerTechDetection rfalNfcvPollerCheckPresence err=%d\r\n", err); + } + + return (gTechsFound != RFAL_POLLER_FOUND_NONE); +} + +/*! + ****************************************************************************** + * \brief Poller Collision Resolution + * + * This method implements the Collision Resolution on all technologies that + * have been detected before. + * + * \return true : One or more devices identified + * \return false : No device have been identified + * + ****************************************************************************** + */ +static bool RfalPollerCollResolution(t_hydra_console *con) +{ + uint8_t i; + uint8_t devCnt; + ReturnCode err; + + /*******************************************************************************/ + /* NFC-A Collision Resolution */ + /*******************************************************************************/ + if( gTechsFound & RFAL_POLLER_FOUND_A ) /* If a NFC-A device was found/detected, perform Collision Resolution */ + { + rfalNfcaListenDevice nfcaDevList[RFAL_POLLER_DEVICES]; + + err = rfalNfcaPollerInitialize(); /* Initialize RFAL for NFC-A */ + if( err != ERR_NONE ) + { + //cprintf(con, "RfalPollerCollResolution rfalNfcaPollerInitialize err=%d\r\n", err); + } + + err = rfalNfcaPollerFullCollisionResolution( RFAL_COMPLIANCE_MODE_NFC, (RFAL_POLLER_DEVICES - gDevCnt), nfcaDevList, &devCnt ); + if( (err == ERR_NONE) && (devCnt != 0) ) + { + for( i=0; i 0); +} + + +/*! + ****************************************************************************** + * \brief Poller NFC DEP Deactivate + * + * This method Deactivates the device if a deactivation procedure exists + * + * \return true : Deactivation successful + * \return false : Deactivation failed + * + ****************************************************************************** + */ +static bool RfalPollerDeactivate( void ) +{ + if( gActiveDev != NULL ) /* Check if a device has been activated */ + { + switch( gActiveDev->rfInterface ) + { + /*******************************************************************************/ + case RFAL_POLLER_INTERFACE_RF: + break; /* No specific deactivation to be performed */ + + /*******************************************************************************/ + case RFAL_POLLER_INTERFACE_ISODEP: + rfalIsoDepDeselect(); /* Send a Deselect to device */ + break; + + /*******************************************************************************/ + case RFAL_POLLER_INTERFACE_NFCDEP: + rfalNfcDepRLS(); /* Send a Release to device */ + break; + + default: + return false; + } + platformLog("Device deactivated \r\n"); + } + + return true; +} diff --git a/src/hydranfc_v2/hydranfc_v2.c b/src/hydranfc_v2/hydranfc_v2.c new file mode 100644 index 0000000..d6651ac --- /dev/null +++ b/src/hydranfc_v2/hydranfc_v2.c @@ -0,0 +1,1298 @@ +/* + * HydraBus/HydraNFC v2 + * + * Copyright (C) 2020 Benjamin VERNOUX + * + * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include /* sprintf */ +#include "ch.h" +#include "common.h" +#include "tokenline.h" +#include "hydrabus_mode.h" +#include "hydranfc_v2.h" +#include "bsp_spi.h" +#include "ff.h" +#include "microsd.h" +#include "hydrabus_sd.h" +#include +#include "bsp_uart.h" + +#include "platform.h" +#include "logger.h" +#include "usart.h" +#include "spi.h" +#include "led.h" + +#include "usbd_custom_hid_if.h" +//#include "ce.h" + +#include "stream_dispatcher.h" +#include "dispatcher.h" +#include "rfal_analogConfig.h" +#include "rfal_rf.h" +#include "rfal_dpo.h" +#include "rfal_chip.h" +#include "st25r3916.h" +#include "st25r3916_irq.h" + +static int exec(t_hydra_console *con, t_tokenline_parsed *p, int token_pos); +static int show(t_hydra_console *con, t_tokenline_parsed *p); + +static thread_t *key_sniff_thread = NULL; +static volatile int irq_count; +volatile int irq; +volatile int irq_end_rx; +uint8_t globalCommProtectCnt; + +/* Do not Enable DPO to have maximum performances/range */ +//#define DPO_ENABLE true + +#ifdef DPO_ENABLE +static rfalDpoEntry dpoSetup[] = { + // new antenna board + {.rfoRes=0, .inc=255, .dec=115}, + {.rfoRes=2, .inc=100, .dec=0x00} +}; +#endif + +void (* st25r3916_irq_fn)(void) = NULL; + +enum { + NFC_A, + NFC_B, + NFC_V, + NFC_F, + NFC_EMUL_UID_14443A +} nfc_function_t; + +/* Triggered when the Ext IRQ is pressed or released. */ +static void extcb1(void * arg) +{ + (void) arg; + + if(st25r3916_irq_fn != NULL) + st25r3916_irq_fn(); + + irq_count++; + irq = 1; +} + +void rfalPreTransceiveCb(void) +{ + rfalDpoAdjust(); +} + +ReturnCode hydranfc_v2_init_RFAL(t_hydra_console *con) +{ + ReturnCode err; + /* RFAL initalisation */ + rfalAnalogConfigInitialize(); + err = rfalInitialize(); + if(err != ERR_NONE) + { + cprintf(con, "hydranfc_v2_init_RFAL rfalInitialize() error=%d\r\n", err); + return err; + } + + /* DPO setup */ +#ifdef DPO_ENABLE + rfalDpoInitialize(); + rfalDpoSetMeasureCallback( rfalChipMeasureAmplitude ); + err = rfalDpoTableWrite(dpoSetup,sizeof(dpoSetup)/sizeof(rfalDpoEntry)); + if(err != ERR_NONE) + { + cprintf(con, "hydranfc_v2_init_RFAL rfalDpoTableWrite() error=%d\r\n", err); + return err; + } + rfalDpoSetEnabled(true); + rfalSetPreTxRxCallback(&rfalPreTransceiveCb); +#endif + return err; +} + +extern t_mode_config mode_con1; + +static bool init_gpio_spi_nfc(t_hydra_console *con) +{ + /* + * Initializes the SPI driver 2. The SPI2 signals are routed as follow: + * ST25R3916 IO4_CS SPI mode / HydraBus PC1 - NSS + * ST25R3916 DATA_CLK SPI mode / HydraBus PB10 - SCK + * ST25R3916 IO6_MISO SPI mode / HydraBus PC2 - MISO + * ST25R3916 IO7_MOSI SPI mode / HydraBus PC3 - MOSI + * Used for communication with ST25R3916 in SPI mode with NSS. + */ + mode_con1.proto.config.spi.dev_gpio_pull = MODE_CONFIG_DEV_GPIO_NOPULL; + mode_con1.proto.config.spi.dev_speed = 5; /* 5 250 000 Hz */ + mode_con1.proto.config.spi.dev_phase = 1; + mode_con1.proto.config.spi.dev_polarity = 0; + mode_con1.proto.config.spi.dev_bit_lsb_msb = DEV_FIRSTBIT_MSB; + mode_con1.proto.config.spi.dev_mode = DEV_MASTER; + bsp_spi_init(BSP_DEV_SPI2, &mode_con1.proto); + + /* + * Initializes the SPI driver 1. The SPI1 signals are routed as follows: + * Shall be configured as SPI Slave for ST25R3916 NFC data sampling on MOD pin. + * NSS. (Not used use Software). + * ST25R3916 MCU_CLK pin28 output / HydraBus PA5 - SCK.(AF5) => SPI Slave CLK input (Sniffer mode/RX Transparent Mode) + * ST25R3916 ST25R3916 MOSI SPI pin31 (IN) / HydraBus PA6 - MISO.(AF5) (MCU TX Transparent Mode) + * ST25R3916 ST25R3916 MISO_SDA pin32 (OUT) / HydraBus PA7 - MOSI.(AF5) => SPI Slave MOSI input (Sniffer mode/RX Transparent Mode) + */ + /* spiStart() is done in sniffer see sniffer.c */ + /* HydraBus SPI1 Slave CLK input */ + palSetPadMode(GPIOA, 5, PAL_MODE_ALTERNATE(5) | PAL_STM32_OSPEED_MID1); + /* HydraBus SPI1 Slave MISO. Not used/Not connected */ + palSetPadMode(GPIOA, 6, PAL_MODE_ALTERNATE(5) | PAL_STM32_OSPEED_MID1); + /* HydraBus SPI1 Slave MOSI. connected to ST25R3916 MOD Pin */ + palSetPadMode(GPIOA, 7, PAL_MODE_ALTERNATE(5) | PAL_STM32_OSPEED_MID1); + + /* Configure K1/2 Buttons as Input */ + palSetPadMode(GPIOB, 8, PAL_MODE_INPUT); /* K1 Button */ + palSetPadMode(GPIOB, 9, PAL_MODE_INPUT); /* K2 Button */ + + /* Configure D1/2/3/4 LEDs as Output */ + D1_OFF; + D2_OFF; + D3_OFF; + D4_OFF; + + palSetPadMode(GPIOB, 0, PAL_MODE_OUTPUT_PUSHPULL | PAL_STM32_OSPEED_MID1); + palSetPadMode(GPIOB, 3, PAL_MODE_OUTPUT_PUSHPULL | PAL_STM32_OSPEED_MID1); + palSetPadMode(GPIOB, 4, PAL_MODE_OUTPUT_PUSHPULL | PAL_STM32_OSPEED_MID1); + palSetPadMode(GPIOB, 5, PAL_MODE_OUTPUT_PUSHPULL | PAL_STM32_OSPEED_MID1); + + palDisablePadEvent(GPIOA, 1); + /* ST25R3916 IRQ output / HydraBus PA1 input */ + palClearPad(GPIOA, 1); + palSetPadMode(GPIOA, 1, PAL_MODE_INPUT | PAL_STM32_OSPEED_MID1); + /* Activates the PAL driver callback */ + //palDisablePadEvent(GPIOA, 1); + palEnablePadEvent(GPIOA, 1, PAL_EVENT_MODE_RISING_EDGE); + palSetPadCallback(GPIOA, 1, &extcb1, NULL); + + /* Init st25r3916 IRQ function callback */ + st25r3916_irq_fn = st25r3916Isr; + hal_st25r3916_spiInit(ST25R391X_SPI_DEVICE); + if (hydranfc_v2_init_RFAL(con) != ERR_NONE) + { + cprintf(con, "HydraNFC v2 not found.\r\n"); + return FALSE; + } + + /* Test platform Ticks/Delay */ +/* + { + uint32_t ticks_ms; + ticks_ms = platformGetSysTick(); + cprintf(con, "platformGetSysTick=%ld\r\n\r\n", ticks_ms); + + cprintf(con, "platformDelay(10) Start\r\n"); + ticks_ms = platformGetSysTick(); + cprintf(con, "platformGetSysTick=%ld\r\n", ticks_ms); + platformDelay(10); + cprintf(con, "platformDelay(10) End\r\n"); + ticks_ms = platformGetSysTick(); + cprintf(con, "platformGetSysTick=%ld\r\n\r\n", ticks_ms); + + cprintf(con, "platformDelay(100) Start\r\n"); + ticks_ms = platformGetSysTick(); + cprintf(con, "platformGetSysTick=%ld\r\n", ticks_ms); + platformDelay(100); + cprintf(con, "platformDelay(100) End\r\n"); + ticks_ms = platformGetSysTick(); + cprintf(con, "platformGetSysTick=%ld\r\n\r\n", ticks_ms); + + cprintf(con, "platformDelay(500) Start\r\n"); + ticks_ms = platformGetSysTick(); + cprintf(con, "platformGetSysTick=%ld\r\n", ticks_ms); + platformDelay(500); + cprintf(con, "platformDelay(500) End\r\n"); + ticks_ms = platformGetSysTick(); + cprintf(con, "platformGetSysTick=%ld\r\n\r\n", ticks_ms); + + cprintf(con, "platformDelay(1000) Start\r\n"); + ticks_ms = platformGetSysTick(); + cprintf(con, "platformGetSysTick=%ld\r\n", ticks_ms); + platformDelay(1000); + cprintf(con, "platformDelay(1000) End\r\n"); + ticks_ms = platformGetSysTick(); + cprintf(con, "platformGetSysTick=%ld\r\n\r\n", ticks_ms); + } +*/ + return TRUE; +} + +static void deinit_gpio_spi_nfc(t_hydra_console *con) +{ + (void)(con); + palClearPad(GPIOA, 1); + palSetPadMode(GPIOA, 1, PAL_MODE_INPUT); + palDisablePadEvent(GPIOA, 1); + + bsp_spi_deinit(BSP_DEV_SPI2); + + palSetPadMode(GPIOA, 5, PAL_MODE_INPUT); + palSetPadMode(GPIOA, 6, PAL_MODE_INPUT); + palSetPadMode(GPIOA, 7, PAL_MODE_INPUT); + +#if 0 + /* Configure K1/2 Buttons as Input */ + palSetPadMode(GPIOB, 8, PAL_MODE_INPUT); /* K1 Button */ + palSetPadMode(GPIOB, 9, PAL_MODE_INPUT); /* K2 Button */ + + /* Configure D1/2/3/4 LEDs as Input */ + palSetPadMode(GPIOB, 0, PAL_MODE_INPUT); + palSetPadMode(GPIOB, 3, PAL_MODE_INPUT); + palSetPadMode(GPIOB, 4, PAL_MODE_INPUT); + palSetPadMode(GPIOB, 5, PAL_MODE_INPUT); +#endif + st25r3916_irq_fn = NULL; +} + +THD_FUNCTION(key_sniff, arg) +{ + int i; + + (void)arg; + + chRegSetThreadName("HydraNFC_v2 key-sniff"); + + while (TRUE) + { + /* If K1_BUTTON is pressed */ + if (K1_BUTTON) + { + /* Wait Until K1_BUTTON is released */ + while(K1_BUTTON) { + D1_ON; + D2_OFF; + D3_ON; + D4_OFF; + chThdSleepMilliseconds(100); + + D1_OFF; + D2_OFF; + D3_OFF; + D4_OFF; + chThdSleepMilliseconds(100); + } + + /* Blink Fast */ + for(i = 0; i < 4; i++) { + D1_ON; + chThdSleepMilliseconds(25); + D1_OFF; + chThdSleepMilliseconds(25); + } + + D1_ON; + // TODO hydranfc_sniff_14443A + //hydranfc_sniff_14443A(NULL, TRUE, FALSE, FALSE); + D1_OFF; + } + + /* If K2_BUTTON is pressed */ + if (K2_BUTTON) + { + /* Wait Until K2_BUTTON is released */ + while(K2_BUTTON) { + D1_OFF; + D2_ON; + D3_OFF; + D4_ON; + chThdSleepMilliseconds(100); + + D1_OFF; + D2_OFF; + D3_OFF; + D4_OFF; + chThdSleepMilliseconds(100); + } + + /* Blink Fast */ + for(i = 0; i < 4; i++) { + D2_ON; + chThdSleepMilliseconds(25); + D2_OFF; + chThdSleepMilliseconds(25); + } + } + + if (chThdShouldTerminateX()) + { + chThdExit((msg_t)1); + } + chThdSleepMilliseconds(100); + } +} + +#if 0 +// TODO hydranfc_v2_scan_iso14443A +#define MIFARE_UL_DATA (MIFARE_UL_DATA_MAX/4) +#define MIFARE_CL1_MAX (5) +#define MIFARE_CL2_MAX (5) +void hydranfc_v2_scan_iso14443A(t_hydranfc_v2_scan_iso14443A *data) +{ + uint8_t data_buf[MIFARE_DATA_MAX]; + uint8_t CL1_buf[MIFARE_CL1_MAX]; + uint8_t CL2_buf[MIFARE_CL2_MAX]; + + uint8_t CL1_buf_size = 0; + uint8_t CL2_buf_size = 0; + + uint8_t i; + + /* Clear data elements */ + memset(data, 0, sizeof(t_hydranfc_v2_scan_iso14443A)); + + /* End Test delay */ + irq_count = 0; + + /* Test ISO14443-A/Mifare read UID */ + Trf797xInitialSettings(); + Trf797xResetFIFO(); + + /* + * Write Modulator and SYS_CLK Control Register (0x09) (13.56Mhz SYS_CLK + * and default Clock 13.56Mhz)) + */ + data_buf[0] = MODULATOR_CONTROL; + data_buf[1] = 0x31; + Trf797xWriteSingle(data_buf, 2); + + /* + * Configure Mode ISO Control Register (0x01) to 0x88 (ISO14443A RX bit + * rate, 106 kbps) and no RX CRC (CRC is not present in the response)) + */ + data_buf[0] = ISO_CONTROL; + data_buf[1] = 0x88; + Trf797xWriteSingle(data_buf, 2); + + /* + data_buf[0] = ISO_CONTROL; + Trf797xReadSingle(data_buf, 1); + if (data_buf[0] != 0x88) + cprintf(con, "Error ISO Control Register read=0x%02lX (should be 0x88)\r\n", + (uint32_t)data_buf[0]); + */ + + /* Turn RF ON (Chip Status Control Register (0x00)) */ + Trf797xTurnRfOn(); + + /* Send REQA (7 bits) and receive ATQA (2 bytes) */ + data_buf[0] = 0x26; /* REQA (7bits) */ + data->atqa_buf_nb_rx_data = Trf797x_transceive_bits(data_buf[0], 7, data->atqa_buf, MIFARE_ATQA_MAX, + 10, /* 10ms TX/RX Timeout */ + 0); /* TX CRC disabled */ + /* Re-send REQA */ + if (data->atqa_buf_nb_rx_data == 0) { + /* Send REQA (7 bits) and receive ATQA (2 bytes) */ + data_buf[0] = 0x26; /* REQA (7 bits) */ + data->atqa_buf_nb_rx_data = Trf797x_transceive_bits(data_buf[0], 7, data->atqa_buf, MIFARE_ATQA_MAX, + 10, /* 10ms TX/RX Timeout */ + 0); /* TX CRC disabled */ + } + if (data->atqa_buf_nb_rx_data > 0) { + /* Send AntiColl Cascade Level1 (2 bytes) and receive CT+3 UID bytes+BCC (5 bytes) [tag 7 bytes UID] or UID+BCC (5 bytes) [tag 4 bytes UID] */ + data_buf[0] = 0x93; + data_buf[1] = 0x20; + + CL1_buf_size = Trf797x_transceive_bytes(data_buf, 2, CL1_buf, MIFARE_CL1_MAX, + 10, /* 10ms TX/RX Timeout */ + 0); /* TX CRC disabled */ + + /* Check tag 7 bytes UID */ + if (CL1_buf[0] == 0x88) { + for (i = 0; i < 3; i++) { + data->uid_buf[data->uid_buf_nb_rx_data] = CL1_buf[1 + i]; + data->uid_buf_nb_rx_data++; + } + + /* Send AntiColl Cascade Level1 (2 bytes)+CT+3 UID bytes+BCC (5 bytes) and receive SAK1 (1 byte) */ + data_buf[0] = 0x93; + data_buf[1] = 0x70; + + for (i = 0; i < CL1_buf_size; i++) { + data_buf[2 + i] = CL1_buf[i]; + } + + data->sak1_buf_nb_rx_data = Trf797x_transceive_bytes(data_buf, (2 + CL1_buf_size), data->sak1_buf, MIFARE_SAK_MAX, + 20, /* 10ms TX/RX Timeout */ + 1); /* TX CRC disabled */ + if(data->sak1_buf_nb_rx_data >= 3) + data->sak1_buf_nb_rx_data -= 2; /* Remove 2 last bytes (CRC) */ + + if (data->sak1_buf_nb_rx_data > 0) { + + /* Send AntiColl Cascade Level2 (2 bytes) and receive 4 UID bytes+BCC (5 bytes)*/ + data_buf[0] = 0x95; + data_buf[1] = 0x20; + + CL2_buf_size = Trf797x_transceive_bytes(data_buf, 2, CL2_buf, MIFARE_CL2_MAX, + 10, /* 10ms TX/RX Timeout */ + 0); /* TX CRC disabled */ + + if (CL2_buf_size > 0) { + for (i = 0; i < 4; i++) { + data->uid_buf[data->uid_buf_nb_rx_data] = CL2_buf[i]; + data->uid_buf_nb_rx_data++; + } + + /* + data_buf[0] = RSSI_LEVELS; + Trf797xReadSingle(data_buf, 1); + if (data_buf[0] < 0x40) + cprintf(con, "RSSI error: 0x%02lX (should be > 0x40)\r\n", (uint32_t)data_buf[0]); + */ + /* + * Select RX with CRC_A + * Configure Mode ISO Control Register (0x01) to 0x08 + * (ISO14443A RX bit rate, 106 kbps) and RX CRC (CRC + * is present in the response) + */ + data_buf[0] = ISO_CONTROL; + data_buf[1] = 0x08; + Trf797xWriteSingle(data_buf, 2); + + /* Send AntiColl Cascade Level2 (2 bytes)+4 UID bytes(4 bytes) and receive SAK2 (1 byte) */ + data_buf[0] = 0x95; + data_buf[1] = 0x70; + + for (i = 0; i < CL2_buf_size; i++) { + data_buf[2 + i] = CL2_buf[i]; + } + + data->sak2_buf_nb_rx_data = Trf797x_transceive_bytes(data_buf, (2 + CL2_buf_size), data->sak2_buf, MIFARE_SAK_MAX, + 20, /* 10ms TX/RX Timeout */ + 1); /* TX CRC disabled */ + + if (data->sak2_buf_nb_rx_data > 0) { + /* Check if it is a Mifare Ultra Light */ + if( (data->atqa_buf[0] == 0x44) && (data->atqa_buf[1] == 0x00) && + (data->sak1_buf[0] == 0x04) && (data->sak2_buf[1] == 0x00) + ) { + for (i = 0; i < 16; i+=4) { + /* Send Read 16 bytes Mifare UL (2Bytes+CRC) */ + data_buf[0] = 0x30; + data_buf[1] = (uint8_t)i; + data->mf_ul_data_nb_rx_data += Trf797x_transceive_bytes(data_buf, 2, &data->mf_ul_data[data->mf_ul_data_nb_rx_data], MIFARE_UL_DATA, + 20, /* 20ms TX/RX Timeout */ + 1); /* TX CRC enabled */ + } + } + } else { + /* Send HALT 2Bytes (CRC is added automatically) */ + data_buf[0] = 0x50; + data_buf[1] = 0x00; + data->halt_buf_nb_rx_data += Trf797x_transceive_bytes(data_buf, 2, data->halt_buf, MIFARE_HALT_MAX, + 20, /* 20ms TX/RX Timeout */ + 1); /* TX CRC enabled */ + } + } + } + } + + /* tag 4 bytes UID */ + else { + data->uid_buf_nb_rx_data = Trf797x_transceive_bytes(data_buf, 2, data->uid_buf, MIFARE_UID_MAX, + 10, /* 10ms TX/RX Timeout */ + 0); /* TX CRC disabled */ + if (data->uid_buf_nb_rx_data > 0) { + /* + data_buf[0] = RSSI_LEVELS; + Trf797xReadSingle(data_buf, 1); + if (data_buf[0] < 0x40) + cprintf(con, "RSSI error: 0x%02lX (should be > 0x40)\r\n", (uint32_t)data_buf[0]); + */ + + /* + * Select RX with CRC_A + * Configure Mode ISO Control Register (0x01) to 0x08 + * (ISO14443A RX bit rate, 106 kbps) and RX CRC (CRC + * is present in the response) + */ + data_buf[0] = ISO_CONTROL; + data_buf[1] = 0x08; + Trf797xWriteSingle(data_buf, 2); + + /* Finish Select (6 bytes) and receive SAK1 (1 byte) */ + data_buf[0] = 0x93; + data_buf[1] = 0x70; + for (i = 0; i < data->uid_buf_nb_rx_data; i++) { + data_buf[2 + i] = data->uid_buf[i]; + } + data->sak1_buf_nb_rx_data = Trf797x_transceive_bytes(data_buf, (2 + data->uid_buf_nb_rx_data), data->sak1_buf, MIFARE_SAK_MAX, + 20, /* 20ms TX/RX Timeout */ + 1); /* TX CRC enabled */ + /* Send HALT 2Bytes (CRC is added automatically) */ + data_buf[0] = 0x50; + data_buf[1] = 0x00; + data->halt_buf_nb_rx_data = Trf797x_transceive_bytes(data_buf, 2, data->halt_buf, MIFARE_HALT_MAX, + 20, /* 20ms TX/RX Timeout */ + 1); /* TX CRC enabled */ + } + } + } + + /* Turn RF OFF (Chip Status Control Register (0x00)) */ + Trf797xTurnRfOff(); +} +#endif + +#if 0 +// TODO hydranfc_v2_scan_mifare +void hydranfc_v2_scan_mifare(t_hydra_console *con) +{ + int i; + uint8_t bcc; + t_hydranfc_v2_scan_iso14443A* data; + t_hydranfc_v2_scan_iso14443A data_buf; + + data = &data_buf; + hydranfc_v2_scan_iso14443A(data); + + if(data->atqa_buf_nb_rx_data > 0) { + cprintf(con, "ATQA:"); + for (i = 0; i < data->atqa_buf_nb_rx_data; i++) + cprintf(con, " %02X", data->atqa_buf[i]); + cprintf(con, "\r\n"); + } + + if(data->sak1_buf_nb_rx_data > 0) { + cprintf(con, "SAK1:"); + for (i = 0; i < data->sak1_buf_nb_rx_data; i++) + cprintf(con, " %02X", data->sak1_buf[i]); + cprintf(con, "\r\n"); + } + + if(data->sak2_buf_nb_rx_data > 0) { + cprintf(con, "SAK2:"); + for (i = 0; i < data->sak2_buf_nb_rx_data; i++) + cprintf(con, " %02X", data->sak2_buf[i]); + cprintf(con, "\r\n"); + } + + if(data->uid_buf_nb_rx_data > 0) { + if(data->uid_buf_nb_rx_data >= 7) { + cprintf(con, "UID:"); + for (i = 0; i < data->uid_buf_nb_rx_data ; i++) { + cprintf(con, " %02X", data->uid_buf[i]); + } + cprintf(con, "\r\n"); + } else { + cprintf(con, "UID:"); + bcc = 0; + for (i = 0; i < data->uid_buf_nb_rx_data - 1; i++) { + cprintf(con, " %02X", data->uid_buf[i]); + bcc ^= data->uid_buf[i]; + } + cprintf(con, " (BCC %02X %s)\r\n", data->uid_buf[i], + bcc == data->uid_buf[i] ? "ok" : "NOT OK"); + } + } + + if (data->mf_ul_data_nb_rx_data > 0) { + #define ISO14443A_SEL_L1_CT 0x88 /* TX CT for 1st Byte */ + uint8_t expected_uid_bcc0; + uint8_t obtained_uid_bcc0; + uint8_t expected_uid_bcc1; + uint8_t obtained_uid_bcc1; + + cprintf(con, "DATA:"); + for (i = 0; i < data->mf_ul_data_nb_rx_data; i++) { + if(i % 16 == 0) + cprintf(con, "\r\n"); + + cprintf(con, " %02X", data->mf_ul_data[i]); + } + cprintf(con, "\r\n"); + + /* Check Data UID with BCC */ + cprintf(con, "DATA UID:"); + for (i = 0; i < 3; i++) + cprintf(con, " %02X", data->mf_ul_data[i]); + for (i = 4; i < 8; i++) + cprintf(con, " %02X", data->mf_ul_data[i]); + cprintf(con, "\r\n"); + + expected_uid_bcc0 = (ISO14443A_SEL_L1_CT ^ data->mf_ul_data[0] ^ data->mf_ul_data[1] ^ data->mf_ul_data[2]); // BCC1 + obtained_uid_bcc0 = data->mf_ul_data[3]; + cprintf(con, " (DATA BCC0 %02X %s)\r\n", expected_uid_bcc0, + expected_uid_bcc0 == obtained_uid_bcc0 ? "ok" : "NOT OK"); + + expected_uid_bcc1 = (data->mf_ul_data[4] ^ data->mf_ul_data[5] ^ data->mf_ul_data[6] ^ data->mf_ul_data[7]); // BCC2 + obtained_uid_bcc1 = data->mf_ul_data[8]; + cprintf(con, " (DATA BCC1 %02X %s)\r\n", expected_uid_bcc1, + expected_uid_bcc1 == obtained_uid_bcc1 ? "ok" : "NOT OK"); + } + /* + cprintf(con, "irq_count: 0x%02ld\r\n", (uint32_t)irq_count); + irq_count = 0; + */ +} +#endif + +#if 0 +// TODO hydranfc_v2_read_mifare_ul +/* Return TRUE if success or FALSE if error */ +int hydranfc_v2_read_mifare_ul(t_hydra_console *con, char* filename) +{ + int i; + FRESULT err; + FIL fp; + uint8_t bcc; + t_hydranfc_v2_scan_iso14443A* data; + t_hydranfc_v2_scan_iso14443A data_buf; + + data = &data_buf; + hydranfc_v2_scan_iso14443A(data); + + if(data->atqa_buf_nb_rx_data > 0) { + cprintf(con, "ATQA:"); + for (i = 0; i < data->atqa_buf_nb_rx_data; i++) + cprintf(con, " %02X", data->atqa_buf[i]); + cprintf(con, "\r\n"); + } + + if(data->sak1_buf_nb_rx_data > 0) { + cprintf(con, "SAK1:"); + for (i = 0; i < data->sak1_buf_nb_rx_data; i++) + cprintf(con, " %02X", data->sak1_buf[i]); + cprintf(con, "\r\n"); + } + + if(data->sak2_buf_nb_rx_data > 0) { + cprintf(con, "SAK2:"); + for (i = 0; i < data->sak2_buf_nb_rx_data; i++) + cprintf(con, " %02X", data->sak2_buf[i]); + cprintf(con, "\r\n"); + } + + if(data->uid_buf_nb_rx_data > 0) { + if(data->uid_buf_nb_rx_data >= 7) { + cprintf(con, "UID:"); + for (i = 0; i < data->uid_buf_nb_rx_data ; i++) { + cprintf(con, " %02X", data->uid_buf[i]); + } + cprintf(con, "\r\n"); + } else { + cprintf(con, "UID:"); + bcc = 0; + for (i = 0; i < data->uid_buf_nb_rx_data - 1; i++) { + cprintf(con, " %02X", data->uid_buf[i]); + bcc ^= data->uid_buf[i]; + } + cprintf(con, " (BCC %02X %s)\r\n", data->uid_buf[i], + bcc == data->uid_buf[i] ? "ok" : "NOT OK"); + } + } + + if (data->mf_ul_data_nb_rx_data > 0) { + #define ISO14443A_SEL_L1_CT 0x88 /* TX CT for 1st Byte */ + uint8_t expected_uid_bcc0; + uint8_t obtained_uid_bcc0; + uint8_t expected_uid_bcc1; + uint8_t obtained_uid_bcc1; + + cprintf(con, "DATA:"); + for (i = 0; i < data->mf_ul_data_nb_rx_data; i++) { + if(i % 16 == 0) + cprintf(con, "\r\n"); + + cprintf(con, " %02X", data->mf_ul_data[i]); + } + cprintf(con, "\r\n"); + + /* Check Data UID with BCC */ + cprintf(con, "DATA UID:"); + for (i = 0; i < 3; i++) + cprintf(con, " %02X", data->mf_ul_data[i]); + for (i = 4; i < 8; i++) + cprintf(con, " %02X", data->mf_ul_data[i]); + cprintf(con, "\r\n"); + + expected_uid_bcc0 = (ISO14443A_SEL_L1_CT ^ data->mf_ul_data[0] ^ data->mf_ul_data[1] ^ data->mf_ul_data[2]); // BCC1 + obtained_uid_bcc0 = data->mf_ul_data[3]; + cprintf(con, " (DATA BCC0 %02X %s)\r\n", expected_uid_bcc0, + expected_uid_bcc0 == obtained_uid_bcc0 ? "ok" : "NOT OK"); + + expected_uid_bcc1 = (data->mf_ul_data[4] ^ data->mf_ul_data[5] ^ data->mf_ul_data[6] ^ data->mf_ul_data[7]); // BCC2 + obtained_uid_bcc1 = data->mf_ul_data[8]; + cprintf(con, " (DATA BCC1 %02X %s)\r\n", expected_uid_bcc1, + expected_uid_bcc1 == obtained_uid_bcc1 ? "ok" : "NOT OK"); + + if( (expected_uid_bcc0 == obtained_uid_bcc0) && (expected_uid_bcc1 == obtained_uid_bcc1) ) + { + if (!is_fs_ready()) { + err = mount(); + if(err) { + cprintf(con, "Mount failed: error %d\r\n", err); + return FALSE; + } + } + + if (!file_open(&fp, filename, 'w')) { + cprintf(con, "Failed to open file %s\r\n", filename); + return FALSE; + } + if(file_append(&fp, data->mf_ul_data, data->mf_ul_data_nb_rx_data)) { + cprintf(con, "Failed to write file %s\r\n", filename); + file_close(&fp); + return FALSE; + } + if (!file_close(&fp)) { + cprintf(con, "Failed to close file %s\r\n", filename); + return FALSE; + } + cprintf(con, "write file %s with success\r\n", filename); + return TRUE; + }else + { + cprintf(con, "Error invalid BCC0/BCC1, file %s not written\r\n", filename); + return FALSE; + } + }else + { + cprintf(con, "Error no data, file %s not written\r\n", filename); + return FALSE; + } + /* + cprintf(con, "irq_count: 0x%02ld\r\n", (uint32_t)irq_count); + irq_count = 0; + */ +} +#endif + +#if 0 +// TODO hydranfc_v2_scan_vicinity +void hydranfc_v2_scan_vicinity(t_hydra_console *con) +{ + static uint8_t data_buf[VICINITY_UID_MAX]; + uint8_t fifo_size; + int i; + + /* End Test delay */ + irq_count = 0; + + /* Test ISO15693 read UID */ + Trf797xInitialSettings(); + Trf797xResetFIFO(); + + /* Write Modulator and SYS_CLK Control Register (0x09) (13.56Mhz SYS_CLK and default Clock 13.56Mhz)) */ + data_buf[0] = MODULATOR_CONTROL; + data_buf[1] = 0x31; + Trf797xWriteSingle(data_buf, 2); + + /* Configure Mode ISO Control Register (0x01) to 0x02 (ISO15693 high bit rate, one subcarrier, 1 out of 4) */ + data_buf[0] = ISO_CONTROL; + data_buf[1] = 0x02; + Trf797xWriteSingle(data_buf, 2); + + /* Configure Test Settings 1 to BIT6/0x40 => MOD Pin becomes receiver subcarrier output (Digital Output for RX/TX) */ + /* + data_buf[0] = TEST_SETTINGS_1; + data_buf[1] = BIT6; + Trf797xWriteSingle(data_buf, 2); + + data_buf[0] = TEST_SETTINGS_1; + Trf797xReadSingle(data_buf, 1); + if (data_buf[0] != 0x40) + { + cprintf(con, "Error Test Settings Register(0x1A) read=0x%02lX (shall be 0x40)\r\n", (uint32_t)data_buf[0]); + err++; + } + */ + + /* Turn RF ON (Chip Status Control Register (0x00)) */ + Trf797xTurnRfOn(); + + McuDelayMillisecond(10); + + /* Send Inventory(3B) and receive data + UID */ + data_buf[0] = 0x26; /* Request Flags */ + data_buf[1] = 0x01; /* Inventory Command */ + data_buf[2] = 0x00; /* Mask */ + + fifo_size = Trf797x_transceive_bytes(data_buf, 3, data_buf, VICINITY_UID_MAX, + 10, /* 10ms TX/RX Timeout (shall be less than 10ms (6ms) in High Speed) */ + 1); /* CRC enabled */ + if (fifo_size > 0) { + /* fifo_size should be 10. */ + cprintf(con, "UID:"); + for (i = 0; i < fifo_size; i++) + cprintf(con, " 0x%02lX", (uint32_t)data_buf[i]); + cprintf(con, "\r\n"); + + /* Read RSSI levels and oscillator status(0x0F/0x4F) */ + data_buf[0] = RSSI_LEVELS; + Trf797xReadSingle(data_buf, 1); + if (data_buf[0] < 0x40) { + cprintf(con, "RSSI error: 0x%02lX (should be > 0x40)\r\n", (uint32_t)data_buf[0]); + } + } + + /* Turn RF OFF (Chip Status Control Register (0x00)) */ + Trf797xTurnRfOff(); + + /* + cprintf(con, "irq_count: 0x%02ld\r\n", (uint32_t)irq_count); + irq_count = 0; + */ +} +#endif + +extern void ScanTags(t_hydra_console *con); + +static void scan(t_hydra_console *con) +{ + /* Init st25r3916 IRQ function callback */ + st25r3916_irq_fn = st25r3916Isr; + + ScanTags(con); + + irq_count = 0; + st25r3916_irq_fn = NULL; + +/* + if (proto->config.hydranfc.dev_function == NFC_TYPEA) + hydranfc_v2_scan_mifare(con); + else if (proto->config.hydranfc.dev_function == NFC_VICINITY) + hydranfc_v2_scan_vicinity(con); +*/ +} + +static int exec(t_hydra_console *con, t_tokenline_parsed *p, int token_pos) +{ + int dev_func; + mode_config_proto_t* proto = &con->mode->proto; + int action, period, t; + bool continuous; + unsigned int mifare_uid = 0; + filename_t sd_file; + int str_offset; + bool sniff_trace_uart1; + bool sniff_raw; + bool sniff_bin; + bool sniff_frame_time; + bool sniff_parity; + + if(p->tokens[token_pos] == T_SD) + { + t = cmd_sd(con, p); + return t; + } + + /* Stop & Start External IRQ */ + st25r3916_irq_fn = NULL; + + sniff_trace_uart1 = FALSE; + sniff_raw = FALSE; + sniff_bin = FALSE; + sniff_frame_time = FALSE; + sniff_parity = FALSE; + action = 0; + period = 1000; + continuous = FALSE; + sd_file.filename[0] = 0; + for (t = token_pos; p->tokens[t]; t++) { + switch (p->tokens[t]) { + case T_SHOW: + t += show(con, p); + break; +/* + case T_NFCA: + proto->config.hydranfc.dev_function = NFC_A; + break; + + case T_NFCB: + proto->config.hydranfc.dev_function = NFC_B; + break; + + case T_NFCV: + proto->config.hydranfc.dev_function = NFC_V; + break; + + case T_NFCF: + proto->config.hydranfc.dev_function = NFC_F; + break; +*/ + case T_PERIOD: + t += 2; + memcpy(&period, p->buf + p->tokens[t], sizeof(int)); + break; + + case T_CONTINUOUS: + continuous = TRUE; + break; + + case T_FILE: + /* Filename specified */ + memcpy(&str_offset, &p->tokens[t+3], sizeof(int)); + snprintf(sd_file.filename, FILENAME_SIZE, "0:%s", p->buf + str_offset); + break; + + case T_SCAN: + action = p->tokens[t]; + break; + + case T_READ_MF_ULTRALIGHT: + action = p->tokens[t]; + if (p->tokens[t+1] != T_ARG_STRING || p->tokens[t+3] != 0) + return FALSE; + memcpy(&str_offset, &p->tokens[t+2], sizeof(int)); + snprintf(sd_file.filename, FILENAME_SIZE, "0:%s", p->buf + str_offset); + break; + + case T_EMUL_MF_ULTRALIGHT: + case T_CLONE_MF_ULTRALIGHT: + action = p->tokens[t]; + break; + + case T_TRACE_UART1: + sniff_trace_uart1 = TRUE; + break; + + case T_FRAME_TIME: + sniff_frame_time = TRUE; + break; + + case T_BIN: + sniff_bin = TRUE; + break; + + case T_PARITY: + sniff_parity = TRUE; + break; + + case T_RAW: + sniff_raw = TRUE; + break; + + case T_SNIFF: + action = p->tokens[t]; + break; + + case T_EMUL_MIFARE: + action = p->tokens[t]; + t += 2; + memcpy(&mifare_uid, p->buf + p->tokens[t], sizeof(int)); + break; + case T_EMUL_ISO14443A: + case T_DIRECT_MODE_0: + case T_DIRECT_MODE_1: + action = p->tokens[t]; + break; + } + } + + switch(action) { + case T_SCAN: + dev_func = proto->config.hydranfc.dev_function; + + if (continuous) { + cprintf(con, "Scanning NFC-A/B/V/F"); + cprintf(con, "with %dms period. Press user button to stop.\r\n", period); + while (!hydrabus_ubtn()) { + scan(con); + chThdSleepMilliseconds(period); + } + } else { + scan(con); + } + /* + if( (dev_func == NFC_TYPEA) || (dev_func == NFC_VICINITY) ) { + if (continuous) { + cprintf(con, "Scanning %s ", + proto->config.hydranfc.dev_function == NFC_TYPEA ? "MIFARE" : "Vicinity"); + cprintf(con, "with %dms period. Press user button to stop.\r\n", period); + while (!hydrabus_ubtn()) { + scan(con); + chThdSleepMilliseconds(period); + } + } else { + scan(con); + } + } else { + cprintf(con, "Please select TypeA or Vicinity mode first.\r\n"); + return 0; + } + */ + break; + + case T_READ_MF_ULTRALIGHT: + cprintf(con, "T_READ_MF_ULTRALIGHT not implemented.\r\n"); + // TODO T_READ_MF_ULTRALIGHT + //hydranfc_v2_read_mifare_ul(con, sd_file.filename); + break; + + case T_EMUL_MF_ULTRALIGHT: + cprintf(con, "T_EMUL_MF_ULTRALIGHT not implemented.\r\n"); + // TODO T_EMUL_MF_ULTRALIGHT + /* + if(sd_file.filename[0] != 0) + { + hydranfc_emul_mf_ultralight_file(con, sd_file.filename); + }else + { + hydranfc_emul_mf_ultralight(con); + } + */ + break; + + case T_CLONE_MF_ULTRALIGHT: + cprintf(con, "T_CLONE_MF_ULTRALIGHT not implemented.\r\n"); + break; + + case T_SNIFF: + // TODO T_SNIFF + cprintf(con, "T_SNIFF not implemented.\r\n"); + #if 0 + if(sniff_bin) + { + if(sniff_raw) + { + /* Sniffer Binary RAW UART1 only */ + hydranfc_sniff_14443AB_bin_raw(con, sniff_frame_time, sniff_frame_time); + }else + { + /* Sniffer Binary UART1 only */ + hydranfc_sniff_14443A_bin(con, sniff_frame_time, sniff_frame_time, sniff_parity); + } + }else + { + if(sniff_raw) + { + /* Sniffer Binary RAW UART1 only */ + hydranfc_sniff_14443AB_bin_raw(con, sniff_frame_time, sniff_frame_time); + }else + { + /* Sniffer ASCII */ + if(sniff_trace_uart1) + { + if(sniff_frame_time) + cprintf(con, "frame-time disabled for trace-uart1 in ASCII\r\n"); + hydranfc_sniff_14443A(con, FALSE, FALSE, TRUE); + }else + { + hydranfc_sniff_14443A(con, sniff_frame_time, sniff_frame_time, FALSE); + } + } + } + #endif + break; + + case T_EMUL_MIFARE: + cprintf(con, "T_EMUL_MIFARE not implemented.\r\n"); + // TODO T_EMUL_MIFARE + //hydranfc_emul_mifare(con, mifare_uid); + break; + + case T_EMUL_ISO14443A: + cprintf(con, "T_EMUL_ISO14443A not implemented.\r\n"); + // TODO T_EMUL_ISO14443A + //hydranfc_emul_iso14443a(con); + break; + + case T_DIRECT_MODE_0: + /* + TODO Test Transparent mode + TX encoding: + In Transparent mode, the framing and FIFO are bypassed, and the MOSI pin directly drives + the modulation of the transmitter. + RX decoding: + In Transparent mode the framing and FIFO are bypassed. The digitized subcarrier signal + directly drives the MISO pin + */ + break; + + case T_DIRECT_MODE_1: + /* + TODO Test Stream mode + TX encoding: + In Stream mode the framing is bypassed. The FIFO data directly defines the modulation + data sent to the transmitter. + RX decoding: + In Stream mode the framing is bypassed. The digitized subcarrier signal is directly stored in + the FIFO. + */ + break; + + default: + break; + } + + return t - token_pos; +} + +void show_registers(t_hydra_console *con) +{ + ReturnCode err; + unsigned int i; + t_st25r3916Regs regDump; + + err = st25r3916GetRegsDump(®Dump); + if(err != ERR_NONE) + { + cprintf(con, "st25r3916GetRegsDump() error=%d\r\n", err); + } + + /* ST25R3916 space A */ + cprintf(con, "ST25R3916 Registers space A:\r\n"); + for (i = 0; i < ST25R3916_REG_IC_IDENTITY+1; i++) { + cprintf(con, "0x%02x\t: 0x%02x\r\n", i, regDump.RsA[i]); + } + cprintf(con, "\r\n"); + /* ST25R3916 space B */ + cprintf(con, "ST25R3916 Registers space B:\r\n"); + for (i = 0; i < ST25R3916_SPACE_B_REG_LEN; i++) { + cprintf(con, "0x%02x\t: 0x%02x\r\n", i, regDump.RsB[i]); + } +} + +static int show(t_hydra_console *con, t_tokenline_parsed *p) +{ + mode_config_proto_t* proto = &con->mode->proto; + int tokens_used; + + tokens_used = 0; + if (p->tokens[1] == T_REGISTERS) { + tokens_used++; + show_registers(con); + } else { + + switch(proto->config.hydranfc.dev_function) { + case NFC_A: + cprintf(con, "Protocol: NFC_A (ISO14443A => MIFARE...)\r\n"); + break; + case NFC_V: + cprintf(con, "Protocol: NFC_V Vicinity (ISO/IEC 15693)\r\n"); + break; + default: + cprintf(con, "Protocol: Unknown\r\n"); + break; + } + } + + return tokens_used; +} + +static const char *get_prompt(t_hydra_console *con) +{ + (void)con; + return "NFCv2" PROMPT; +} + +static int init(t_hydra_console *con, t_tokenline_parsed *p) +{ + mode_config_proto_t* proto; + int tokens_used = 0; + + if(con != NULL) + { + proto = &con->mode->proto; + proto->config.hydranfc.dev_function = NFC_A; + } + + if(init_gpio_spi_nfc(con) == FALSE) { + deinit_gpio_spi_nfc(con); + return tokens_used; + } + + if(key_sniff_thread == NULL) { +/* + key_sniff_thread = chThdCreateFromHeap(NULL, + 8192, + "key_sniff", + NORMALPRIO, + key_sniff, + NULL); +*/ + } + + /* Process cmdline arguments, skipping "nfc". */ + if(p != NULL) { + if(con != NULL) + { + tokens_used = 1 + exec(con, p, 1); + } + } + + return tokens_used; +} + + +/** \brief DeInit/Cleanup HydraNFC functions + * + * \param con t_hydra_console*: hydra console (optional can be NULL if unused) + * \return void + * + */ +void hydranfc_cleanup(t_hydra_console *con) +{ + if(key_sniff_thread != NULL) { + chThdTerminate(key_sniff_thread); + chThdWait(key_sniff_thread); + key_sniff_thread = NULL; + } + + deinit_gpio_spi_nfc(con); +} + +/** \brief Check if HydraNFC is detected + * + * \return bool: return TRUE if success or FALSE if failure + * + */ +bool hydranfc_v2_is_detected(void) +{ + if(init_gpio_spi_nfc(NULL) == FALSE) { + deinit_gpio_spi_nfc(NULL); + return FALSE; + } + return TRUE; +} + +/** \brief Init HydraNFC functions + * + * \param con t_hydra_console*: hydra console (optional can be NULL if unused) + * \return bool: return TRUE if success or FALSE if failure + * + */ +bool hydranfc_init(t_hydra_console *con) +{ + if(con != NULL) + { + /* Defaults */ + /* + mode_config_proto_t* proto = &con->mode->proto; + proto->dev_num = 0; + proto->config.uart.dev_speed = 115200; + proto->config.uart.dev_parity = 0; + proto->config.uart.dev_stop_bit = 1; + proto->config.uart.bus_mode = BSP_UART_MODE_UART; + bsp_uart_init(proto->dev_num, proto); + */ + } + init(con, NULL); + + return TRUE; +} + +const mode_exec_t mode_nfc_exec = { + .init = &init, + .exec = &exec, + .cleanup = &hydranfc_cleanup, + .get_prompt = &get_prompt, +}; diff --git a/src/hydranfc_v2/hydranfc_v2.h b/src/hydranfc_v2/hydranfc_v2.h new file mode 100644 index 0000000..32cb923 --- /dev/null +++ b/src/hydranfc_v2/hydranfc_v2.h @@ -0,0 +1,104 @@ +/* + * HydraBus/HydraNFC v2 + * + * Copyright (C) 2020 Benjamin VERNOUX + * + * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 + * + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _HYDRANFC_V2_H_ +#define _HYDRANFC_V2_H_ + +#include "common.h" +//#include "mcu.h" + +#define MIFARE_DATA_MAX 20 +/* Does not managed UID > 4+BCC to be done later ... */ +#define MIFARE_UID_MAX 11 +#define VICINITY_UID_MAX 16 + +#define MIFARE_ATQA_MAX (4) +#define MIFARE_SAK_MAX (4) +#define MIFARE_HALT_MAX (4) +#define MIFARE_UL_DATA_MAX (64) + +#define NFC_TX_RAWDATA_BUF_SIZE (64) +extern unsigned char nfc_tx_rawdata_buf[NFC_TX_RAWDATA_BUF_SIZE+1]; + +/* TODO macro in HAL... */ +/* USer Button K1/2 Configured as Input */ +#define K1_BUTTON (palReadPad(GPIOB, 8)) +#define K2_BUTTON (palReadPad(GPIOB, 9)) + +/* LEDs D1/D2/D3/D4 Configured as Output */ +#define D1_ON (palSetPad(GPIOB, 0)) +#define D1_OFF (palClearPad(GPIOB, 0)) +#define D1_TOGGLE (palTogglePad(GPIOB, 0)) + +#define D2_ON (palSetPad(GPIOB, 3)) +#define D2_OFF (palClearPad(GPIOB, 3)) + +#define D3_ON (palSetPad(GPIOB, 4)) +#define D3_OFF (palClearPad(GPIOB, 4)) + +#define D4_ON (palSetPad(GPIOB, 5)) +#define D4_OFF (palClearPad(GPIOB, 5)) + +extern void (*st25r3916_irq_fn)(void); + +/* Structure used & filled by hydranfc_scan_iso14443A() */ +typedef struct { + uint8_t atqa_buf_nb_rx_data; + uint8_t atqa_buf[MIFARE_ATQA_MAX]; + + uint8_t uid_buf_nb_rx_data; + uint8_t uid_buf[MIFARE_UID_MAX]; + + uint8_t sak1_buf_nb_rx_data; + uint8_t sak1_buf[MIFARE_SAK_MAX]; + + uint8_t sak2_buf_nb_rx_data; + uint8_t sak2_buf[MIFARE_SAK_MAX]; + + uint8_t halt_buf_nb_rx_data; + uint8_t halt_buf[MIFARE_HALT_MAX]; + + uint8_t mf_ul_data_nb_rx_data; + uint8_t mf_ul_data[MIFARE_UL_DATA_MAX]; +} t_hydranfc_scan_iso14443A; + +bool hydranfc_v2_is_detected(void); + +bool hydranfc_init(t_hydra_console *con); +void hydranfc_cleanup(t_hydra_console *con); + +void hydranfc_show_registers(t_hydra_console *con); + +void hydranfc_scan_iso14443A(t_hydranfc_scan_iso14443A *data); + +void hydranfc_scan_mifare(t_hydra_console *con); +void hydranfc_scan_vicinity(t_hydra_console *con); + +void hydranfc_sniff_14443A(t_hydra_console *con, bool start_of_frame, bool end_of_frame, bool sniff_trace_uart1); +void hydranfc_sniff_14443A_bin(t_hydra_console *con, bool start_of_frame, bool end_of_frame, bool parity); +void hydranfc_sniff_14443AB_bin_raw(t_hydra_console *con, bool start_of_frame, bool end_of_frame); + +void hydranfc_emul_mifare(t_hydra_console *con, uint32_t mifare_uid); + +void hydranfc_emul_iso14443a(t_hydra_console *con); + +void hydranfc_emul_mf_ultralight(t_hydra_console *con); +int hydranfc_emul_mf_ultralight_file(t_hydra_console *con, char* filename); + +#endif /* _HYDRANFC_V2_H_ */ + diff --git a/src/hydranfc_v2/hydranfc_v2.mk b/src/hydranfc_v2/hydranfc_v2.mk new file mode 100644 index 0000000..55497bd --- /dev/null +++ b/src/hydranfc_v2/hydranfc_v2.mk @@ -0,0 +1,6 @@ +# List of all the hydranfc related files. +HYDRANFC_V2_SRC = hydranfc_v2/hydranfc_v2.c \ + hydranfc_v2/hydranfc_rfal_poller.c + +# Required include directories +HYDRANFC_V2_INC = ./hydranfc_v2 diff --git a/src/hydranfc_v2/lib.mk b/src/hydranfc_v2/lib.mk new file mode 100644 index 0000000..8df490f --- /dev/null +++ b/src/hydranfc_v2/lib.mk @@ -0,0 +1,9 @@ +# List of all the HydraNFC v2 lib related files. +HYDRANFC_V2_LIB_SRC = hydranfc_v2/lib/ndef/src/lib_wrapper.c \ + hydranfc_v2/lib/ndef/src/tagtype5_wrapper.c \ + hydranfc_v2/lib/st25r/src/st25r.c + +# Required include directories +HYDRANFC_V2_LIB_INC = ./hydranfc_v2/lib/common/inc \ + ./hydranfc_v2/lib/ndef/inc \ + ./hydranfc_v2/lib/st25r/inc diff --git a/src/hydranfc_v2/lib/common/inc/tagtype3_wrapper.h b/src/hydranfc_v2/lib/common/inc/tagtype3_wrapper.h new file mode 100644 index 0000000..2972138 --- /dev/null +++ b/src/hydranfc_v2/lib/common/inc/tagtype3_wrapper.h @@ -0,0 +1,10 @@ +#ifndef _TAGTYPE3_WRAPPER_H_ +#define _TAGTYPE3_WRAPPER_H_ + +#include "lib_NDEF.h" + +uint16_t NfcType3_GetLength(uint16_t* Length); +uint16_t NfcType3_ReadNDEF( uint8_t* pData ); +uint16_t NfcType3_WriteNDEF(uint16_t Length, uint8_t* pData ); + +#endif // _TAGTYPE3_WRAPPER_H_ diff --git a/src/hydranfc_v2/lib/common/inc/tagtype4_wrapper.h b/src/hydranfc_v2/lib/common/inc/tagtype4_wrapper.h new file mode 100644 index 0000000..6070e9c --- /dev/null +++ b/src/hydranfc_v2/lib/common/inc/tagtype4_wrapper.h @@ -0,0 +1,10 @@ +#ifndef _TAGNFCA_H_ +#define _TAGNFCA_H_ + +#include "lib_NDEF.h" + +uint16_t NfcType4_GetLength(uint16_t* Length); +uint16_t NfcType4_ReadNDEF( uint8_t* pData ); +uint16_t NfcType4_WriteNDEF(uint16_t Length, uint8_t* pData ); + +#endif // _TAGNFCA_H_ diff --git a/src/hydranfc_v2/lib/common/inc/tagtype5_wrapper.h b/src/hydranfc_v2/lib/common/inc/tagtype5_wrapper.h new file mode 100644 index 0000000..b78d891 --- /dev/null +++ b/src/hydranfc_v2/lib/common/inc/tagtype5_wrapper.h @@ -0,0 +1,131 @@ +/** + ****************************************************************************** + * @file tagtype5_wrapper.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file provides an abstraction layer to the libNDEF for the NFC Forum Type5 Tag. + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __TAGTYPE5_WRAPPER_H +#define __TAGTYPE5_WRAPPER_H + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + +/** @addtogroup Tag_Type_5 + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief Tag Type 5 State enumeration definition. + */ +typedef enum +{ + TT5_NO_NDEF = 0, /**< No data detected in the tag. */ + TT5_INITIALIZED, /**< Capability container detected. */ + TT5_READ_WRITE, /**< Read-Write data detected. */ + TT5_READ /**< Read-Only data message detected. */ +} TT5_State; + +/** @brief Type5 Tag Capability Container Magic numbers as defined by the NFC Forum. */ +typedef enum { + NFCT5_MAGICNUMBER_E1_CCFILE = 0xE1, /**< Complete data area can be read by 1-byte block adrdess commands. */ + NFCT5_MAGICNUMBER_E2_CCFILE = 0xE2 /**< Last part of the data area can be only read by 2-bytes block address commands.\n + The first 256 blocks can be read by 1-byte block address commands. */ +} TT5_MagicNumber_t; + +/** + * @brief Type5 Tag Capability Container structure. + */ +typedef struct +{ + TT5_MagicNumber_t MagicNumber; /**< CCfile[0]: Magic Number should be E1h or E2h (for extended API) */ + uint8_t Version; /**< CCfile[1]: Capability container version (b7-b4) and access conditions (b3-b0) */ + uint8_t MemorySize; /**< CCfile[2]: Memory size, expressed in 8 bytes blocks, set to 0 if tag size is greater than 16kbits. */ + uint8_t TT5Tag; /**< CCfile[3]: Additionnal information on the Type5 Tag:\n + b0: supports `read multiple block` commands\n + b1: RFU\n + b2: RFU\n + b3: supports `lock block` commands\n + b4: requires the `special frame` format + */ + uint8_t rsved1; /**< RFU */ + uint8_t rsved2; /**< RFU */ + uint16_t ExtMemorySize; /**< CCfile[6],CCfile[7]: Memory size, expressed in 8 bytes blocks, when tag size is greater than 16kbits. */ + TT5_State State; /**< Indicates if a NDEF message is present. */ + uint32_t NDEF_offset; /**< Indicates the address of a NDEF message in the tag. */ +}sCCFileInfo; + +/** @brief Type5 Tag Type-Length-Value structure as defined by the NFC Forum */ +typedef struct +{ + uint8_t Type; /**< NFC Forum message Type */ + uint8_t Length; /**< Message length if lesser than 255 bytes */ + uint16_t Length16; /**< Message length if greater than or equal to 255 bytes */ +} TT5_TLV_t; + + +/* Exported constants --------------------------------------------------------*/ +/** @brief Memory size value indicating that this is a 8-bytes Capability Container */ +#define NFCT5_EXTENDED_CCFILE 0x00 +/** @brief Capability container version 1.0 */ +#define NFCT5_VERSION_V1_0 0x40 +/** @brief Read access condition mask for the Capability Container byte1 */ +#define NFCT5_READ_ACCESS 0x0C +/** @brief Write access condition mask for the Capability Container byte1 */ +#define NFCT5_WRITE_ACCESS 0x03 + +/** @brief Type5 Tag NDEF message TLV-Type. */ +#define NFCT1_LOCK_CONTROL_TLV ((uint8_t) 0x01) +#define NFCT1_MEMORY_CONTROL_TLV ((uint8_t) 0x02) +#define NFCT5_NDEF_MSG_TLV ((uint8_t) 0x03) +/** @brief Type5 Tag Proprietary message TLV-Type. */ +#define NFCT5_PROPRIETARY_TLV ((uint8_t) 0xFD) +/** @brief Type5 Tag Terminator TLV-Type. */ +#define NFCT5_TERMINATOR_TLV ((uint8_t) 0xFE) +/** @brief TLV-Length indicating a 4-bytes TLV (Length coded on 2 bytes). */ +#define NFCT5_3_BYTES_L_TLV ((uint8_t) 0xFF) + +/* Exported macro ------------------------------------------------------------*/ +/* External variables --------------------------------------------------------*/ +extern sCCFileInfo CCFileStruct; +extern uint16_t ccFileOffset; + +/* Exported functions ------------------------------------------------------- */ +uint16_t NfcType5_WriteCCFile( const uint8_t * const pCCBuffer ); +uint16_t NfcType5_ReadCCFile( uint8_t * const pCCBuffer ); +uint16_t NfcType5_TT5Init( void ); +uint16_t NfcType5_NDEFDetection( void ); +uint16_t NfcType5_ReadNDEF( uint8_t* pData ); +uint16_t NfcType5_WriteNDEF(uint16_t Length, uint8_t* pData ); +uint16_t NfcType5_GetLength(uint16_t* Length); + +#endif /* __TAGTYPE5_WRAPPER_H */ + +/* @} + */ + +/******************* (C) COPYRIGHT 2016 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF.h new file mode 100644 index 0000000..7877818 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF.h @@ -0,0 +1,271 @@ +/** + ****************************************************************************** + * @file lib_NDEF.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage NDEF file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_H +#define __LIB_NDEF_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +/* include file which match the HW configuration */ +#include "lib_wrapper.h" +#include + +#define NDEF_ACTION_COMPLETED 0x9000 + +#ifndef errorchk +#define errorchk(fCall) if (status = (fCall), status != NDEF_ACTION_COMPLETED) \ + {goto Error;} else +#endif + +/* Error codes for Higher level */ +#define NDEF_OK RESULTOK +#define NDEF_ERROR ERRORCODE_GENERIC +#define NDEF_ERROR_MEMORY_TAG 2 +#define NDEF_ERROR_MEMORY_INTERNAL 3 +#define NDEF_ERROR_LOCKED 4 +#define NDEF_ERROR_NOT_FORMATED 5 + +#define NDEF_MAX_SIZE NFC_DEVICE_MAX_NDEFMEMORY +#define NDEF_RECORD_MAX_SIZE (512) + +#define NDEF_SIZE_OFFSET 0 +#define FIRST_RECORD_OFFSET 0 + +#define RECORD_FLAG_FIELD 1 +#define TYPE_LENGTH_FIELD 1 +#define ID_LENGTH_FIELD 1 + + +#define MB_Mask ((uint8_t)(0x80)) +#define ME_Mask ((uint8_t)(0x40)) +#define CF_Mask ((uint8_t)(0x20)) +#define SR_Mask ((uint8_t)(0x10)) +#define IL_Mask ((uint8_t)(0x08)) +#define TNF_Mask ((uint8_t)(0x07)) + +#define TNF_Empty 0x00 +#define TNF_WellKnown 0x01 +#define TNF_MediaType 0x02 +#define TNF_AbsoluteURI 0x03 +#define TNF_NFCForumExternal 0x04 +#define TNF_Unknown 0x05 +#define TNF_Unchanged 0x06 +#define TNF_Reserved 0x07 + +#define SP_MAX_RECORD 4 + +#define AAR_TYPE_STRING "android.com:pkg" +#define AAR_TYPE_STRING_LENGTH 15 + +#define M24SR_DISCOVERY_APP_STRING "st.com:m24sr_discovery_democtrl" +#define M24SR_DISCOVERY_APP_STRING_LENGTH 31 + +#define VCARD_TYPE_STRING "text/vcard" +#define VCARD_TYPE_STRING_LENGTH 10 + +#define XVCARD_TYPE_STRING "text/x-vCard" +#define XVCARD_TYPE_STRING_LENGTH 12 + +#define XVCARD2_TYPE_STRING "text/x-vcard" +#define XVCARD2_TYPE_STRING_LENGTH 12 + +#define SMART_POSTER_TYPE_STRING "Sp" +#define SMART_POSTER_TYPE_STRING_LENGTH 2 + +#define URI_TYPE_STRING "U" +#define URI_TYPE_STRING_LENGTH 1 + +#define SMS_TYPE_STRING "sms:" +#define SMS_TYPE_STRING_LENGTH 4 + +#define GEO_TYPE_STRING "geo:" +#define GEO_TYPE_STRING_LENGTH 4 + +#define URI_LATITUDE_END "," +#define URI_LATITUDE_END_LENGTH 1 + +#define EMAIL_TYPE_STRING "mailto:" +#define EMAIL_TYPE_STRING_LENGTH 7 + +#define URI_FIRST_DATA_END "?" +#define URI_FIRST_DATA_END_LENGTH 1 + +#define SUBJECT_BEGIN_STRING "subject=" +#define SUBJECT_BEGIN_STRING_LENGTH 8 + +#define MESSAGE_BEGIN_STRING "body=" +#define MESSAGE_BEGIN_STRING_LENGTH 5 + +#define URI_SECOND_DATA_END "&" +#define URI_SECOND_DATA_END_LENGTH 1 + +#define TEXT_TYPE_STRING "T" +#define TEXT_TYPE_STRING_LENGTH 1 + +#define ISO_ENGLISH_CODE_STRING "en" +#define ISO_ENGLISH_CODE_STRING_LENGTH 2 + + +#define URI_ID_0x00 0x00 +#define URI_ID_0x01 0x01 +#define URI_ID_0x02 0x02 +#define URI_ID_0x03 0x03 +#define URI_ID_0x04 0x04 +#define URI_ID_0x05 0x05 +#define URI_ID_0x06 0x06 +#define URI_ID_0x07 0x07 +#define URI_ID_0x08 0x08 +#define URI_ID_0x09 0x09 +#define URI_ID_0x0A 0x0A +#define URI_ID_0x0B 0x0B +#define URI_ID_0x0C 0x0C +#define URI_ID_0x0D 0x0D +#define URI_ID_0x0E 0x0E +#define URI_ID_0x0F 0x0F +#define URI_ID_0x10 0x10 +#define URI_ID_0x11 0x11 +#define URI_ID_0x12 0x12 +#define URI_ID_0x13 0x13 +#define URI_ID_0x14 0x14 +#define URI_ID_0x15 0x15 +#define URI_ID_0x16 0x16 +#define URI_ID_0x17 0x17 +#define URI_ID_0x18 0x18 +#define URI_ID_0x19 0x19 +#define URI_ID_0x1A 0x1A +#define URI_ID_0x1B 0x1B +#define URI_ID_0x1C 0x1C +#define URI_ID_0x1D 0x1D +#define URI_ID_0x1E 0x1E +#define URI_ID_0x1F 0x1F +#define URI_ID_0x20 0x20 +#define URI_ID_0x21 0x21 +#define URI_ID_0x22 0x22 +#define URI_ID_0x23 0x23 +#define URI_RFU 0x24 + +#define URI_ID_0x01_STRING "http://www.\0" +#define URI_ID_0x02_STRING "https://www.\0" +#define URI_ID_0x03_STRING "http://\0" +#define URI_ID_0x04_STRING "https://\0" +#define URI_ID_0x05_STRING "tel:\0" +#define URI_ID_0x06_STRING "mailto:\0" +#define URI_ID_0x07_STRING "ftp://anonymous:anonymous@\0" +#define URI_ID_0x08_STRING "ftp://ftp.\0" +#define URI_ID_0x09_STRING "ftps://\0" +#define URI_ID_0x0A_STRING "sftp://\0" +#define URI_ID_0x0B_STRING "smb://\0" +#define URI_ID_0x0C_STRING "nfs://\0" +#define URI_ID_0x0D_STRING "ftp://\0" +#define URI_ID_0x0E_STRING "dav://\0" +#define URI_ID_0x0F_STRING "news:\0" +#define URI_ID_0x10_STRING "telnet://\0" +#define URI_ID_0x11_STRING "imap:\0" +#define URI_ID_0x12_STRING "rtsp://\0" +#define URI_ID_0x13_STRING "urn:\0" +#define URI_ID_0x14_STRING "pop:\0" +#define URI_ID_0x15_STRING "sip:\0" +#define URI_ID_0x16_STRING "sips:\0" +#define URI_ID_0x17_STRING "tftp:\0" +#define URI_ID_0x18_STRING "btspp://\0" +#define URI_ID_0x19_STRING "btl2cap://\0" +#define URI_ID_0x1A_STRING "btgoep://\0" +#define URI_ID_0x1B_STRING "tcpobex://\0" +#define URI_ID_0x1C_STRING "irdaobex://\0" +#define URI_ID_0x1D_STRING "file://\0" +#define URI_ID_0x1E_STRING "urn:epc:id:\0" +#define URI_ID_0x1F_STRING "urn:epc:tag\0" +#define URI_ID_0x20_STRING "urn:epc:pat:\0" +#define URI_ID_0x21_STRING "urn:epc:raw:\0" +#define URI_ID_0x22_STRING "urn:epc:\0" +#define URI_ID_0x23_STRING "urn:nfc:\0" + +// exported variables +extern uint8_t NDEF_Buffer[NDEF_MAX_SIZE]; +extern uint32_t NDEF_Buffer_size; +extern uint8_t NDEF_Record_Buffer [NDEF_RECORD_MAX_SIZE]; +extern uint32_t NDEF_Record_Buffer_size; + +typedef enum +{ + UNKNOWN_TYPE = 0, + VCARD_TYPE, + WELL_KNOWN_ABRIDGED_URI_TYPE, + URI_SMS_TYPE, + URI_GEO_TYPE, + URI_EMAIL_TYPE, + SMARTPOSTER_TYPE, + URL_TYPE, + TEXT_TYPE, + HANDOVER_TYPE, + /* list of "external type" known by this demo, other external type will be addressed as UNKNWON_TYPE */ + M24SR_DISCOVERY_APP_TYPE, + BT_TYPE, + BLE_TYPE, + URI_WIFITOKEN_TYPE +} NDEF_TypeDef; + +typedef struct sRecordInfo sRecordInfo_t; + +struct sRecordInfo +{ + uint8_t RecordFlags; + uint8_t TypeLength; + uint32_t PayloadLength; + uint8_t IDLength; + uint8_t Type[0xFF]; + uint8_t ID[0xFF]; + uint16_t PayloadOffset; + uint8_t* PayloadBufferAdd; /* add where payload content has been stored */ + NDEF_TypeDef NDEF_Type; /* to store identification ID for application */ + sRecordInfo_t *SPRecordStructAdd[SP_MAX_RECORD]; /*in case of smart poster array to store add of other sRecordInfo struct */ + uint8_t NbOfRecordInSPPayload; +}; + +uint16_t NDEF_IdentifyNDEF( sRecordInfo_t *pRecordStruct, uint8_t* pNDEF ); +uint16_t NDEF_IdentifyBuffer( sRecordInfo_t *pRecordStruct, uint8_t* pNDEF ); +uint16_t NDEF_ReadNDEF( uint8_t *pNDEF ); +uint16_t NDEF_WriteNDEF( uint16_t NDEF_Size, uint8_t *pNDEF ); +uint16_t NDEF_ClearNDEF(void); +uint16_t NDEF_getNDEFSize(uint16_t* Size); +uint32_t NDEF_WriteRecord( sRecordInfo_t *pRecord, uint8_t* pNDEF ); +uint16_t NDEF_AppendRecord(sRecordInfo_t *Record ); +uint32_t NDEF_GetRecordLength( sRecordInfo_t *pRecord ); + +#ifdef __cplusplus +} +#endif +#endif /* __LIB_NDEF_H */ + + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_AAR.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_AAR.h new file mode 100644 index 0000000..44df63b --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_AAR.h @@ -0,0 +1,54 @@ +/** + ****************************************************************************** + * @file lib_NDEF_AAR.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage AAR. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_AAR_H +#define __LIB_NDEF_AAR_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + +typedef struct +{ + char PackageName[80]; +}sAARInfo; + +uint16_t NDEF_AddAAR( const sAARInfo *pAARStruct ); + +#ifdef __cplusplus +} +#endif + +#endif /* __LIB_NDEF_AAR_H */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Bluetooth.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Bluetooth.h new file mode 100644 index 0000000..272f3db --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Bluetooth.h @@ -0,0 +1,209 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Bluetooth.h + * @author MMY Application Team + * @version $Revision: 2475 $ + * @date $Date: 2016-06-24 12:11:59 +0200 (Fri, 24 Jun 2016) $ + * @brief This file help to manage a NDEF file representing a Bluetooth pairing info. + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_BLUETOOTH_H +#define __LIB_NDEF_BLUETOOTH_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + +/** @addtogroup lib_NDEF_Bluetooth + * @{ + */ + +/** @brief MIME type for the Bluetooth BR/EDR Out-Of-Band data. */ +#define NDEF_BLUETOOTH_BREDR_MIME_TYPE "application/vnd.bluetooth.ep.oob" +/** @brief MIME type for the Bluetooth Low Energy Out-Of-Band data. */ +#define NDEF_BLUETOOTH_BLE_MIME_TYPE "application/vnd.bluetooth.le.oob" + + +/** @brief Enumerates the Extended Inquiry Responses, as defined in the Bluetooth v4.0 core specification. */ +typedef enum { + BLUETOOTH_EIR_FLAGS = 0x01, /**< Bluetooth flags:\n + b0: LE limited Discoverable Mode,\n + b1: LE general Discoverable Mode,\n + b2: BR/EDR not supported,\n + b3: Simultaneous LE & BR/EDR Conroller,\n + b4: Simultaneous LE & BR/EDR Host + */ + BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_16 = 0x02, /**< Bluetooth service UUID on 16-bits (partial list) */ + BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_16 = 0x03, /**< Bluetooth service UUID on 16-bits (complete list) */ + BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_32 = 0x04, /**< Bluetooth service UUID on 32-bits (partial list) */ + BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_32 = 0x05, /**< Bluetooth service UUID on 32-bits (complete list) */ + BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_128 = 0x06, /**< Bluetooth service UUID on 128-bits (partial list) */ + BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_128 = 0x07, /**< Bluetooth service UUID on 128-bits (complete list) */ + BLUETOOTH_EIR_SHORT_LOCAL_NAME = 0x08, /**< Shortened local name */ + BLUETOOTH_EIR_COMPLETE_LOCAL_NAME = 0x09, /**< Complete local name */ + BLUETOOTH_EIR_TX_POWER_LEVEL = 0x0A, /**< TX Power Level (1 byte): 0xXX:-127 to +127dBm */ + BLUETOOTH_EIR_DEVICE_CLASS = 0x0D, /**< Class of device, Format defined in Assigned Numbers */ + BLUETOOTH_EIR_SIMPLE_PAIRING_HASH = 0x0E, /**< Simple Pairing Hash C (16 octets), Format defined in [Vol. 2], Part H Section 7.2.2*/ + BLUETOOTH_EIR_SIMPLE_PAIRING_RANDOMIZER = 0x0F, /**< Simple Pairing Randomizer R (16 octets), Format defined in[Vol. 2], Part H Section 7.2.2 */ + BLUETOOTH_EIR_SECURITY_MANAGER_TK_VALUE = 0x10, /**< TK Value: Value as used in pairing over LE Physical channel. Format defined in [Vol. 3], Part H Section 2.3*/ + BLUETOOTH_EIR_SECURITY_MANAGER_FLAGS = 0x11, /**< Flags (1 octet):\n + b0: OOB Flags Field (0 = OOB data not present, 1 = OOB data present),\n + b1: LE supported (Host) (i.e. bit 65 of LMP Extended Feature bits Page 1),\n + b2: Simultaneous LE and BR/EDR to Same Device Capable (Host) (i.e. bit 66 of LMP Extended Feature bits Page 1)\n + b3: Address type (0 = Public Address, 1 = Random Address) + */ + BLUETOOTH_EIR_SLAVE_CONNECTION_INTERVAL_RANGE = 0x12, /**< Slave Connection Interval Range: The first 2 octets defines the minimum value for the connection interval, The second 2 octets defines the maximum value for the connection interval */ + BLUETOOTH_EIR_SERVICE_SOLICITATION_16 = 0x14, /**< Service UUIDs: List of 16 bit Service UUIDs*/ + BLUETOOTH_EIR_SERVICE_SOLICITATION_128 = 0x15, /**< Service UUIDs: List of 128 bit Service UUID*/ + BLUETOOTH_EIR_SERVICE_DATA = 0x16, /**< Service Data (2 or more octets): The first 2 octets contain the 16 bit Service UUID followed by additional service data */ + BLUETOOTH_EIR_APPEARANCE = 0x19, /**< UUID for `Appearance`: The Appearance characteristic value shall be the enumerated value as defined by Bluetooth Assigned Numbers document. */ + BLUETOOTH_EIR_BLE_DEVICE_ADDRESS = 0x1B, /**< 6 LSB bytes: Device address, 7th byte: Address type (Public/Random) */ + BLUETOOTH_EIR_BLE_ROLE = 0x1C, /**< Device Role: Periph only, Central only, Periph prefered, Central prefered */ + BLUETOOTH_EIR_MANUFACTURER_DATA = 0xFF /**< Manufacturer Specific Data (2 or more octets): The first 2 octets contain the Company Identifier Code followed by additional manufacturer specific data */ +} Ndef_Bluetooth_Eir_Types_t; + + +/** @brief Bluetooth Flag field: LE limited discovery. */ +#define NDEF_BLE_LIMITED_DISCOVERY_FLAG (0x1) +/** @brief Bluetooth Flag field: LE general discovery. */ +#define NDEF_BLE_GENERAL_DISCOVERY_FLAG (0x2) +/** @brief Bluetooth Flag field: BR/EDR compliant. */ +#define NDEF_BLE_NOT_BREDR_COMPLIANT_FLAG (0x4) +/** @brief Bluetooth Flag field: LE & BR/EDR simultaneous support. */ +#define NDEF_BLE_LE_BREDR_SIMULTANEOUS_FLAG (0x8) + +/** @brief Enumerates the Bluetooth LE address types. */ +typedef enum { + NDEF_BLE_PUBLIC_ADDRESS_TYPE = 0x0, /**< Public Device Address. */ + NDEF_BLE_RANDOM_ADDRESS_TYPE = 0x1, /**< Random Device Address. */ + NDEF_BLE_UNDEF_ADDRESS_TYPE = 0xff /**< Device Address is undefined. */ +} Ndef_BLE_Address_Type_t; + +/** @brief Enumerates Bluetooth LE Roles */ +typedef enum { + NDEF_BLE_ROLE_PERIPH_ONLY = 0x0, /**< Only Peripheral Role supported. */ + NDEF_BLE_ROLE_CENTRAL_ONLY = 0x1, /**< Only Central Role supported. */ + NDEF_BLE_ROLE_PERIPH_PREFERRED = 0x2, /**< Peripheral and Central Role supported, Peripheral Role preferred for connection establishment. */ + NDEF_BLE_ROLE_CENTRAL_PREFERRED = 0x3, /**< Peripheral and Central Role supported, Central Role preferred for connection establishment. */ + NDEF_BLE_ROLE_UNDEF = 0xff /**< LE Role is undefined. */ +} Ndef_BLE_Role_t; + +/** @brief Enumerates Bluetooth protocols */ +typedef enum { + NDEF_BLUETOOTH_BREDR, /**< Standard bluetooth */ + NDEF_BLUETOOTH_BLE /**< Bluetooth Low Energy */ +} Ndef_Bluetooth_type_t; + +/** @brief Helper macro to set a particular EIR in the EIR mask of a `Ndef_Bluetooth_OOB_t` instance. + * @param bt Pointer to a `Ndef_Bluetooth_OOB_t` struct + * @param option Index of the option based on the `Ndef_Bluetooth_Eir_Types_t` */ +#define NDEF_BLUETOOTH_SET_OPTIONAL_MASK(bt,option) do { bt->OptionalMask |= (1<<(option)); } while (0) + +/** @brief Helper macro to unset a particular EIR in the EIR mask of a `Ndef_Bluetooth_OOB_t` instance. + * @param bt Pointer to a `Ndef_Bluetooth_OOB_t` struct + * @param option Index of the option based on the `Ndef_Bluetooth_Eir_Types_t` */ +#define NDEF_BLUETOOTH_UNSET_OPTIONAL_MASK(bt,option) do {bt->OptionalMask &= ~(1<<(option)); } while (0) + +/** @brief Helper macro to know if a particular EIR is present in the EIR mask of a `Ndef_Bluetooth_OOB_t` instance. + * @param bt Pointer to a `Ndef_Bluetooth_OOB_t` struct + * @param option Index of the option based on the `Ndef_Bluetooth_Eir_Types_t` */ +#define NDEF_BLUETOOTH_GET_OPTIONAL_MASK(bt,option) ((bt->OptionalMask & (1<<(option))) >> (option)) + +/** @brief Helper macro to create a mask for a particular EIR. + * @param option Index of the option based on the `Ndef_Bluetooth_Eir_Types_t` */ +#define NDEF_BLUETOOTH_OPTION(option) (1<<(option)) + +/** @brief Bluetooth Out-Of-Band data structure. + * @details Some fields are shared by both Br/Edr & LE Bluetooth, some are specific... + * No union used here to comply with the Cube coding guidelines, despite the fact that it could have save memory space. + */ +typedef struct +{ + /* Mandatory fields */ + Ndef_Bluetooth_type_t Type; /**< *Mandatory*: Bluetooth type (Br/Edr or LE). */ + char DeviceAddress[6]; /**< *Mandatory*: Device address. For LE: 6 LSB of Device Address EIR. */ + /* Optionnal common fields */ + uint32_t OptionalMask; /**< This Mask is used to keep track of EIRs present in the OOB: each bit index corresponds to a `Ndef_Bluetooth_Eir_Types_t` value. */ + uint8_t Flags; /**< Flags from BLUETOOTH_EIR_FLAGS. */ + + uint16_t ClassUUID16[0xff/2]; /**< UUIDs from BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_16 or BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_16. */ + uint32_t ClassUUID32[0xff/4]; /**< UUIDs from BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_32 or BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_32. */ + uint32_t ClassUUID128[0xff/16][4]; /**< UUIDs from BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_128 or BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_128. */ + uint8_t nbUUID16; /**< Number of UUIDs speficied in ClassUUID16. */ + uint8_t nbUUID32; /**< Number of UUIDs speficied in ClassUUID32. */ + uint8_t nbUUID128; /**< Number of UUIDs speficied in ClassUUID128. */ + + char LocalName[0xff]; /**< Device local name from BLUETOOTH_EIR_SHORT_LOCAL_NAME or BLUETOOTH_EIR_COMPLETE_LOCAL_NAME. */ + uint8_t DeviceClass[3]; /**< Class of device from BLUETOOTH_EIR_DEVICE_CLASS. */ + // if no TPL, TPL is unknown + uint8_t TxPowerLevel; /**< TX power Level from BLUETOOTH_EIR_TX_POWER_LEVEL. */ + + uint8_t SMFlags; /**< Security Manager Flags from BLUETOOTH_EIR_SECURITY_MANAGER_FLAGS. */ + uint16_t SlaveConnIntervalRange[2]; /**< Slave Connection Interval Range from BLUETOOTH_EIR_SLAVE_CONNECTION_INTERVAL_RANGE. */ + uint16_t ServiceSolicitation16[0xff/2]; /**< Service Solicitation from BLUETOOTH_EIR_SERVICE_SOLICITATION_16. */ + uint32_t ServiceSolicitation128[0xff/16][4]; /**< Service Solicitation from BLUETOOTH_EIR_SERVICE_SOLICITATION_128. */ + uint8_t nbServiceSolicitation16; /**< Number of UUIDs in ServiceSolicitation16. */ + uint8_t nbServiceSolicitation128; /**< Number of UUIDs in ServiceSolicitation128. */ + /* for br/edr only */ + uint8_t SimplePairingHash[16]; /**< *For Br/Edr only*: Simple Pairing Hash from BLUETOOTH_EIR_SIMPLE_PAIRING_HASH. */ + uint8_t SimplePairingRandomizer[16]; /**< *For Br/Edr only*: Simple Pairing Randomizer from BLUETOOTH_EIR_SIMPLE_PAIRING_RANDOMIZER. */ + /* BLE mandatory fields */ + Ndef_BLE_Address_Type_t DeviceAddressType; /**< *For LE only*, *Mandatory*: Address Type, MSB of the Device Address EIR (Public or Random) */ + Ndef_BLE_Role_t Role; /**< *For LE only*, *Mandatory*: LE Role from BLUETOOTH_EIR_BLE_ROLE and defined in `Ndef_BLE_Role_t`. */ + /* BLE optional fields */ + uint8_t SecureManagerTK[16]; /**< *For LE only*: Security Manager TK from BLUETOOTH_EIR_SECURITY_MANAGER_TK_VALUE. */ + uint16_t Appearance; /**< *For LE only*: Appearance from BLUETOOTH_EIR_APPEARANCE. */ + /* track number of unparsed EIR */ + uint8_t nbUnknown; /**< Number of EIRs not parsed because of an unknown EIR type. */ + uint8_t nbServiceData; /**< Number of EIRs not parsed because being of type BLUETOOTH_EIR_SERVICE_DATA. */ + uint8_t nbManufacturerData; /**< Number of EIRs not parsed because being of type BLUETOOTH_EIR_MANUFACTURER_DATA. */ +} Ndef_Bluetooth_OOB_t ; + +/** @brief Extended Inquiry Response format. + * @details This structure is used to parse/build EIRs in the Bluetooth OOB. + */ +typedef struct { + uint8_t length; /**< Length of the EIRs, including the type field (1 byte). */ + uint8_t type; /**< EIR type as defined in `Ndef_Bluetooth_Eir_Types_t`. */ + uint8_t value[1]; /**< single-element array, to keep track of the address of the EIR data */ +} NDEF_EIR_t ; + +uint16_t NDEF_ReadBluetoothOOB( sRecordInfo_t *pRecordStruct, Ndef_Bluetooth_OOB_t *pBluetooth ); +uint16_t NDEF_AppendBluetoothOOB( Ndef_Bluetooth_OOB_t *pBluetooth, char* RecordID ); +void NDEF_PrepareBluetoothMessage(Ndef_Bluetooth_OOB_t *pBluetooth, uint8_t *pNDEFMessage, uint16_t *size ); +uint32_t NDEF_GetBluetoothOOBLength( Ndef_Bluetooth_OOB_t *pBluetooth ); + +#ifdef __cplusplus +} +#endif + +/** @} + */ + +#endif /* __LIB_NDEF_BLUETOOTH_H */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Email.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Email.h new file mode 100644 index 0000000..f9d24f8 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Email.h @@ -0,0 +1,71 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Email.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage Email NDEF file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_EMAIL_H +#define __LIB_NDEF_EMAIL_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + +/* "mailto:customer.service@st.com?subject=M24SR S/N 754FHFGJF46G329 WARRANTY&body=this is an auomatic warranty activation email" */ + +#ifdef NDEF_DYN_ALLOC +typedef struct +{ + char *EmailAdd; + char *Subject; + char *Message; + char *Information; +}sEmailInfo; +#else +typedef struct +{ + char EmailAdd[64]; + char Subject[100]; + char Message[2000]; + char Information[400]; +}sEmailInfo; +#endif +uint16_t NDEF_ReadEmail( sRecordInfo_t *pRecordStruct, sEmailInfo *pEmailStruct ); +uint16_t NDEF_WriteEmail( sEmailInfo *pEmailStruct ); +void NDEF_PrepareEmailMessage( sEmailInfo *pEmailStruct, uint8_t *pNDEFMessage, uint16_t *size ); +void NDEF_closeEmail( sEmailInfo *pEmailStruct); + +#ifdef __cplusplus +} +#endif + +#endif /* __LIB_NDEF_EMAIL_H */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Geo.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Geo.h new file mode 100644 index 0000000..6b4b47d --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Geo.h @@ -0,0 +1,58 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Geo.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage Geolocation NDEF file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_GEO_H +#define __LIB_NDEF_GEO_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + +typedef struct +{ + char Latitude[20]; + char Longitude[20]; + char Information[100]; +}sGeoInfo; + +uint16_t NDEF_ReadGeo( sRecordInfo_t *pRecordStruct, sGeoInfo *pGeoStruct ); +uint16_t NDEF_WriteGeo( sGeoInfo *pGeoStruct ); +void NDEF_PrepareGeoMessage( sGeoInfo *pGeoStruct, uint8_t *pNDEFMessage, uint16_t *size ); + +#ifdef __cplusplus +} +#endif + +#endif /* __LIB_NDEF_GEO_H */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Handover.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Handover.h new file mode 100644 index 0000000..49069fe --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Handover.h @@ -0,0 +1,122 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Bluetooth.h + * @author MMY Application Team + * @version $Revision: 2475 $ + * @date $Date: 2016-06-24 12:11:59 +0200 (Fri, 24 Jun 2016) $ + * @brief This file help to manage Bluetooth NDEF file. + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_HANDOVER_H +#define __LIB_NDEF_HANDOVER_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + + +/** @addtogroup lib_NDEF_Handover NDEF Handover library + * @{ + */ + +/** @brief SIze of the buffer used to store an Alternative Carrier (allocated on the stack). + * @details 128 bytes should be enough, the specification recommends to use short URIs as AC identifiers. + */ +#define NDEF_AC_BUFFER_SIZE (128) + +/** @brief NFC Forum Well-Known Type name for a Handover Select record */ +#define NDEF_HANDOVER_SELECT_TYPE_STR "Hs" +/** @brief NFC Forum Well-Known Type name for a Handover Request record */ +#define NDEF_HANDOVER_REQUEST_TYPE_STR "Hr" +/** @brief NFC Forum Well-Known Type name for a Handover Select Select (ascii value) */ +#define NDEF_HANDOVER_SELECT_TYPE 0x4872 +/** @brief NFC Forum Well-Known Type name for a Handover Request record (ascii value) */ +#define NDEF_HANDOVER_REQUEST_TYPE 0x4873 +/** @brief NFC Forum Handover record implemented version */ +#define NDEF_HANDOVER_VERSION_1_2 0x12 + +/** @brief NFC Forum Well-Known Type name for a Colision Resolution record */ +#define NDEF_HANDOVER_COLLISION_RESOLUTION_TYPE_STR "cr" +/** @brief NFC Forum Well-Known Type name for an Alternative Carrier record */ +#define NDEF_HANDOVER_ALTERNATIVE_CARRIER_TYPE_STR "ac" + +/** @brief NFC Forum Power States values mask */ +#define NDEF_HANDOVER_AC_CPS_MASK (0x3) +/** @brief Enumerates the NFC Forum Power States possible values */ +typedef enum { + NDEF_HANDOVER_AC_CPS_INACTIVE = 0x0, /**< The HW for this Alternative Carrier has to be switch on before proceeding. */ + NDEF_HANDOVER_AC_CPS_ACTIVE = 0x1, /**< The HW for this Alternative Carrier is currently running. */ + NDEF_HANDOVER_AC_CPS_ACTIVATING = 0x2, /**< The HW for this Alternative Carrier is being activated. */ + NDEF_HANDOVER_AC_CPS_UNKNOWN = 0x3 /**< The HW for this Alternative Carrier is unknown. */ +} Ndef_Handover_ac_cps_t; + + + +typedef struct { + uint8_t cps; /**< Current Power State for this Alternative Carrier Hardware. */ + sRecordInfo_t ac_record; /**< The record structure used to store/build the Alternative Carrier record. */ + uint8_t aux_data_ref_count; /**< The number of Auxiliary Data Reference for this Alternative Carrier. */ + /* following fields are only used when reading NDEF */ + uint8_t* aux_data_ref_start; /**< Internal field, managed by the library, to keep track of the Auxiliary Data Reference start address in the AC record. */ + uint8_t* aux_data_ref_end; /**< Internal field, managed by the library, to keep track of the Auxiliary Data Reference end address in the AC record. */ +} Ndef_Handover_alternative_carrier_t; + + +typedef struct { + uint16_t type; /**< Handover type: could be Select or Request. */ + uint8_t version; /**< Version of the Handover record. */ + /* following fields are only used when reading NDEF */ + uint8_t has_cr; /**< Boolean, if true this Handover has a Collision Resolution nested record. */ + uint16_t cr_random_number; /**< Random number for the Collision Resolution. */ + uint8_t nb_alternative_carrier; /**< Number of Alternative Carrier nested records un this Handover. */ + uint8_t* ac_start; /**< Internal field, managed by the library, to keep track of the Alternative Carrier Reference Data start address in the Handover record. */ + uint8_t* ac_end; /**< Internal field, managed by the library, to keep track of the Alternative Carrier Reference Data end address in the Handover record. */ +} Ndef_Handover_t; + + + +uint16_t NDEF_ReadHandover(sRecordInfo_t *pRecord , Ndef_Handover_t *pHandover ); +uint16_t NDEF_ReadAC( uint8_t ac_nb, Ndef_Handover_t *pHandover , Ndef_Handover_alternative_carrier_t *pAC ); +uint16_t NDEF_ReadAuxData( uint8_t aux_data_nb, Ndef_Handover_alternative_carrier_t *pAC, sRecordInfo_t *pRecord ); + +uint16_t NDEF_CreateHandover(Ndef_Handover_t *pHandover, sRecordInfo_t* pRecord ); +uint16_t NDEF_AddAlternativeCarrier(Ndef_Handover_alternative_carrier_t *pAC, char* CarrierDataRef, char **AuxDataRefID, sRecordInfo_t* pRecord ); +uint16_t NDEF_WriteHandover( sRecordInfo_t* pRecord , uint8_t* pNdef); + +uint32_t NDEF_GetACDataLength(Ndef_Handover_alternative_carrier_t *pAC,char *CarrierDataRef, char **AuxDataRefID); + + +#ifdef __cplusplus +} +#endif + +/** @} + */ + +#endif /* __LIB_NDEF_HANDOVER_H */ + +/******************* (C) COPYRIGHT 2016 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_MyApp.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_MyApp.h new file mode 100644 index 0000000..26c56c4 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_MyApp.h @@ -0,0 +1,89 @@ +/** + ****************************************************************************** + * @file lib_NDEF_MyApp.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file illustrate how to use M24SR with a proprietary protocol. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_MYAPP_H +#define __LIB_NDEF_MYAPP_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + +#define BLINK_CONFIG "" +#define BLINK_CONFIG_STRING_SIZE 14 +#define BLINK_CONFIG_END "<\\BLINK_CONFIG>" +#define BLINK_CONFIG_END_STRING_SIZE 15 + +#define LINE_DESCR "" +#define LINE_DESCR_STRING_SIZE 12 +#define LINE_DESCR_END "<\\LINE_DESCR>" +#define LINE_DESCR_END_STRING_SIZE 13 + +#define BLINKING_NONE 0x00 +#define BLINKING_SLOW 0x01 +#define BLINKING_MEDIUM 0x02 +#define BLINKING_FAST 0x03 + +#define MYAPP_NB_LINES ((uint8_t)8) +#define MYAPP_LED_CONF_INITAL_STATE ((uint8_t) 0x1) +#define MYAPP_LED_CONF_BLINKING ((uint8_t) 0x2) + +typedef struct +{ + uint8_t LedConf[4]; + uint8_t Speed; +}sLedBlinkConfig; + +typedef struct +{ + uint8_t LineNb; + uint16_t BackGroundColor; + uint16_t FontColor; + char String[20]; +}sLineConfig; + +typedef struct +{ + sLedBlinkConfig LedBlinkConf; + sLineConfig LineX[MYAPP_NB_LINES]; +}sMyAppInfo; + +uint16_t NDEF_ReadMyApp( sRecordInfo_t *pRecordStruct, sMyAppInfo *pMyAppStruct ); +uint16_t NDEF_WriteMyApp( sMyAppInfo *pMyAppStruct ); + +#ifdef __cplusplus +} +#endif + +#endif /* __LIB_NDEF_MYAPP_H */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_SMS.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_SMS.h new file mode 100644 index 0000000..e697b1d --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_SMS.h @@ -0,0 +1,59 @@ +/** + ****************************************************************************** + * @file lib_NDEF_SMS.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage SMS NDEF file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_SMS_H +#define __LIB_NDEF_SMS_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + + +typedef struct +{ + char PhoneNumber[16]; + char Message[400]; + char Information[400]; +}sSMSInfo; + +uint16_t NDEF_ReadSMS( sRecordInfo_t *pRecordStruct, sSMSInfo *pSMSStruct ); +uint16_t NDEF_WriteSMS( sSMSInfo *pSMSStruct ); +void NDEF_PrepareSMSMessage( sSMSInfo *pSMSStruct, uint8_t *pNDEFMessage, uint16_t *size ); + +#ifdef __cplusplus +} +#endif + +#endif /* __LIB_NDEF_SMS_H */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Text.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Text.h new file mode 100644 index 0000000..12ec08d --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Text.h @@ -0,0 +1,84 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Text.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage Text NDEF file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_TEXT_H +#define __LIB_NDEF_TEXT_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + +/** @brief NDEF Text buffer length. */ +#define NDEF_TEXT_MAX_LENGTH 40 +/** @brief NDEF Language code buffer length. */ +#define NDEF_TEXT_LANGUAGE_CODE_MAX_LENGTH 10 + +/** @brief NDEF Text encoding possible values. */ +typedef enum { + NDEF_TEXT_UTF8 = 0, + NDEF_TEXT_UTF16 = 1 +} NDEF_Text_encoding_t; + +/** @brief This structure is used to handle information from a NDEF Text record. */ +#ifdef NDEF_DYN_ALLOC + typedef struct { + NDEF_Text_encoding_t encoding; /**< metadata: UTF-8 / UTF-16. */ + char language_code[NDEF_TEXT_LANGUAGE_CODE_MAX_LENGTH]; /**< metadata: Language code as specified by IANA. */ + char *text; /**< The text itself. */ + } NDEF_Text_info_t; +#else + typedef struct { + NDEF_Text_encoding_t encoding; /**< metadata: UTF-8 / UTF-16. */ + char language_code[NDEF_TEXT_LANGUAGE_CODE_MAX_LENGTH]; /**< metadata: Language code as specified by IANA. */ + char text[NDEF_TEXT_MAX_LENGTH]; /**< The text itself. */ + } NDEF_Text_info_t; +#endif + +/** @brief This structure is used to parse the raw data from a text record and access its metadata. */ +typedef struct { + uint8_t language_length:4; /**< Language code length. */ + uint8_t rfu:3; /**< reserved for futur usage */ + uint8_t encoding:1; /**< UTF-8 (0) or UTF-16 (1) encoding. */ + char language[1]; /**< IANA language code. */ +} NDEF_Text_metadata_t; + +uint16_t NDEF_WriteText( char *text ); +uint16_t NDEF_ReadText( sRecordInfo_t *pRecordStruct, NDEF_Text_info_t *pText ); + +#ifdef __cplusplus +} +#endif + +#endif /* __LIB_NDEF_TEXT_H */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_URI.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_URI.h new file mode 100644 index 0000000..35f26b5 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_URI.h @@ -0,0 +1,60 @@ +/** + ****************************************************************************** + * @file lib_NDEF_URI.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage URI NDEF file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_URI_H +#define __LIB_NDEF_URI_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + +typedef struct +{ + char protocol[80]; + char URI_Message[400]; + char Information[400]; +}sURI_Info; + +uint16_t NDEF_ReadURI(sRecordInfo_t *pRecordStruct, sURI_Info *pURI); +uint16_t NDEF_WriteURI(sURI_Info *pURI); + +void NDEF_PrepareURIMessage( sURI_Info *pURI, uint8_t *pNDEFMessage, uint16_t *size ); +char getUriType( char *protocol ); + +#ifdef __cplusplus +} +#endif + +#endif /* __LIB_NDEF_URI_H */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Vcard.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Vcard.h new file mode 100644 index 0000000..fe2a15f --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Vcard.h @@ -0,0 +1,129 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Vcard.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage Vcard NDEF file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_VCARD_H +#define __LIB_NDEF_VCARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + + +#define VCARD_VERSION_2_1 "2.1" +#define VCARD_VERSION_2_1_SIZE 3 + +#define VCARD_VERSION_3_0 "3.0" +#define VCARD_VERSION_3_0_SIZE 3 + + +#define BEGIN "BEGIN:" +#define VCARD "VCARD" +#define VERSION "VERSION:" +#define VCARD_NAME "N:" + // TODO: rename FIRSTNAME into FORMATTEDNAME +#define FIRSTNAME "FN:" +#define HOME_TEL "TEL;HOME:" +#define WORK_TEL "TEL;WORK:" +#define CELL_TEL "TEL;CELL:" +#define HOME_EMAIL "EMAIL;HOME:" +#define WORK_EMAIL "EMAIL;WORK:" +#define GEN_EMAIL "EMAIL:" +#define HOME_ADDRESS "ADR;HOME:" +#define WORK_ADDRESS "ADR;WORK:" +#define GEN_ADDRESS "ADR:" +#define TITLE "TITLE:" +#define ORG "ORG:" +#define URL "URL:" +#define END "END:" +#define JPEG "JPEG" +#define PICTURE_PHOTO "PHOTO;" +#define PICTURE_BASE64 "ENCODING=BASE64" + +#define LIMIT "\r\n" + +#define BEGIN_STRING_SIZE 6 +#define VCARD_STRING_SIZE 5 +#define VERSION_STRING_SIZE 8 +#define VCARD_NAME_STRING_SIZE 2 + // TODO: rename FIRSTNAME into FORMATTEDNAME +#define FIRSTNAME_STRING_SIZE 3 +#define HOME_TEL_STRING_SIZE 9 +#define WORK_TEL_STRING_SIZE 9 +#define CELL_TEL_STRING_SIZE 9 +#define HOME_EMAIL_STRING_SIZE 11 +#define WORK_EMAIL_STRING_SIZE 11 +#define HOME_ADDRESS_STRING_SIZE 9 +#define WORK_ADDRESS_STRING_SIZE 9 +#define TITLE_STRING_SIZE 6 +#define ORG_STRING_SIZE 4 +#define URL_STRING_SIZE 4 +#define END_STRING_SIZE 4 +#define JPEG_STRING_SIZE 4 + +#define LIMIT_STRING_SIZE 2 + +typedef struct +{ + char Version [10]; + char Name[80]; + // TODO: rename FirstName into FormattedName + char FirstName[80]; + char Title[80]; + char Org[80]; + char HomeAddress[80]; + char WorkAddress[80]; + char Address[80]; + char HomeTel[40]; + char WorkTel[40]; + char CellTel[40]; + char HomeEmail[80]; + char WorkEmail[80]; + char Email[80]; + char Url[80]; + char *Picture; + uint32_t PictureSize; +}sVcardInfo; + +uint16_t NDEF_ReadVcard( sRecordInfo_t *pRecordStruct, sVcardInfo *pVcardStruct ); +uint16_t NDEF_WriteVcard( sVcardInfo *pVcardStruct ); +void NDEF_PrepareVcardMessage( sVcardInfo *pVcardStruct, uint8_t *pNDEFMessage, uint16_t *size ); +int NDEF_getVcardPicture( uint8_t* pPayload, uint32_t PayloadSize, uint8_t* pPict ); + +#ifdef __cplusplus +} +#endif + +#endif /* __LIB_NDEF_VCARD_H */ + + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Wifi.h b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Wifi.h new file mode 100644 index 0000000..d456ef0 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_NDEF_Wifi.h @@ -0,0 +1,118 @@ +/** + ****************************************************************************** + * @file lib_NDEF_WifiToken.h + * @author Central LAB + * @version $Revision:$ + * @date $Date:$ + * @brief This file helps to manage the NDEF message representing a Wifi Token. + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_NDEF_WIFIT_H +#define __LIB_NDEF_WIFIT_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" + +/** @addtogroup lib_NDEF_Wifi Wifi OOB library (WPS) + * @ingroup libNDEF + * @{ + */ + + +/* Exported types ------------------------------------------------------------*/ +/** @brief This index points to the position of the credential length value in Token1. + * Its value may require to be updated if the token1 is modified. + */ +#define CONFIG_TOKEN_1_CREDENTIAL_LENGTH_INDEX 7 + +/** @brief This index points to the position of the Authentication type value in Token3. + * Its value may require to be updated if the token3 is modified. + */ +#define CONFIG_TOKEN_3_AUTHENTICATION_TYPE_INDEX ((uint32_t)5) +/** @brief This index points to the position of the Encryption type value in Token3. + * Its value may require to be updated if the token3 is modified. + */ +#define CONFIG_TOKEN_3_ENCRYPTION_TYPE_INDEX ((uint32_t)11) + +/** @brief MIME type for the Wifi OOB token. + */ +#define WIFITOKEN_TYPE_STRING "application/vnd.wfa.wsc" +/** @brief Length of the MIME type for the Wifi OOB token. + */ +#define WIFITOKEN_TYPE_STRING_LENGTH ((uint32_t)23) + +/** + * @brief Network key to be used when the Authentication is set to None. + * Althought WPS defines a 0 length network key in such case, + * with tested phones a 8 digit value is required. + */ +#define NDEF_WIFI_DEFAULT_NETWORK_KEY "00000000" + +typedef enum { + NDEF_WIFI_ENCRYPTION_NONE = 0x0000, /**< WPS No Encryption (set to 0 for Android native support / should be 1) */ + NDEF_WIFI_ENCRYPTION_WEP = 0x0002, /**< WPS Encryption based on WEP */ + NDEF_WIFI_ENCRYPTION_TKIP = 0x0003, /**< WPS Encryption based on TKIP */ + NDEF_WIFI_ENCRYPTION_AES = 0x0004 /**< WPS Encryption based on AES */ +} Ndef_Wifi_Encryption_t; + +typedef enum { + NDEF_WIFI_AUTHENTICATION_NONE = 0x0000, /**< WPS No Authentication (set to 0 for Android native support / should be 1) */ + NDEF_WIFI_AUTHENTICATION_WPAPSK = 0x0002, /**< WPS Authentication based on WPAPSK */ + NDEF_WIFI_AUTHENTICATION_SHARED = 0x0003, /**< WPS Authentication based on ?? */ + NDEF_WIFI_AUTHENTICATION_WPA = 0x0004, /**< WPS Authentication based on WPA */ + NDEF_WIFI_AUTHENTICATION_WPA2 = 0x0005, /**< WPS Authentication based on WPA2 */ + NDEF_WIFI_AUTHENTICATION_WPA2PSK = 0x0006 /**< WPS Authentication based on WPA2PSK */ +} Ndef_Wifi_Authentication_t; + +/** + * @brief WifiToken structure, to store Network SSID, Authentication Type, Encryption Type and Network Key. + */ +typedef struct +{ + char NetworkSSID[32]; /**< Store the Network SSID. */ + Ndef_Wifi_Authentication_t AuthenticationType; /**< Store the Authentication type to be used. */ + Ndef_Wifi_Encryption_t EncryptionType; /**< Store the Encryption to be used. */ + char NetworkKey[32]; /**< Store the Network Key. */ +}sWifiTokenInfo; + + +uint16_t NDEF_ReadWifiToken(struct sRecordInfo *pRecordStruct, sWifiTokenInfo *pWifiTokenStruct); +uint16_t NDEF_WriteWifiToken( sWifiTokenInfo *pWifiTokenStruct ); + +/** + * @} + */ + + +#ifdef __cplusplus +} +#endif + +#endif /* __LIB_NDEF_WIFIT_H */ + +/******************* (C) COPYRIGHT 2016 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/inc/lib_wrapper.h b/src/hydranfc_v2/lib/ndef/inc/lib_wrapper.h new file mode 100644 index 0000000..6f5fc5b --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/inc/lib_wrapper.h @@ -0,0 +1,57 @@ +/** + ****************************************************************************** + * @file lib_wrapper.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to have upper layer independent from HW + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __LIB_WRAPPER_H +#define __LIB_WRAPPER_H + +/* Includes ------------------------------------------------------------------*/ +#include "hydranfc_v2_common.h" +#include "st25r.h" + +typedef enum { + NFCTAG_TYPE5 = 0, + NFCTAG_TYPE4, + NFCTAG_TYPE3, + NFCTAG_TYPE2, + NFCTAG_TYPE1, + NFCTAG_NOTSET +} NFCTAG_Protocol_Id_t; + + +uint16_t NfcTag_SelectProtocol(NFCTAG_Protocol_Id_t protocol); +uint16_t NfcTag_ReadNDEF( uint8_t* pData ); +uint16_t NfcTag_WriteNDEF(uint16_t Length, uint8_t* pData ); +uint16_t NfcTag_WriteProprietary(uint16_t Length, uint8_t* pData ); +uint16_t NfcTag_GetLength(uint16_t* Length); + +#endif /* __LIB_WRAPPER_H */ + + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF.c new file mode 100644 index 0000000..1ed7174 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF.c @@ -0,0 +1,748 @@ +/** + ****************************************************************************** + * @file lib_NDEF.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage NDEF file, to parse and identify them. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF.h" +#include "lib_NDEF_Bluetooth.h" +#include "lib_NDEF_Handover.h" +#include "lib_NDEF_Wifi.h" + +/** @addtogroup NFC_libraries + * @{ + * @brief This is the library used to manage the content of the TAG (data) + * But also the specific feature of the tag, for instance + * password, gpo... + */ + + +/** @addtogroup libNFC_FORUM + * @{ + * @brief This part of the library manage data which follow NFC forum organisation. + */ + +/** @defgroup libNDEF_Private_Functions + * @{ + */ + + +static uint16_t NDEF_IsNDEFPresent( void ); +static uint16_t NDEF_ParseRecordHeader( sRecordInfo_t *pRecordStruct ); +static void NDEF_ParseWellKnownType( sRecordInfo_t *pRecordStruct ); +static void NDEF_ParseMediaType( sRecordInfo_t *pRecordStruct ); +static void NDEF_ParseForumExternalType( sRecordInfo_t *pRecordStruct ); +static void NDEF_ParseURI( sRecordInfo_t *pRecordStruct ); +static void NDEF_ParseSP( sRecordInfo_t *pRecordStruct ); +static uint16_t NDEF_IdentifySPRecord( sRecordInfo_t *pRecordStruct, uint8_t* pPayload ); + +/** @brief This buffer is used to store the data sent/received by the TAG. */ +uint8_t NDEF_Buffer [NDEF_MAX_SIZE]; +/** @brief Size of the buffer used to build the NDEF messages. */ +uint32_t NDEF_Buffer_size = NDEF_MAX_SIZE; +/** @brief This buffer is used when it's required to prepare a record before adding it to the NDEF_Buffer. */ +uint8_t NDEF_Record_Buffer [NDEF_RECORD_MAX_SIZE]; +/** @brief Size of the buffer used when a record has to be prepared. */ +uint32_t NDEF_Record_Buffer_size = NDEF_RECORD_MAX_SIZE; + +/* In case of smart Poster composed with different record, 3 records supported so far */ +sRecordInfo_t SPRecordStruct1, SPRecordStruct2, SPRecordStruct3, SPRecordStruct4; +sRecordInfo_t *SPRecordStructAdd[SP_MAX_RECORD] = { &SPRecordStruct1, &SPRecordStruct2, &SPRecordStruct3, &SPRecordStruct4 }; + +/** + * @brief This function checks that the tag contain a NDEF message. + * @retval NDEF_OK : There is a NDEF file stored in tag. + * @retval NDEF_ERROR : No NDEF in the tag. + */ +static uint16_t NDEF_IsNDEFPresent( void ) +{ + uint16_t FileSize; + + /* Check NDEF existence */ + NfcTag_GetLength(&FileSize); + + if( FileSize != 0 ) + return NDEF_OK; + else + return NDEF_ERROR; +} + +/** + * @brief This function identify the type of record. + * @param pRecordStruct : pointer on the record structure to fill. + * @param pPayload : pointer on the payload. + * @retval Status : Status of the operation. + */ +static uint16_t NDEF_IdentifySPRecord( sRecordInfo_t *pRecordStruct, uint8_t* pPayload ) +{ + uint16_t status = NDEF_ERROR; + uint16_t SizeOfRecordHeader, TypeNbByte, PayloadLengthField, IDLengthField, IDNbByte; + + /* Is ID length field present */ + if( (*pPayload) & IL_Mask ) + { + IDLengthField = ID_LENGTH_FIELD; + } + else + { + IDLengthField = 0; + } + + /* it's a SR */ + if( (*pPayload) & SR_Mask ) + { + TypeNbByte = pPayload[1]; + PayloadLengthField = 1; + if( IDLengthField == ID_LENGTH_FIELD ) + IDNbByte = pPayload[3]; + else + IDNbByte = 0; + } + else + { + TypeNbByte = pPayload[1]; + PayloadLengthField = 4; + if( IDLengthField == ID_LENGTH_FIELD ) + IDNbByte = pPayload[6]; + else + IDNbByte = 0; + } + + SizeOfRecordHeader = RECORD_FLAG_FIELD + TYPE_LENGTH_FIELD + PayloadLengthField + IDLengthField + TypeNbByte + IDNbByte; + + /* it's a SR */ + if( pPayload[0] & SR_Mask ) + { + pRecordStruct->RecordFlags = pPayload[0]; + pRecordStruct->TypeLength = TypeNbByte; + pRecordStruct->PayloadLength = pPayload[2]; + pRecordStruct->IDLength = IDNbByte; + memcpy( pRecordStruct->Type, &pPayload[3+IDLengthField], TypeNbByte ); + memcpy( pRecordStruct->ID, &pPayload[3+IDLengthField+TypeNbByte], IDNbByte ); + pRecordStruct->PayloadOffset = SizeOfRecordHeader; + } + else + { + pRecordStruct->RecordFlags = pPayload[0]; + pRecordStruct->TypeLength = TypeNbByte; + pRecordStruct->PayloadLength = ( ((uint32_t)pPayload[2]) << 24 ) | + ( ((uint32_t)pPayload[3]) << 16 ) | + ( ((uint32_t)pPayload[4]) << 8 ) + | pPayload[5] ; + pRecordStruct->IDLength = IDNbByte; + memcpy( pRecordStruct->Type, &pPayload[6+IDLengthField], TypeNbByte ); + memcpy( pRecordStruct->ID, &pPayload[6+IDLengthField+TypeNbByte], IDNbByte ); + pRecordStruct->PayloadOffset = SizeOfRecordHeader; + } + + pRecordStruct->PayloadBufferAdd = pPayload + SizeOfRecordHeader ; + + status = NDEF_ParseRecordHeader( pRecordStruct ); + + return status; +} + +/** + * @brief This function parse the record header and dispatch regarding TNF value. + * @param pRecordStruct : pointer on the record structure to fill. + * @retval NDEF_OK : record identified and structure filled. + * @retval NDEF_ERROR : Not supported. + */ +static uint16_t NDEF_ParseRecordHeader( sRecordInfo_t *pRecordStruct ) +{ + uint16_t status = NDEF_OK; + + switch( (pRecordStruct->RecordFlags & TNF_Mask) ) + { + case TNF_WellKnown: + NDEF_ParseWellKnownType( pRecordStruct ); + break; + + case TNF_MediaType: + NDEF_ParseMediaType( pRecordStruct ); + break; + + case TNF_NFCForumExternal: + NDEF_ParseForumExternalType( pRecordStruct); + break; + + default: + /* currently not supported or unknown*/ + pRecordStruct->NDEF_Type = UNKNOWN_TYPE; + status = NDEF_ERROR; + } + return status; +} + +/** + * @brief This function parse the Well Known type record. + * @param pRecordStruct : pointer on the record structure to fill. + */ +static void NDEF_ParseWellKnownType( sRecordInfo_t *pRecordStruct ) +{ + uint8_t* pPayload; + + pPayload = (uint8_t*)( pRecordStruct->PayloadBufferAdd ); + + if( !memcmp( &(pRecordStruct->Type), SMART_POSTER_TYPE_STRING, pRecordStruct->TypeLength ) ) + { + /* special case where we have to parse others records */ + pRecordStruct->NDEF_Type = SMARTPOSTER_TYPE; + NDEF_ParseSP( pRecordStruct ); + } + + else if( !memcmp( &(pRecordStruct->Type), URI_TYPE_STRING, pRecordStruct->TypeLength ) ) + { + /* it's an URI Type check if it's an URL or SMS or ... */ + /* check identifier */ + if( *pPayload == URI_ID_0x00 ) + { + NDEF_ParseURI( pRecordStruct ); + } + else if( (*pPayload > URI_ID_0x00) && (*pPayload < URI_RFU) ) + { + /* email special case */ + if( *pPayload == (uint8_t) URI_ID_0x06 ) + { + pRecordStruct->NDEF_Type = URI_EMAIL_TYPE; + } + else + { + pRecordStruct->NDEF_Type = WELL_KNOWN_ABRIDGED_URI_TYPE; + } + } + else + { + pRecordStruct->NDEF_Type = UNKNOWN_TYPE; + } + } + + else if( !memcmp( &(pRecordStruct->Type), TEXT_TYPE_STRING, pRecordStruct->TypeLength ) ) + { + pRecordStruct->NDEF_Type = TEXT_TYPE; + } else if ((!memcmp( &(pRecordStruct->Type), NDEF_HANDOVER_SELECT_TYPE_STR, pRecordStruct->TypeLength )) || + (!memcmp( &(pRecordStruct->Type), NDEF_HANDOVER_REQUEST_TYPE_STR, pRecordStruct->TypeLength ) )) + { + pRecordStruct->NDEF_Type = HANDOVER_TYPE; + } + else + pRecordStruct->NDEF_Type = UNKNOWN_TYPE; +} + +/** + * @brief This function parse the Media type record. + * @param pRecordStruct : pointer on the record structure to fill. + */ +static void NDEF_ParseMediaType( sRecordInfo_t *pRecordStruct ) +{ + if( !memcmp( &(pRecordStruct->Type), VCARD_TYPE_STRING, pRecordStruct->TypeLength ) ) + pRecordStruct->NDEF_Type = VCARD_TYPE; + else if( !memcmp( &(pRecordStruct->Type), XVCARD_TYPE_STRING, pRecordStruct->TypeLength ) ) + pRecordStruct->NDEF_Type = VCARD_TYPE; + else if( !memcmp( &(pRecordStruct->Type), XVCARD2_TYPE_STRING, pRecordStruct->TypeLength ) ) + pRecordStruct->NDEF_Type = VCARD_TYPE; + else if (!memcmp(&pRecordStruct->Type, NDEF_BLUETOOTH_BREDR_MIME_TYPE, pRecordStruct->TypeLength)) + pRecordStruct->NDEF_Type = BT_TYPE; + else if (!memcmp(&pRecordStruct->Type, NDEF_BLUETOOTH_BLE_MIME_TYPE, pRecordStruct->TypeLength)) + pRecordStruct->NDEF_Type = BLE_TYPE; + else if (!memcmp(&pRecordStruct->Type, WIFITOKEN_TYPE_STRING, pRecordStruct->TypeLength)) + pRecordStruct->NDEF_Type = URI_WIFITOKEN_TYPE; + else + pRecordStruct->NDEF_Type = UNKNOWN_TYPE; +} + +/** + * @brief This function parse the Forum External type record. + * @param pRecordStruct : pointer on the record structure to fill. + */ +static void NDEF_ParseForumExternalType( sRecordInfo_t *pRecordStruct ) +{ + if( !memcmp( &(pRecordStruct->Type), M24SR_DISCOVERY_APP_STRING, pRecordStruct->TypeLength ) ) + pRecordStruct->NDEF_Type = M24SR_DISCOVERY_APP_TYPE; + else + pRecordStruct->NDEF_Type = UNKNOWN_TYPE; +} + +/** + * @brief This function parse the URI type record. + * @param pRecordStruct : pointer on the record structure to fill. + */ +static void NDEF_ParseURI( sRecordInfo_t *pRecordStruct ) +{ + uint8_t* pPayload; + + pPayload = (uint8_t*)( pRecordStruct->PayloadBufferAdd ); + pPayload++; /* to skip URI identifier first URI payload byte */ + + if( !memcmp( pPayload, SMS_TYPE_STRING, strlen(SMS_TYPE_STRING) ) ) + { + pRecordStruct->NDEF_Type = URI_SMS_TYPE; + } + else if( !memcmp( pPayload, GEO_TYPE_STRING, strlen(GEO_TYPE_STRING) ) ) + { + pRecordStruct->NDEF_Type = URI_GEO_TYPE; + } + else + pRecordStruct->NDEF_Type = UNKNOWN_TYPE; +} + +/** + * @brief This function parse the Smart Poster. + * @param pRecordStruct : pointer on the record structure to fill. + */ +static void NDEF_ParseSP( sRecordInfo_t *pRecordStruct ) +{ + uint8_t* pPayload; + uint32_t PayloadSize = 0; + uint32_t SPPayloadSize = 0; + uint32_t OffsetInSPPayload = 0; + uint32_t RecordPosition = 0; + sRecordInfo_t *pSPRecordStruct; + + /* initialize variable with size of the payload and poiter on data */ + PayloadSize = pRecordStruct->PayloadLength; + + pPayload = (uint8_t*)( pRecordStruct->PayloadBufferAdd ); + + pSPRecordStruct = SPRecordStructAdd[0]; + + /* Initailize the number of record find in the SP payload */ + pRecordStruct->NbOfRecordInSPPayload = 0; + + do + { + pSPRecordStruct = SPRecordStructAdd[RecordPosition]; + /* identify the record in the SP payload */ + if( NDEF_IdentifySPRecord( pSPRecordStruct, pPayload ) == NDEF_OK ) + { + /* store add of structure that will contain the other record information */ + pRecordStruct->NbOfRecordInSPPayload++; + pRecordStruct->SPRecordStructAdd[RecordPosition] = pSPRecordStruct; + + /* After SPRecord + First Record check if we are at the end of NDEF file */ + SPPayloadSize = pSPRecordStruct->PayloadLength; + + OffsetInSPPayload += pSPRecordStruct->PayloadOffset + SPPayloadSize; + pPayload += OffsetInSPPayload; + } + else /* Recommended Action Record for example */ + { + SPPayloadSize = 0; + } + RecordPosition++; + } + while( (OffsetInSPPayload < PayloadSize) && RecordPositionRecordFlags = pNDEF[0]; + pRecordStruct->TypeLength = TypeNbByte; + pRecordStruct->PayloadLength = pNDEF[2]; + pRecordStruct->IDLength = IDNbByte; + memcpy( pRecordStruct->Type, &pNDEF[3+IDLengthField], TypeNbByte ); + memcpy( pRecordStruct->ID, &pNDEF[3+IDLengthField+TypeNbByte], IDNbByte ); + pRecordStruct->PayloadOffset = SizeOfRecordHeader; + } + else + { + pRecordStruct->RecordFlags = pNDEF[0]; + pRecordStruct->TypeLength = TypeNbByte; + pRecordStruct->PayloadLength = ( ((uint32_t)pNDEF[2]) << 24 ) | + ( ((uint32_t)pNDEF[3]) << 16 ) | + ( ((uint32_t)pNDEF[4]) << 8 ) + | pNDEF[5] ; + pRecordStruct->IDLength = IDNbByte; + memcpy( pRecordStruct->Type, &pNDEF[6+IDLengthField], TypeNbByte ); + memcpy( pRecordStruct->ID, &pNDEF[6+IDLengthField+TypeNbByte], IDNbByte ); + pRecordStruct->PayloadOffset = SizeOfRecordHeader; + } + + pRecordStruct->PayloadBufferAdd = pNDEF; + + NDEF_ParseRecordHeader( pRecordStruct ); + + return NDEF_OK; +} + +/** + * @brief This function read the NDEF content of the TAG. + * @param pNDEF : pointer on the buffer to store NDEF data. + * @retval NDEF_OK : NDEF file data retrieve and store in the buffer. + * @retval NDEF_ERROR : not able to read NDEF from tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot read tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be read. + */ +uint16_t NDEF_ReadNDEF( uint8_t* pNDEF ) +{ + return NfcTag_ReadNDEF( pNDEF ); +} + + + +/** + * @brief This function read the NDEF size of the TAG. + * @param Size : pointer to a 16-bit Size (in bytes) to be returned. + * @retval NDEF_OK : NDEF file data retrieve and store in the buffer. + * @retval NDEF_ERROR : not able to read NDEF from tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot read tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be read. + */ +uint16_t NDEF_getNDEFSize(uint16_t* Size) +{ + return NfcTag_GetLength(Size); +} +/** + * @brief This function write the NDEF in the TAG. + * @param pNDEF : pointer on the buffer containing the NDEF data. + * @retval NDEF_OK : NDEF file data written in the tag. + * @retval NDEF_ERROR : not able to store NDEF in tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be write. + */ +uint16_t NDEF_WriteNDEF( uint16_t NDEF_Size, uint8_t *pNDEF ) +{ + return NfcTag_WriteNDEF( NDEF_Size, pNDEF ); + +} + +/** + * @brief This function append the record to an the NDEF in the TAG. + * @param pRecord : pointer on the record with data to be written. + * @retval NDEF_OK : NDEF file data written in the tag. + * @retval NDEF_ERROR : not able to store NDEF in tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be write. + */ +uint16_t NDEF_AppendRecord(sRecordInfo_t *Record ) +{ + uint16_t status; + uint16_t NDEF_Size = 0; + uint8_t* pData = NDEF_Buffer; + + status = NDEF_getNDEFSize(&NDEF_Size); + if(status != NDEF_OK) return status ; + + if(NDEF_Size != 0) + { + // There are already records in the NDEF + Record->RecordFlags &= ~MB_Mask; + + status = NfcTag_ReadNDEF(pData); + if(status != NDEF_OK) return status ; + + uint8_t* pNdefRecord; + sRecordInfo_t LastRecord; + do { + pNdefRecord = pData; + NDEF_IdentifyBuffer(&LastRecord,pData); + pData += LastRecord.PayloadOffset + LastRecord.PayloadLength; + // TO DO: add a security condition to avoid infinite loop if NDEF file is corrupted + } while(!(LastRecord.RecordFlags & ME_Mask)); + LastRecord.RecordFlags &= ~ME_Mask; + *pNdefRecord = LastRecord.RecordFlags; + } else { + // This will be the first message in memory + Record->RecordFlags |= MB_Mask; + } + Record->RecordFlags |= ME_Mask; + uint32_t RecordLength = NDEF_WriteRecord(Record,pData); + + + return NfcTag_WriteNDEF( NDEF_Size + RecordLength, NDEF_Buffer ); + +} + + + +/** + * @brief This function identify the NDEF message stored in tag. + * @param pRecordStruct : Structure to fill with record information. + * @param pNDEF : pointer on the NDEF message data. + * @retval NDEF_OK : record struct filled. + * @retval NDEF_ERROR : record struct not updated. + */ +uint16_t NDEF_IdentifyBuffer( sRecordInfo_t *pRecordStruct, uint8_t* pNDEF ) +{ + uint16_t SizeOfRecordHeader, TypeNbByte, PayloadLengthField, IDLengthField, IDNbByte; + + /* Is ID length field present */ + if( (*pNDEF) & IL_Mask ) + { + IDLengthField = ID_LENGTH_FIELD; + } + else + { + IDLengthField = 0; + } + + /* it's a SR */ + if( (*pNDEF) & SR_Mask ) + { + /* Analyse short record layout */ + TypeNbByte = pNDEF[1]; + PayloadLengthField = 1; + if( IDLengthField == ID_LENGTH_FIELD ) + IDNbByte = pNDEF[3]; + else + IDNbByte = 0; + } + else + { + /* Analyse normal record layout */ + TypeNbByte = pNDEF[1]; + PayloadLengthField = 4; + if( IDLengthField == ID_LENGTH_FIELD ) + IDNbByte = pNDEF[6]; + else + IDNbByte = 0; + } + + SizeOfRecordHeader = RECORD_FLAG_FIELD + TYPE_LENGTH_FIELD + PayloadLengthField + IDLengthField + TypeNbByte + IDNbByte; + + /* it's a SR */ + if( pNDEF[0] & SR_Mask ) + { + pRecordStruct->RecordFlags = pNDEF[0]; + pRecordStruct->TypeLength = TypeNbByte; + pRecordStruct->PayloadLength = pNDEF[2]; + pRecordStruct->IDLength = IDNbByte; + memcpy( pRecordStruct->Type, &pNDEF[3+IDLengthField], TypeNbByte ); + memcpy( pRecordStruct->ID, &pNDEF[3+IDLengthField+TypeNbByte], IDNbByte ); + pRecordStruct->PayloadOffset = SizeOfRecordHeader; + } + else + { + pRecordStruct->RecordFlags = pNDEF[0]; + pRecordStruct->TypeLength = TypeNbByte; + pRecordStruct->PayloadLength = ( ((uint32_t)pNDEF[2]) << 24 ) | + ( ((uint32_t)pNDEF[3]) << 16 ) | + ( ((uint32_t)pNDEF[4]) << 8 ) + | pNDEF[5] ; + pRecordStruct->IDLength = IDNbByte; + memcpy( pRecordStruct->Type, &pNDEF[6+IDNbByte], TypeNbByte ); + memcpy( pRecordStruct->ID, &pNDEF[6+IDNbByte+TypeNbByte], IDNbByte ); + pRecordStruct->PayloadOffset = SizeOfRecordHeader; + } + + pRecordStruct->PayloadBufferAdd = &pNDEF[pRecordStruct->PayloadOffset]; + + NDEF_ParseRecordHeader( pRecordStruct ); + + return NDEF_OK; +} + +/** + * @brief This function writes a record into a NDEF buffer. (update SR flag if required) + * @param pRecord : Structure with record information to be written. + * @param pNDEF : pointer on the NDEF buffer. + * @retval Length : Length of the written data (in bytes) + */ +uint32_t NDEF_WriteRecord( sRecordInfo_t *pRecord, uint8_t* pNDEF ) +{ + /************************************/ +/* 7 | 6 | 5 | 4 | 3 | 2 1 0 */ +/*----------------------------------*/ +/* MB ME CF SR IL TNF */ +/*----------------------------------*/ +/* TYPE LENGTH */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 3 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 2 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 1 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 0 */ +/*----------------------------------*/ +/* ID LENGTH */ +/*----------------------------------*/ +/* TYPE */ +/*----------------------------------*/ +/* ID */ +/*----------------------------------*/ +/* PAYLOAD */ +/************************************/ + uint8_t * start = pNDEF; + + // start by considering payload length + if(pRecord->PayloadLength <= 0xFF) + pRecord->RecordFlags |= SR_Mask; + else + pRecord->RecordFlags &= ~SR_Mask; + + // Then start writing! + *pNDEF++ = pRecord->RecordFlags; + + *pNDEF++ = pRecord->TypeLength; + + if (!(pRecord->RecordFlags & SR_Mask)) + { + *pNDEF++ = (pRecord->PayloadLength >> 24) & 0xFF; + *pNDEF++ = (pRecord->PayloadLength >> 16) & 0xFF ; + *pNDEF++ = (pRecord->PayloadLength >> 8) & 0xFF; + } + *pNDEF++ = (pRecord->PayloadLength) & 0xFF; + + if(pRecord->RecordFlags & IL_Mask) + *pNDEF++ = (pRecord->IDLength); + + memcpy(pNDEF,pRecord->Type,pRecord->TypeLength); + pNDEF += pRecord->TypeLength; + + if(pRecord->RecordFlags & IL_Mask) + { + memcpy(pNDEF,pRecord->ID,pRecord->IDLength); + pNDEF += pRecord->IDLength; + } + + memcpy(pNDEF,pRecord->PayloadBufferAdd,pRecord->PayloadLength); + pNDEF += pRecord->PayloadLength; + + return (pNDEF - start); +} + +/** + * @brief This function return the length a record data (update SR flag if required) + * @param pRecord : Structure with record information + * @retval Length : Length of the data (in bytes) + */ +uint32_t NDEF_GetRecordLength( sRecordInfo_t *pRecord ) +{ + // start by considering payload length + if(pRecord->PayloadLength <= 0xFF) + pRecord->RecordFlags |= SR_Mask; + else + pRecord->RecordFlags &= ~SR_Mask; + + // Then compute the length + uint32_t length = 1 + // Flags + 1 + // Type length + ((pRecord->RecordFlags & SR_Mask)? 1 : 4) + // Payload length + ((pRecord->RecordFlags & IL_Mask)? 1 : 0) + // ID length + pRecord->TypeLength + // Type + ((pRecord->RecordFlags & IL_Mask)? pRecord->IDLength : 0) + // ID + pRecord->PayloadLength; // Payload; + + return length; +} + +/** + * @brief This function clears the NDEF file + * @retval NDEF Status + */ +uint16_t NDEF_ClearNDEF(void) +{ + return NDEF_WriteNDEF(0 , NULL); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_AAR.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_AAR.c new file mode 100644 index 0000000..e6d5728 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_AAR.c @@ -0,0 +1,133 @@ +/** + ****************************************************************************** + * @file lib_NDEF_AAR.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to add AAR to NDEF file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_AAR.h" + +/** @addtogroup NFC_libraries + * @{ + * @brief This is the library used to manage the content of the TAG (data) + * But also the specific feature of the tag, for instance + * password, gpo... + */ + + +/** @addtogroup libNFC_FORUM + * @{ + * @brief This part of the library manage data which follow NFC forum organisation. + */ + +/** + * @brief This buffer contains the data send/received by TAG + */ +extern uint8_t NDEF_Buffer []; + +/** @defgroup libAAR_Private_Functions + * @{ + */ + +/** + * @} + */ + +/** @defgroup libAAR_Public_Functions + * @{ + * @brief This file is used to manage AAR (stored or loaded in tag) + */ + + +/** + * @brief This function add AAR (Android Application Record) in the tag. + * @param pAARStruct : pointer on structure that contain AAR information. + * @retval NDEF_OK : AAR added. + * @retval NDEF_ERROR : not able to store NDEF in tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be write. + */ +uint16_t NDEF_AddAAR( const sAARInfo *pAARStruct ) +{ + uint16_t status = NDEF_ERROR; + +/* AAR: External Type Record Header */ +/************************************/ +/* 7 | 6 | 5 | 4 | 3 | 2 1 0 */ +/*----------------------------------*/ +/* MB ME CF SR IL TNF */ /* <---- IL=0, CF=0 and SR=1 TNF=4 NFC Forum external type*/ +/*----------------------------------*/ +/* TYPE LENGTH */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 3 */ /* <---- Not Used */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 2 */ /* <---- Not Used */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 1 */ /* <---- Not Used */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 0 */ +/*----------------------------------*/ +/* ID LENGTH */ /* <---- Not Used */ +/*----------------------------------*/ +/* TYPE */ /* android.com:pkg */ +/*----------------------------------*/ +/* ID */ /* <---- Not Used */ +/************************************/ + + /* Do we have to add AAR to an existing NDEF message */ + /* retrieve current NDEF size and current record flag*/ + sRecordInfo_t AARrecord; + + /* fill AAR record header */ + AARrecord.RecordFlags = SR_Mask | TNF_NFCForumExternal; + AARrecord.TypeLength = AAR_TYPE_STRING_LENGTH; + + memcpy( AARrecord.Type, AAR_TYPE_STRING, AAR_TYPE_STRING_LENGTH ); + + /* fill AAR payload */ + AARrecord.PayloadBufferAdd = (uint8_t*)pAARStruct->PackageName; + AARrecord.PayloadLength= strlen(pAARStruct->PackageName) ; + + status = NDEF_AppendRecord(&AARrecord); + + return status; +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Bluetooth.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Bluetooth.c new file mode 100644 index 0000000..6930ca6 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Bluetooth.c @@ -0,0 +1,554 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Bluetooth.c + * @author MMY Application Team + * @version $Revision: 2702 $ + * @date $Date: 2016-07-13 18:45:05 +0200 (Wed, 13 Jul 2016) $ + * @ingroup LibNDEF_Bluetooth + * @brief This file help to manage a NDEF file representing a Bluetooth pairing info. + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_Bluetooth.h" + + + +/** @addtogroup lib_NDEF_Bluetooth Bluetooth OOB library + * @ingroup libNDEF + * @{ + * @brief This module is used to manage a Bluetooth Out-Of-Band NDEF message, to start a communication based on Bluetooth. + * @details The Bluetooth OOB format is described by the Bluetooth v4.0 core specification. + * It consists in a list of Extended Inquiry Responses formated as length-type-value. + * This module allows to build, write & read such data embedded in a NDEF message. + * @section Bluetooth_Library_Usage Bluetooth NDEF Library usage + * @subsection Bluetooth_Write_BrEdr How to write a Bluetooth Br/Edr OOB + * 1. Instanciate & initialize a `Ndef_Bluetooth_OOB_t` structure, specifying: + * - the `NDEF_BLUETOOTH_BREDR` type. + * - the mandatory Device Address field. + * - any other optional EIRs. + * + * Ndef_Bluetooth_OOB_t w_bredr_oob = { .Type = NDEF_BLUETOOTH_BREDR, + * .DeviceAddress = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, + * .OptionalMask = NDEF_BLUETOOTH_OPTION(BLUETOOTH_EIR_COMPLETE_LOCAL_NAME) | + * NDEF_BLUETOOTH_OPTION(BLUETOOTH_EIR_DEVICE_CLASS) | + * NDEF_BLUETOOTH_OPTION(BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_16), + * .LocalName = "MyDevice", + * .nbUUID16 = 2, + * .ClassUUID16 = {0x111E,0x110B}, + * .DeviceClass = {0x04,0x04,0x20} + * }; + * 2. Clear the NDEF message and call the `NDEF_AppendBluetoothOOB` function to write the OOB: + * + * NDEF_ClearNDEF(); + * NDEF_AppendBluetoothOOB ( &w_bredr_oob, NULL ); + * @note Second parameter of `NDEF_AppendBluetoothOOB` can be used to specify an ID for the OOB record (useful for the NDEF Handover message, where specifying an ID is mandatory) + * @subsection Bluetooth_Write_Ble How to write a Bluetooth LE OOB + * 1. Instanciate & initialize a `Ndef_Bluetooth_OOB_t` structure, specifying: + * - the `NDEF_BLUETOOTH_BLE` type. + * - the mandatory Device Address & LE Role fields. + * - any other optional EIRs. + * + * Ndef_Bluetooth_OOB_t w_ble_oob = { .Type = NDEF_BLUETOOTH_BLE, + * .DeviceAddress = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06}, + * .DeviceAddressType = NDEF_BLE_PUBLIC_ADDRESS_TYPE, + * .Role = NDEF_BLE_ROLE_PERIPH_ONLY, + * .OptionalMask = NDEF_BLUETOOTH_OPTION(BLUETOOTH_EIR_COMPLETE_LOCAL_NAME), + * .LocalName = "MyDeviceName", + * }; + * + * 2. Clear the NDEF message and call the `NDEF_AppendBluetoothOOB` function to write the OOB: + * + * NDEF_ClearNDEF(); + * NDEF_AppendBluetoothOOB ( &w_ble_oob, NULL ); + * @note Second parameter of `NDEF_AppendBluetoothOOB` can be used to specify an ID for the OOB record (useful for the NDEF Handover message, where specifying an ID is mandatory) + * + * @subsection Bluetooth_Read How to read a Bluetooth OOB + * 1. Read the 1st record of the NDEF message: + * + * sRecordInfo_t record; + * NDEF_ReadNDEF(NDEF_Buffer); + * NDEF_IdentifyBuffer(record,NDEF_Buffer); + * 2. Decode the Bluetooth OOB: + * + * Ndef_Bluetooth_OOB_t bluetooth_oob; + * NDEF_ReadBluetoothOOB(&record,&bluetooth_oob); + * 3. Use the data from the `Ndef_Bluetooth_OOB_t` structure to start a Bluetooth connexion. + * + * + * + */ + + +/** + * @brief This function copies an array, changing its endianness, usefull to convert data to BLE endianess. + * @param dst Pointer on 1st element of the destination array. + * @param src pointer on 1st element of the source array . + * @param length Number of element to copy. + * @return Pointer to the destination array. + */ +uint8_t* NDEF_BluetoothCopy(uint8_t* dst, uint8_t* src, uint32_t length) +{ + uint32_t index; + for(index = 0 ; index < length; index++) + { + dst[index] = src[length - index - 1]; + } + return dst; +} + +/** + * @brief This function reads a NDEF record and retrieves Bluetooth (BR/EDR or BLE) OOB information if present. + * @param pRecord Pointer on the record structure. + * @param pBluetooth Pointer on the structure to fill . + * @retval NDEF_OK OOB information has been retrieved from the NDEF record. + * @retval NDEF_ERROR OOB information cannot be retrieved. + */ +uint16_t NDEF_ReadBluetoothOOB( sRecordInfo_t *pRecord, Ndef_Bluetooth_OOB_t *pBluetooth ) +{ + uint8_t* pData = pRecord->PayloadBufferAdd; + uint8_t* OOBEnd = pRecord->PayloadBufferAdd + pRecord->PayloadLength; + + pBluetooth->OptionalMask = 0; + pBluetooth->nbServiceData = 0; + pBluetooth->Role = NDEF_BLE_ROLE_UNDEF; + pBluetooth->DeviceAddressType = NDEF_BLE_UNDEF_ADDRESS_TYPE; + pBluetooth->nbUUID16 = 0; + pBluetooth->nbUUID32 = 0; + pBluetooth->nbUUID128 = 0; + pBluetooth->nbServiceSolicitation16 = 0; + pBluetooth->nbServiceSolicitation128 = 0; + + if((pRecord->TypeLength == strlen(NDEF_BLUETOOTH_BREDR_MIME_TYPE)) && + !memcmp(pRecord->Type,NDEF_BLUETOOTH_BREDR_MIME_TYPE,strlen(NDEF_BLUETOOTH_BREDR_MIME_TYPE))) + { + pBluetooth->Type = NDEF_BLUETOOTH_BREDR; + /* Retrieve mandatory OOB data: */ + /* 2 bytes for length and 6 bytes for device addr */ + NDEF_BluetoothCopy((uint8_t*)pBluetooth->DeviceAddress,&pData[2],sizeof(pBluetooth->DeviceAddress)); + pData += 8; + } else if ((pRecord->TypeLength == strlen(NDEF_BLUETOOTH_BLE_MIME_TYPE)) && + !memcmp(pRecord->Type,NDEF_BLUETOOTH_BLE_MIME_TYPE,strlen(NDEF_BLUETOOTH_BLE_MIME_TYPE))) + { + pBluetooth->Type = NDEF_BLUETOOTH_BLE; + /* for BLE, mandatory fields are in EIR */ + } else { + /* This is an unknown MIME type */ + return NDEF_ERROR; + } + + /* EIR format: 1 byte for length, 1 byte for type, n bytes for data */ + while (pData < OOBEnd) + { + NDEF_EIR_t* rEIR = (NDEF_EIR_t*)pData; + /* +1 for EIR length byte */ + pData += rEIR->length + 1; + + /* keep track of all EIR found */ + if(rEIR->type < 0x20) + NDEF_BLUETOOTH_SET_OPTIONAL_MASK(pBluetooth,rEIR->type); + + switch (rEIR->type) + { + case BLUETOOTH_EIR_FLAGS: + pBluetooth->Flags = *rEIR->value; + break; + + case BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_16: + case BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_16: + pBluetooth->nbUUID16 = (rEIR->length - 1) / 2 ; + NDEF_BluetoothCopy((uint8_t*)pBluetooth->ClassUUID16,rEIR->value,rEIR->length-1); + break; + + case BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_32: + case BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_32: + pBluetooth->nbUUID32 = (rEIR->length - 1) / 4 ; + NDEF_BluetoothCopy((uint8_t*)pBluetooth->ClassUUID32,rEIR->value,rEIR->length-1); + break; + + case BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_128: + case BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_128: + pBluetooth->nbUUID128 = (rEIR->length - 1) / 16 ; + NDEF_BluetoothCopy((uint8_t*)pBluetooth->ClassUUID128,rEIR->value,rEIR->length-1); + break; + + case BLUETOOTH_EIR_SHORT_LOCAL_NAME: + case BLUETOOTH_EIR_COMPLETE_LOCAL_NAME: + /* No worry about name length as max EIR length is 0xff using 1 byte for the type metadata */ + memcpy(pBluetooth->LocalName,rEIR->value,rEIR->length-1); + pBluetooth->LocalName[rEIR->length-1] = '\0'; + break; + + case BLUETOOTH_EIR_TX_POWER_LEVEL: + pBluetooth->TxPowerLevel = *rEIR->value; + break; + + case BLUETOOTH_EIR_DEVICE_CLASS: + NDEF_BluetoothCopy((uint8_t*)pBluetooth->DeviceClass,rEIR->value,sizeof(pBluetooth->DeviceClass)); + break; + + case BLUETOOTH_EIR_SIMPLE_PAIRING_HASH: + NDEF_BluetoothCopy((uint8_t*)pBluetooth->SimplePairingHash,rEIR->value,sizeof(pBluetooth->SimplePairingHash)); + break; + + case BLUETOOTH_EIR_SIMPLE_PAIRING_RANDOMIZER: + NDEF_BluetoothCopy((uint8_t*)pBluetooth->SimplePairingRandomizer,rEIR->value,sizeof(pBluetooth->SimplePairingRandomizer)); + break; + + case BLUETOOTH_EIR_SECURITY_MANAGER_TK_VALUE: + NDEF_BluetoothCopy((uint8_t*)pBluetooth->SecureManagerTK,rEIR->value,sizeof(pBluetooth->SecureManagerTK)); + break; + + case BLUETOOTH_EIR_SECURITY_MANAGER_FLAGS: + pBluetooth->SMFlags = *rEIR->value; + break; + + case BLUETOOTH_EIR_SLAVE_CONNECTION_INTERVAL_RANGE: + NDEF_BluetoothCopy((uint8_t*)pBluetooth->SlaveConnIntervalRange,rEIR->value,sizeof(pBluetooth->SlaveConnIntervalRange)); + break; + + case BLUETOOTH_EIR_SERVICE_SOLICITATION_16: + pBluetooth->nbServiceSolicitation16 = (rEIR->length - 1) / 2 ; + NDEF_BluetoothCopy((uint8_t*)pBluetooth->ServiceSolicitation16,rEIR->value,rEIR->length-1); + break; + + case BLUETOOTH_EIR_SERVICE_SOLICITATION_128: + pBluetooth->nbServiceSolicitation128 = (rEIR->length - 1) / 16 ; + NDEF_BluetoothCopy((uint8_t*)pBluetooth->ServiceSolicitation128,rEIR->value,rEIR->length-1); + break; + + case BLUETOOTH_EIR_SERVICE_DATA: + /* a specific function should be used for this EIR */ + pBluetooth->nbServiceData++; + break; + + case BLUETOOTH_EIR_MANUFACTURER_DATA: + /* a specific function should be used for this EIR */ + pBluetooth->nbManufacturerData++; + break; + + case BLUETOOTH_EIR_APPEARANCE: + pBluetooth->Appearance = *(uint16_t *)rEIR->value; + break; + + case BLUETOOTH_EIR_BLE_DEVICE_ADDRESS: + NDEF_BluetoothCopy((uint8_t*)pBluetooth->DeviceAddress,rEIR->value,sizeof(pBluetooth->DeviceAddress)); + pBluetooth->DeviceAddressType = (Ndef_BLE_Address_Type_t)rEIR->value[sizeof(pBluetooth->DeviceAddress)]; + break; + + case BLUETOOTH_EIR_BLE_ROLE: + pBluetooth->Role = (Ndef_BLE_Role_t) *rEIR->value; + break; + + default: + pBluetooth->nbUnknown++; + break; + } /* switch rEIR->type */ + } /* while (pData < OOBEnd) */ + /* Check that BLE mandatory fields are there */ + if((pBluetooth->Type == NDEF_BLUETOOTH_BLE) && + (!NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_BLE_DEVICE_ADDRESS) || + !NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_BLE_ROLE))) + return NDEF_ERROR; + + return NDEF_OK; +} + +/** + * @brief This function appends a Bluetooth OOB record to the NDEF message, using the OOB data given in the input structure. + * @param pBluetooth Pointer on a `Ndef_Bluetooth_OOB_t` structure containing the OOB information. + * @param RecordID ID to be used for this record (required for Handover case, can be set to NULL in other cases). + * @retval NDEF_OK The Bluetooth OOB record has been appended. + * @retval NDEF_ERROR_MEMORY_INTERNAL The Bluetooth OOB record cannot be appended due to memory size limitation. + * @retval NDEF_ERROR The Bluetooth OOB record cannot be appended. + */ +uint16_t NDEF_AppendBluetoothOOB( Ndef_Bluetooth_OOB_t *pBluetooth, char* RecordID ) +{ + sRecordInfo_t Record; + uint16_t status; + + Record.RecordFlags = TNF_MediaType; + Record.RecordFlags |= (RecordID != NULL) ? IL_Mask : 0; + Record.IDLength = strlen(RecordID); + memcpy(Record.ID,RecordID,Record.IDLength); + + if(pBluetooth->Type == NDEF_BLUETOOTH_BREDR) + { + Record.TypeLength = strlen(NDEF_BLUETOOTH_BREDR_MIME_TYPE); + memcpy(Record.Type, NDEF_BLUETOOTH_BREDR_MIME_TYPE, Record.TypeLength); + } + else if (pBluetooth->Type == NDEF_BLUETOOTH_BLE) + { + Record.TypeLength = strlen(NDEF_BLUETOOTH_BLE_MIME_TYPE); + memcpy(Record.Type, NDEF_BLUETOOTH_BLE_MIME_TYPE, Record.TypeLength); + } + else + { + return NDEF_ERROR; + } + + /* Generate OOB payload */ + Record.PayloadLength = NDEF_GetBluetoothOOBLength(pBluetooth); + Record.PayloadBufferAdd = NDEF_Record_Buffer; + if(Record.PayloadLength > NDEF_RECORD_MAX_SIZE) + return NDEF_ERROR_MEMORY_INTERNAL; + + /* pData: pointer to ease increment of record buffer address (byte granularity) */ + uint8_t* pData = Record.PayloadBufferAdd; + + /* for BR-EDR Device address & length are managed outside EIR */ + if(pBluetooth->Type == NDEF_BLUETOOTH_BREDR) + { + *pData = Record.PayloadLength; + pData += 2; + NDEF_BluetoothCopy(pData,(uint8_t*)pBluetooth->DeviceAddress,sizeof(pBluetooth->DeviceAddress)); + pData+=sizeof(pBluetooth->DeviceAddress); + } + + /* wEIR: pointer to ease write to the buffer. + * length always set with an additional +1 corresponding to the EIR type byte. + * pData increment is always done with an additional +1 corresponding to the EIR length byte. + */ + NDEF_EIR_t* wEIR; + + + if(pBluetooth->Type == NDEF_BLUETOOTH_BLE) + { + /* following EIR are mandatory for BLE */ + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->DeviceAddress) + sizeof(pBluetooth->DeviceAddressType) + 1; + wEIR->type = BLUETOOTH_EIR_BLE_DEVICE_ADDRESS; + NDEF_BluetoothCopy(wEIR->value, (uint8_t*)pBluetooth->DeviceAddress,sizeof(pBluetooth->DeviceAddress)); + wEIR->value[sizeof(pBluetooth->DeviceAddress)] = pBluetooth->DeviceAddressType; + pData += wEIR->length + 1; + + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->Role) + 1; + wEIR->type = BLUETOOTH_EIR_BLE_ROLE; + wEIR->value[0] = pBluetooth->Role; + pData += wEIR->length + 1; + + } + + /* Rely on the optional mask to know if a EIR is required or not */ + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_FLAGS)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->Flags) + 1; + wEIR->type = BLUETOOTH_EIR_FLAGS; + wEIR->value[0] = pBluetooth->Flags; + pData += wEIR->length + 1; + } + + if(pBluetooth->nbUUID16 > 0) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = 2 * pBluetooth->nbUUID16 + 1; + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_16)) + wEIR->type = BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_16; + else + wEIR->type = BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_16; + NDEF_BluetoothCopy(wEIR->value, (uint8_t*) pBluetooth->ClassUUID16, 2 * pBluetooth->nbUUID16); + pData += wEIR->length + 1; + + } + + if(pBluetooth->nbUUID32 > 0) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = 4 * pBluetooth->nbUUID32 + 1; + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_32)) + wEIR->type = BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_32; + else + wEIR->type = BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_32; + NDEF_BluetoothCopy(wEIR->value, (uint8_t*)pBluetooth->ClassUUID32, 4 * pBluetooth->nbUUID32); + pData += wEIR->length + 1; + + } + + if(pBluetooth->nbUUID128 > 0) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = 16 * pBluetooth->nbUUID128 + 1; + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_128)) + wEIR->type = BLUETOOTH_EIR_SERVICE_CLASS_UUID_COMPLETE_128; + else + wEIR->type = BLUETOOTH_EIR_SERVICE_CLASS_UUID_PARTIAL_128; + NDEF_BluetoothCopy(wEIR->value, (uint8_t*) pBluetooth->ClassUUID128, 16 * pBluetooth->nbUUID128); + pData += wEIR->length + 1; + + } + + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SHORT_LOCAL_NAME) || + NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_COMPLETE_LOCAL_NAME)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = strlen(pBluetooth->LocalName) + 1; + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SHORT_LOCAL_NAME)) + wEIR->type = BLUETOOTH_EIR_SHORT_LOCAL_NAME; + else + wEIR->type = BLUETOOTH_EIR_COMPLETE_LOCAL_NAME; + memcpy(wEIR->value, pBluetooth->LocalName,strlen(pBluetooth->LocalName)); + pData += wEIR->length + 1; + + } + + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_TX_POWER_LEVEL)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->TxPowerLevel) + 1; + wEIR->type = BLUETOOTH_EIR_TX_POWER_LEVEL; + wEIR->value[0] = pBluetooth->TxPowerLevel; + pData += wEIR->length + 1; + } + + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_DEVICE_CLASS)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->DeviceClass) + 1; + wEIR->type = BLUETOOTH_EIR_DEVICE_CLASS; + NDEF_BluetoothCopy(wEIR->value, pBluetooth->DeviceClass,sizeof(pBluetooth->DeviceClass)); + pData += wEIR->length + 1; + + } + + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SIMPLE_PAIRING_HASH)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->SimplePairingHash) + 1; + wEIR->type = BLUETOOTH_EIR_SIMPLE_PAIRING_HASH; + NDEF_BluetoothCopy(wEIR->value, pBluetooth->SimplePairingHash,sizeof(pBluetooth->SimplePairingHash)); + pData += wEIR->length + 1; + + } + + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SIMPLE_PAIRING_RANDOMIZER)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->SimplePairingRandomizer) + 1; + wEIR->type = BLUETOOTH_EIR_SIMPLE_PAIRING_RANDOMIZER; + NDEF_BluetoothCopy(wEIR->value, pBluetooth->SimplePairingRandomizer,sizeof(pBluetooth->SimplePairingRandomizer)); + pData += wEIR->length + 1; + + } + + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SECURITY_MANAGER_TK_VALUE)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->SecureManagerTK) + 1; + wEIR->type = BLUETOOTH_EIR_SECURITY_MANAGER_TK_VALUE; + NDEF_BluetoothCopy(wEIR->value, pBluetooth->SecureManagerTK,sizeof(pBluetooth->SecureManagerTK)); + pData += wEIR->length + 1; + + } + + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SECURITY_MANAGER_FLAGS)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->SMFlags) + 1; + wEIR->type = BLUETOOTH_EIR_SECURITY_MANAGER_FLAGS; + wEIR->value[0] = pBluetooth->SMFlags; + pData += wEIR->length + 1; + + } + + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SLAVE_CONNECTION_INTERVAL_RANGE)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->SlaveConnIntervalRange) + 1; + wEIR->type = BLUETOOTH_EIR_SLAVE_CONNECTION_INTERVAL_RANGE; + NDEF_BluetoothCopy(wEIR->value, (uint8_t*)pBluetooth->SlaveConnIntervalRange,sizeof(pBluetooth->SlaveConnIntervalRange)); + pData += wEIR->length + 1; + + } + + if(pBluetooth->nbServiceSolicitation16 > 0) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = 2 * pBluetooth->nbServiceSolicitation16 + 1; + wEIR->type = BLUETOOTH_EIR_SERVICE_SOLICITATION_16; + NDEF_BluetoothCopy(wEIR->value, (uint8_t*)pBluetooth->ServiceSolicitation16, 16 * pBluetooth->nbServiceSolicitation16); + pData += wEIR->length + 1; + + } + + if(pBluetooth->nbServiceSolicitation128 > 0) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = 16 * pBluetooth->nbServiceSolicitation128 + 1; + wEIR->type = BLUETOOTH_EIR_SERVICE_SOLICITATION_128; + NDEF_BluetoothCopy(wEIR->value, (uint8_t*) pBluetooth->ServiceSolicitation128, 16 * pBluetooth->nbServiceSolicitation128); + pData += wEIR->length + 1; + + } + + if(NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_APPEARANCE)) + { + wEIR = (NDEF_EIR_t*)pData; + wEIR->length = sizeof(pBluetooth->Appearance) + 1; + wEIR->type = BLUETOOTH_EIR_APPEARANCE; + wEIR->value[0] = pBluetooth->Appearance; + pData += wEIR->length + 1; + + } + + + status = NDEF_AppendRecord(&Record); + if(status != NDEF_OK) return status; + + return NDEF_OK; +} + +/** + * @brief This function computeS the payload size for the OOB, using the data given in the input `Ndef_Bluetooth_OOB_t` structure. + * @param pBluetooth Pointer on a `Ndef_Bluetooth_OOB_t` structure containing the OOB information. + * @return Computed length in bytes. + */ +uint32_t NDEF_GetBluetoothOOBLength( Ndef_Bluetooth_OOB_t *pBluetooth ) +{ + uint32_t length = (pBluetooth->Type == NDEF_BLUETOOTH_BREDR) ? sizeof(pBluetooth->DeviceAddress) + 2 : 0; // +2 is for BR/EDR mandatory length + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_FLAGS)? sizeof(pBluetooth->Flags) + 2 : 0 ; + length += pBluetooth->nbUUID16 ? pBluetooth->nbUUID16 * 2 + 2 : 0; + length += pBluetooth->nbUUID32 ? pBluetooth->nbUUID32 * 4 + 2 : 0; + length += pBluetooth->nbUUID128 ? pBluetooth->nbUUID128 * 16 + 2 : 0; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SHORT_LOCAL_NAME)? strlen(pBluetooth->LocalName) + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_COMPLETE_LOCAL_NAME)? strlen(pBluetooth->LocalName) + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_TX_POWER_LEVEL)? sizeof(pBluetooth->TxPowerLevel + 2) : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_DEVICE_CLASS)? sizeof(pBluetooth->DeviceClass) + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SIMPLE_PAIRING_HASH)? sizeof(pBluetooth->SimplePairingHash) + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SIMPLE_PAIRING_RANDOMIZER)? sizeof(pBluetooth->SimplePairingRandomizer) + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SECURITY_MANAGER_TK_VALUE)? sizeof(pBluetooth->SecureManagerTK) + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SECURITY_MANAGER_FLAGS)? sizeof(pBluetooth->SMFlags) + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SLAVE_CONNECTION_INTERVAL_RANGE)? sizeof(pBluetooth->SlaveConnIntervalRange) + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SERVICE_SOLICITATION_16)? pBluetooth->nbServiceSolicitation16 * 2 + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_SERVICE_SOLICITATION_128)? pBluetooth->nbServiceSolicitation128 * 16 + 2 : 0 ; + length += NDEF_BLUETOOTH_GET_OPTIONAL_MASK(pBluetooth,BLUETOOTH_EIR_APPEARANCE)? sizeof(pBluetooth->Appearance) + 2 : 0 ; + length += (pBluetooth->Type == NDEF_BLUETOOTH_BLE)? sizeof(pBluetooth->DeviceAddress) + sizeof(pBluetooth->DeviceAddressType) + 2 : 0 ; + length += (pBluetooth->Type == NDEF_BLUETOOTH_BLE)? sizeof(pBluetooth->Role) + 2 : 0; + + return length; +} +/** + * @} + */ + +/******************* (C) COPYRIGHT 2016 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Email.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Email.c new file mode 100644 index 0000000..768afba --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Email.c @@ -0,0 +1,438 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Email.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage NDEF file that represent Email. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_Email.h" +#include "stdlib.h" + +/** @addtogroup NFC_libraries + * @{ + * @brief This is the library used to manage the content of the TAG (data) + * But also the specific feature of the tag, for instance + * password, gpo... + */ + + +/** @addtogroup libNFC_FORUM + * @{ + * @brief This part of the library manage data which follow NFC forum organisation. + */ + +/** + * @brief This buffer contains the data send/received by TAG + */ +extern uint8_t NDEF_Buffer []; + + +/** @defgroup libEmail_Private_Functions + * @{ + */ + + +static void NDEF_FillEmailStruct( uint8_t* pPayload, uint32_t PayloadSize, sEmailInfo *pEmailStruct ); +static void NDEF_ReadURI_Email( sRecordInfo_t *pRecordStruct, sEmailInfo *pEmailStruct ); + +/** + * @brief This function fill Email structure with information of NDEF message + * @param pPayload : pointer on the payload data of the NDEF message + * @param PayloadSize : number of data in the payload + * @param pEmailStruct : pointer on the structure to fill + * @retval NONE + */ +static void NDEF_FillEmailStruct( uint8_t* pPayload, uint32_t PayloadSize, sEmailInfo *pEmailStruct ) +{ + uint8_t* pLastByteAdd, *pLook4Word, *pEndString; + uint32_t SizeOfKeyWord = 0; + + pEndString = 0; + + /* First character force to NULL in case not matching found */ +#ifdef NDEF_DYN_ALLOC + pEmailStruct->EmailAdd = NULL; + pEmailStruct->Subject = NULL; + pEmailStruct->Message = NULL; + pEmailStruct->Information = NULL; +#else + *pEmailStruct->EmailAdd = 0; + *pEmailStruct->Subject = 0; + *pEmailStruct->Message = 0; +#endif + + /* Interesting information are stored before picture if any */ + /* Moreover picture is not used in this demonstration SW */ + pLastByteAdd = (uint8_t*)(pPayload + PayloadSize); + + /* first byte should be the "mailto:" well know URI type, skip it */ + pLook4Word = ++pPayload; + + /* Retrieve email add */ + if( pLook4Word != pLastByteAdd ) + { + pEndString = pLook4Word; + while( memcmp( pEndString, URI_FIRST_DATA_END, URI_FIRST_DATA_END_LENGTH ) && (pEndString < pLastByteAdd) ) + { + pEndString++; + } + if( ( !memcmp( pEndString, URI_FIRST_DATA_END, URI_FIRST_DATA_END_LENGTH ) ) || (pEndString == pLastByteAdd) ) + { +#ifdef NDEF_DYN_ALLOC + pEmailStruct->EmailAdd = malloc(pEndString-pLook4Word + 1); + if(pEmailStruct->EmailAdd != NULL) +#endif + { + memcpy( pEmailStruct->EmailAdd, pLook4Word, pEndString-pLook4Word); + /* add end of string character */ + pEmailStruct->EmailAdd[pEndString-pLook4Word] = 0; + } + } + } + + pEndString += URI_FIRST_DATA_END_LENGTH; + pLook4Word = pEndString; + + /* check if e-mail subject is present */ + if( !memcmp( pLook4Word, SUBJECT_BEGIN_STRING, SUBJECT_BEGIN_STRING_LENGTH ) ) + { + SizeOfKeyWord = SUBJECT_BEGIN_STRING_LENGTH; + + /* Retrieve subject */ + if( pLook4Word != pLastByteAdd ) + { + pLook4Word += SizeOfKeyWord; + pEndString = pLook4Word; + while( memcmp( pEndString, URI_SECOND_DATA_END, URI_SECOND_DATA_END_LENGTH ) && (pEndString < pLastByteAdd) ) + { + pEndString++; + } + if( ( !memcmp( pEndString, URI_SECOND_DATA_END, URI_SECOND_DATA_END_LENGTH ) ) || (pEndString == pLastByteAdd) ) + { +#ifdef NDEF_DYN_ALLOC + pEmailStruct->Subject = malloc(pEndString-pLook4Word + 1); + if(pEmailStruct->Subject != NULL) +#endif + { + memcpy( pEmailStruct->Subject, pLook4Word, pEndString-pLook4Word ); + /* add end of string character */ + pEmailStruct->Subject[pEndString-pLook4Word] = 0; + } + } + pEndString += URI_SECOND_DATA_END_LENGTH; + } + } + + pLook4Word = pEndString; + + /* check if e-mail message is present */ + if( !memcmp( pLook4Word, MESSAGE_BEGIN_STRING, MESSAGE_BEGIN_STRING_LENGTH ) ) + { + pEndString += MESSAGE_BEGIN_STRING_LENGTH; + /* Retrieve message */ +#ifdef NDEF_DYN_ALLOC + pEmailStruct->Message = malloc(PayloadSize - (pEndString - pPayload + 1) + 1); + if(pEmailStruct->Message != NULL) +#endif + { + memcpy( pEmailStruct->Message, pEndString, PayloadSize - (pEndString - pPayload + 1) ); + /* add end of string character */ + pEmailStruct->Message[PayloadSize-(pEndString-pPayload+1)] = 0; + } + } +} + +/** + * @brief This function read the Email and store data in a structure. + * @param pRecordStruct : Pointer on the record structure. + * @param pEmailStruct : pointer on the structure to fill. + */ +static void NDEF_ReadURI_Email( sRecordInfo_t *pRecordStruct, sEmailInfo *pEmailStruct ) +{ + uint8_t* pPayload; + uint32_t PayloadSize; + + PayloadSize = pRecordStruct->PayloadLength; + + /* Read record header */ + pPayload = (uint8_t*)(pRecordStruct->PayloadBufferAdd); + + if( pRecordStruct->NDEF_Type == URI_EMAIL_TYPE ) + NDEF_FillEmailStruct( pPayload , PayloadSize, pEmailStruct ); + +} + +/** + * @} + */ + +/** @defgroup libEmail_Public_Functions + * @{ + * @brief This file is used to manage Email (stored or loaded in tag) + */ + +/** + * @brief This function read NDEF and retrieve Eamil information if any. + * @param pRecordStruct : Pointer on the record structure. + * @param pEmailStruct : pointer on the structure to fill . + * @retval NDEF_OK : Email information from NDEF have been retrieved. + * @retval NDEF_ERROR : not able to read NDEF in tag. + */ +uint16_t NDEF_ReadEmail( sRecordInfo_t *pRecordStruct, sEmailInfo *pEmailStruct ) +{ + uint16_t status = NDEF_ERROR; + sRecordInfo_t *pSPRecordStruct; + uint32_t PayloadSize, RecordPosition; + uint8_t* pData; + + + if( pRecordStruct->NDEF_Type == URI_EMAIL_TYPE ) + { + NDEF_ReadURI_Email( pRecordStruct, pEmailStruct ); + status = NDEF_OK; + } + else if( pRecordStruct->NDEF_Type == SMARTPOSTER_TYPE ) + { + for( RecordPosition = 0; RecordPosition < pRecordStruct->NbOfRecordInSPPayload; RecordPosition++ ) + { + pSPRecordStruct = pRecordStruct->SPRecordStructAdd[RecordPosition]; + if( pSPRecordStruct->NDEF_Type == URI_EMAIL_TYPE ) + { + NDEF_ReadURI_Email( pSPRecordStruct, pEmailStruct ); + status = NDEF_OK; + } + if( pSPRecordStruct->NDEF_Type == TEXT_TYPE ) + { + PayloadSize = pSPRecordStruct->PayloadLength; + + /* The instruction content the UTF-8 language code that is not used here */ + pData = (uint8_t*)pSPRecordStruct->PayloadBufferAdd; + PayloadSize -= *pData + 1; /* remove not usefull data */ + pData += *pData + 1; + + memcpy( pEmailStruct->Information, pData, PayloadSize ); + } + } + } + + return status; +} + +/** + * @brief This function write the NDEF file with the Email data given in the structure. + * @param pEmailStruct : pointer on structure that contain the Email information. + * @retval NDEF_OK : the function is successful. + * @retval NDEF_ERROR : not able to store NDEF in tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be write. + */ +uint16_t NDEF_WriteEmail( sEmailInfo *pEmailStruct ) +{ + uint16_t status = NDEF_ERROR, Offset = 0; + + NDEF_PrepareEmailMessage( pEmailStruct, NDEF_Buffer, &Offset ); + + status = NfcTag_WriteNDEF( Offset, NDEF_Buffer ); + + return status; +} + +/** + * @brief This function write the NDEF file with the Email data given in the structure. + * @param pEmailStruct : pointer on structure that contain the Email information. + * @param pNDEFMessage : pointer on the NDEF message. + * @param size : to store the size of the NDEF message generated. + */ +void NDEF_PrepareEmailMessage( sEmailInfo *pEmailStruct, uint8_t *pNDEFMessage, uint16_t *size ) +{ + uint16_t Offset = 0; + uint32_t emailSize = 0; + uint32_t infoSize = 0; + uint32_t totalSize = 0; + + /* Email is an URI but can be included in a smart poster to add text to give instruction to user for instance */ + + /* Email (smart poster) Record Header */ +/************************************/ +/* 7 | 6 | 5 | 4 | 3 | 2 1 0 */ +/*----------------------------------*/ +/* MB ME CF SR IL TNF */ /* <---- CF=0, IL=0 and SR=1 TNF=1 NFC Forum Well-known type*/ +/*----------------------------------*/ +/* TYPE LENGTH */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 3 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 2 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 1 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 0 */ +/*----------------------------------*/ +/* ID LENGTH */ /* <---- Not Used */ +/*----------------------------------*/ +/* TYPE */ +/*----------------------------------*/ +/* ID */ /* <---- Not Used */ +/************************************/ + + /* Email : 1+@+1+subject+1+message */ + emailSize = 1 + strlen( pEmailStruct->EmailAdd ) + URI_FIRST_DATA_END_LENGTH + SUBJECT_BEGIN_STRING_LENGTH + + strlen( pEmailStruct->Subject ) + URI_SECOND_DATA_END_LENGTH + MESSAGE_BEGIN_STRING_LENGTH + strlen( pEmailStruct->Message ); + + /* Check if a Smart poster is needed */ + if( pEmailStruct->Information[0] != '\0' ) + { + /* Info : 1+2+info */ + infoSize = 1 + ISO_ENGLISH_CODE_STRING_LENGTH + strlen( pEmailStruct->Information ); + /* Total */ + totalSize = 4 + emailSize + 4 + infoSize; + if( emailSize > 255 ) totalSize += 3; /* Normal Email size */ + if( infoSize > 255 ) totalSize += 3; /* Normal Info size */ + + /* SmartPoster header */ + if( totalSize > 255 ) + { + pNDEFMessage[Offset++] = 0xC1; + pNDEFMessage[Offset++] = SMART_POSTER_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (totalSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (totalSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (totalSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = totalSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = 0xD1; + pNDEFMessage[Offset++] = SMART_POSTER_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (uint8_t)totalSize; + } + memcpy( &pNDEFMessage[Offset], SMART_POSTER_TYPE_STRING, SMART_POSTER_TYPE_STRING_LENGTH ); + Offset += SMART_POSTER_TYPE_STRING_LENGTH; + } + + /* Email header */ + pNDEFMessage[Offset] = 0x81; + if( emailSize < 256 ) pNDEFMessage[Offset] |= 0x10; // Set the SR bit + if( pEmailStruct->Information[0] == '\0' ) pNDEFMessage[Offset] |= 0x40; // Set the ME bit + Offset++; + + pNDEFMessage[Offset++] = URI_TYPE_STRING_LENGTH; + if( emailSize > 255 ) + { + pNDEFMessage[Offset++] = (emailSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (emailSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (emailSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = emailSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = (uint8_t)emailSize; + } + memcpy( &pNDEFMessage[Offset], URI_TYPE_STRING, URI_TYPE_STRING_LENGTH ); + Offset += URI_TYPE_STRING_LENGTH; + + /* Email pay load */ + pNDEFMessage[Offset++] = URI_ID_0x06; + memcpy( &pNDEFMessage[Offset], pEmailStruct->EmailAdd, strlen(pEmailStruct->EmailAdd) ); + Offset += strlen( pEmailStruct->EmailAdd ); + memcpy( &pNDEFMessage[Offset], URI_FIRST_DATA_END, URI_FIRST_DATA_END_LENGTH ); + Offset += URI_FIRST_DATA_END_LENGTH; + + memcpy( &pNDEFMessage[Offset], SUBJECT_BEGIN_STRING, SUBJECT_BEGIN_STRING_LENGTH ); + Offset += SUBJECT_BEGIN_STRING_LENGTH; + memcpy( &pNDEFMessage[Offset], pEmailStruct->Subject, strlen(pEmailStruct->Subject) ); + Offset += strlen( pEmailStruct->Subject ); + memcpy( &pNDEFMessage[Offset], URI_SECOND_DATA_END, URI_SECOND_DATA_END_LENGTH ); + Offset += URI_SECOND_DATA_END_LENGTH; + + memcpy( &pNDEFMessage[Offset], MESSAGE_BEGIN_STRING, MESSAGE_BEGIN_STRING_LENGTH ); + Offset += MESSAGE_BEGIN_STRING_LENGTH; + memcpy( &pNDEFMessage[Offset], pEmailStruct->Message, strlen(pEmailStruct->Message) ); + Offset += strlen( pEmailStruct->Message ); + + /* Information header */ + if( pEmailStruct->Information[0] != '\0' ) + { + if( infoSize > 255 ) + { + pNDEFMessage[Offset++] = 0x41; + pNDEFMessage[Offset++] = TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (infoSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (infoSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (infoSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = infoSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = 0x51; + pNDEFMessage[Offset++] = TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (uint8_t)infoSize; + } + + memcpy( &pNDEFMessage[Offset], TEXT_TYPE_STRING, TEXT_TYPE_STRING_LENGTH ); + Offset += TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = ISO_ENGLISH_CODE_STRING_LENGTH; /* UTF-8 with x byte language code */ + memcpy( &pNDEFMessage[Offset], ISO_ENGLISH_CODE_STRING, ISO_ENGLISH_CODE_STRING_LENGTH ); + Offset += ISO_ENGLISH_CODE_STRING_LENGTH; + + /* Information payload */ + memcpy( &pNDEFMessage[Offset], pEmailStruct->Information, strlen(pEmailStruct->Information) ); + Offset += strlen( pEmailStruct->Information ); + + } + + *size = (uint16_t)(Offset); + +} + +/** + * @brief This function close a NDEF Email buffer freeing associated memory. + * @param pEmailStruct : pointer on structure that contain the Email information. + */ +void NDEF_closeEmail( sEmailInfo *pEmailStruct) +{ +#ifdef NDEF_DYN_ALLOC + if(pEmailStruct->EmailAdd != NULL) free(pEmailStruct->EmailAdd); + if(pEmailStruct->Information != NULL) free(pEmailStruct->Information); + if(pEmailStruct->Message != NULL) free(pEmailStruct->Message); + if(pEmailStruct->Subject != NULL) free(pEmailStruct->Subject); +#endif +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Geo.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Geo.c new file mode 100644 index 0000000..9e92f09 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Geo.c @@ -0,0 +1,358 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Geo.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage NDEF file that represent geolocation. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_Geo.h" + +/** @addtogroup NFC_libraries + * @{ + * @brief This is the library used to manage the content of the TAG (data) + * But also the specific feature of the tag, for instance + * password, gpo... + */ + + +/** @addtogroup libNFC_FORUM + * @{ + * @brief This part of the library manage data which follow NFC forum organisation. + */ + +/** + * @brief This buffer contains the data send/received by TAG + */ +extern uint8_t NDEF_Buffer []; + +/** @defgroup libGeo_Private_Functions + * @{ + */ + +static void NDEF_FillGeoStruct( uint8_t* pPayload, uint32_t PayloadSize, sGeoInfo *pGeoStruct ); +static void NDEF_ReadURI_Geo( sRecordInfo_t *pRecordStruct, sGeoInfo *pGeoStruct ); + +/** + * @brief This function fill Geo structure with information of NDEF message. + * @param pPayload : pointer on the payload data of the NDEF message. + * @param PayloadSize : number of data in the payload. + * @param pGeoStruct : pointer on the structure to fill. + */ +static void NDEF_FillGeoStruct( uint8_t* pPayload, uint32_t PayloadSize, sGeoInfo *pGeoStruct ) +{ + uint8_t* pLastByteAdd, *pLook4Word, *pEndString; + char* pKeyWord; + uint32_t SizeOfKeyWord; + pEndString = 0; + + pKeyWord = GEO_TYPE_STRING; + SizeOfKeyWord = GEO_TYPE_STRING_LENGTH; + + /* First character force to NULL in case not matching found */ + *pGeoStruct->Latitude = 0; + *pGeoStruct->Longitude = 0; + + /* Interresting information are stored before picture if any */ + /* Moreover picture is not used in this demonstration SW */ + pLastByteAdd = (uint8_t*)(pPayload + PayloadSize); + + pLook4Word = pPayload; + while( memcmp( pLook4Word, pKeyWord, SizeOfKeyWord ) && (pLook4Word < pLastByteAdd) ) + { + pLook4Word++; + } + + /* Retrieve phone number */ + if( pLook4Word != pLastByteAdd ) + { + pLook4Word += SizeOfKeyWord; + pEndString = pLook4Word; + while( memcmp( pEndString, URI_LATITUDE_END, URI_LATITUDE_END_LENGTH ) && (pEndString < pLastByteAdd) ) + { + pEndString++; + } + if( pEndString != pLastByteAdd ) + { + memcpy( pGeoStruct->Latitude, pLook4Word, pEndString-pLook4Word ); + /* add end of string character */ + pGeoStruct->Latitude[pEndString-pLook4Word] = 0; + } + } + pEndString += URI_LATITUDE_END_LENGTH; + pLook4Word = pEndString; + + memcpy( pGeoStruct->Longitude, pEndString, PayloadSize - (pEndString - pPayload) ); + /* add end of string character */ + pGeoStruct->Longitude[PayloadSize-(pEndString-pPayload)] = 0; + +} + +/** + * @brief This function read the geoloccation information and store data in a structure. + * @param pRecordStruct : Pointer on the record structure. + * @param pGeoStruct : pointer on the structure to fill. + */ +static void NDEF_ReadURI_Geo( sRecordInfo_t *pRecordStruct, sGeoInfo *pGeoStruct ) +{ + uint8_t* pPayload; + uint32_t PayloadSize; + + PayloadSize = pRecordStruct->PayloadLength; + + /* Read record header */ + pPayload = (uint8_t*)(pRecordStruct->PayloadBufferAdd); + + if( pRecordStruct->NDEF_Type == URI_GEO_TYPE ) + NDEF_FillGeoStruct( pPayload , PayloadSize, pGeoStruct ); + +} + +/** + * @} + */ + +/** @defgroup libGeo_Public_Functions + * @{ + * @brief This file is used to manage geolocation (stored or loaded in tag) + */ + +/** + * @brief This function read NDEF and retrieve Geo information if any. + * @param pRecordStruct : Pointer on the record structure. + * @param pGeoStruct : pointer on the structure to fill . + * @retval NDEF_OK : Geolocation information from NDEF have been retrieved. + * @retval NDEF_ERROR : not able to read NDEF from tag. + */ +uint16_t NDEF_ReadGeo( sRecordInfo_t *pRecordStruct, sGeoInfo *pGeoStruct ) +{ + uint16_t status = NDEF_ERROR; + sRecordInfo_t *pSPRecordStruct; + uint32_t PayloadSize, RecordPosition; + uint8_t* pData; + + if( pRecordStruct->NDEF_Type == URI_GEO_TYPE ) + { + NDEF_ReadURI_Geo( pRecordStruct, pGeoStruct ); + status = NDEF_OK; + } + else if( pRecordStruct->NDEF_Type == SMARTPOSTER_TYPE ) + { + for( RecordPosition = 0; RecordPosition < pRecordStruct->NbOfRecordInSPPayload; RecordPosition++ ) + { + pSPRecordStruct = pRecordStruct->SPRecordStructAdd[RecordPosition]; + if( pSPRecordStruct->NDEF_Type == URI_GEO_TYPE ) + { + NDEF_ReadURI_Geo( pSPRecordStruct, pGeoStruct ); + status = NDEF_OK; + } + if( pSPRecordStruct->NDEF_Type == TEXT_TYPE ) + { + PayloadSize = pSPRecordStruct->PayloadLength; + + /* The instruction content the UTF-8 language code that is not used here */ + pData = (uint8_t*)pSPRecordStruct->PayloadBufferAdd; + PayloadSize -= *pData + 1; /* remove not usefull data */ + pData += *pData + 1; /* set pointer on usefull data */ + + memcpy( pGeoStruct->Information, pData, PayloadSize ); + /* add end of string character */ + pGeoStruct->Information[PayloadSize] = 0; + } + } + } + + return status; +} + +/** + * @brief This function write the NDEF file with the geolocation data given in the structure. + * @param pGeoStruct : pointer on structure that contain the geolocation information. + * @retval NDEF_OK : the function is succesful. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be write. + */ +uint16_t NDEF_WriteGeo( sGeoInfo *pGeoStruct ) +{ + uint16_t status = NDEF_ERROR,Offset = 0; + + NDEF_PrepareGeoMessage( pGeoStruct, NDEF_Buffer, &Offset ); + + status = NfcTag_WriteNDEF( Offset, NDEF_Buffer ); + + return status; +} + +/** + * @brief This function write the NDEF file with the geolocation data given in the structure. + * @param pGeoStruct : pointer on structure that contain the geolocation information. + * @param pNDEFMessage : pointer on the NDEF message. + * @param size : to store the size of the NDEF message generated. + */ +void NDEF_PrepareGeoMessage( sGeoInfo *pGeoStruct, uint8_t *pNDEFMessage, uint16_t *size ) +{ + uint16_t Offset = 0; + uint32_t geoSize = 0; + uint32_t infoSize = 0; + uint32_t totalSize = 0; + + /* GEO is an URI but can be included in a smart poster to add text to give instruction to user for instance */ + + /* GEO (smart poster) Record Header */ +/************************************/ +/* 7 | 6 | 5 | 4 | 3 | 2 1 0 */ +/*----------------------------------*/ +/* MB ME CF SR IL TNF */ /* <---- CF=0, IL=0 and SR=1 TNF=1 NFC Forum Well-known type*/ +/*----------------------------------*/ +/* TYPE LENGTH */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 3 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 2 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 1 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 0 */ +/*----------------------------------*/ +/* ID LENGTH */ /* <---- Not Used */ +/*----------------------------------*/ +/* TYPE */ +/*----------------------------------*/ +/* ID */ /* <---- Not Used */ +/************************************/ + + /* GEO : 1+geo:+latitude+1+longitude */ + geoSize = 1 + GEO_TYPE_STRING_LENGTH + strlen(pGeoStruct->Latitude) + URI_LATITUDE_END_LENGTH + strlen(pGeoStruct->Longitude); + + /* Check if a Smart poster is needed */ + if( pGeoStruct->Information[0] != '\0' ) + { + /* Info : 1+2+info */ + infoSize = 1 + ISO_ENGLISH_CODE_STRING_LENGTH + strlen(pGeoStruct->Information); + /* Total */ + totalSize = 4 + geoSize + 4 + infoSize; + if( geoSize > 255 ) totalSize += 3; /* Normal Geo size */ + if( infoSize > 255 ) totalSize += 3; /* Normal Info size */ + + /* SmartPoster header */ + if( totalSize > 255 ) + { + pNDEFMessage[Offset++] = 0xC1; + pNDEFMessage[Offset++] = SMART_POSTER_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (totalSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (totalSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (totalSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = totalSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = 0xD1; + pNDEFMessage[Offset++] = SMART_POSTER_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (uint8_t)totalSize; + } + memcpy( &pNDEFMessage[Offset], SMART_POSTER_TYPE_STRING, SMART_POSTER_TYPE_STRING_LENGTH ); + Offset += SMART_POSTER_TYPE_STRING_LENGTH; + } + + /* GEO header */ + pNDEFMessage[Offset] = 0x81; + if( geoSize < 256 ) pNDEFMessage[Offset] |= 0x10; // Set the SR bit + if( pGeoStruct->Information[0] == '\0' ) pNDEFMessage[Offset] |= 0x40; // Set the ME bit + Offset++; + + pNDEFMessage[Offset++] = URI_TYPE_STRING_LENGTH; + if( geoSize > 255 ) + { + pNDEFMessage[Offset++] = (geoSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (geoSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (geoSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = geoSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = (uint8_t)geoSize; + } + memcpy( &pNDEFMessage[Offset], URI_TYPE_STRING, URI_TYPE_STRING_LENGTH ); + Offset += URI_TYPE_STRING_LENGTH; + + /* GEO payload */ + pNDEFMessage[Offset++] = URI_ID_0x00; /* URI identifier no abbreviation */ + memcpy( &pNDEFMessage[Offset], GEO_TYPE_STRING, GEO_TYPE_STRING_LENGTH ); + Offset += GEO_TYPE_STRING_LENGTH; + memcpy( &pNDEFMessage[Offset], pGeoStruct->Latitude, strlen(pGeoStruct->Latitude) ); + Offset += strlen( pGeoStruct->Latitude ); + memcpy( &pNDEFMessage[Offset], URI_LATITUDE_END, URI_LATITUDE_END_LENGTH ); + Offset += URI_LATITUDE_END_LENGTH; + memcpy( &pNDEFMessage[Offset], pGeoStruct->Longitude, strlen(pGeoStruct->Longitude) ); + Offset += strlen( pGeoStruct->Longitude ); + + /* Information header */ + if( pGeoStruct->Information[0] != '\0' ) + { + if( infoSize > 255 ) + { + pNDEFMessage[Offset++] = 0x41; + pNDEFMessage[Offset++] = TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (infoSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (infoSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (infoSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = infoSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = 0x51; + pNDEFMessage[Offset++] = TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (uint8_t)infoSize; + } + + memcpy( &pNDEFMessage[Offset], TEXT_TYPE_STRING, TEXT_TYPE_STRING_LENGTH ); + Offset += TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = ISO_ENGLISH_CODE_STRING_LENGTH; /* UTF-8 with x byte language code */ + memcpy( &pNDEFMessage[Offset], ISO_ENGLISH_CODE_STRING, ISO_ENGLISH_CODE_STRING_LENGTH ); + Offset += ISO_ENGLISH_CODE_STRING_LENGTH; + + /* Information payload */ + memcpy( &pNDEFMessage[Offset], pGeoStruct->Information, strlen(pGeoStruct->Information) ); + Offset += strlen( pGeoStruct->Information ); + } + + *size = (uint16_t)(Offset); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Handover.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Handover.c new file mode 100644 index 0000000..d538529 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Handover.c @@ -0,0 +1,509 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Bluetooth.c + * @author MMY Application Team + * @version $Revision: 2702 $ + * @date $Date: 2016-07-13 18:45:05 +0200 (Wed, 13 Jul 2016) $ + * @brief This file helps to manage a NDEF Handover message. + * @ingroup libNDEF_Handover + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_Handover.h" + +/** @addtogroup lib_NDEF_Handover NDEF Handover library + * @ingroup libNDEF + * @brief This module is used to manage the NDEF Handover messages, to negociate the switch to a non-nfc protocol of communication. + * @details + * The NDEF Handover process is described by the NFC Forum Connection Handover specification. + * It consists in a specific NDEF message construct, as: + * - NDEF 1st record: Handover Request or Handover Select record + * - Version + * - Collision Resolution (nested record, optional) + * - Random number + * - Alternative Carrier 1 (nested record) + * - Power state + * - Reference Data + * - Auxiliary Data Reference 1 + * - ... + * - Auxiliary Data Reference N + * - ... + * - Alternative Carrier N (nested record) + * - NDEF record 2+: Alternative Carrier or Auxiliary Data: Connection details for one of the AC (record ID is the AC Reference Data or an Auxiliary Data Reference). + * - ... + * - NDEF record N: Alternative Carrier or Auxiliary Data: Connection details for one of the AC (record ID is the AC Reference Data or an Auxiliary Data Reference). + * _________________ + * @section Handover_Library_Usage NDEF Handover Library usage: + * @subsection Static_Handover Static Handover + * The Static Handover is used when a device is only equipped with a NFC Tag (no peer-to-peer) to directly propose a set of Alternative Carriers (ACs: bluetooth, wifi,...) + * without running the full handover request-select process.\n + * The Handover Select record use in that case is similar to the one used during a regular Handover negociation.\n + * 1. Declare & initialize an instance of `Ndef_Handover_t`, such as: + * + * Ndef_Handover_t wHandover = {.type = NDEF_HANDOVER_SELECT_TYPE, .version = NDEF_HANDOVER_VERSION_1_2}; + * 2. Declare a `sRecordInfo_t` instance: + * + * sRecordInfo_t HandoverRecord; + * 3. Call the `NDEF_CreateHandover` function, to start preparing the Handover Select record + * + * NDEF_CreateHandover(&wHandover,&HandoverRecord); + * 4. Call the `NDEF_AddAlternativeCarrier` for each Alternative Carrier (such as Bluetooth, Wifi, ...) + * 5. Declare and initialize as many `Ndef_Handover_alternative_carrier_t` instances as the number of non-NFC protocol available. + * And then call the `NDEF_AddAlternativeCarrier` for each of them. + * + * Ndef_Handover_alternative_carrier_t wAC_BREDR = {.cps = NDEF_HANDOVER_AC_CPS_ACTIVE, + * .aux_data_ref_count = 0}; + * Ndef_Handover_alternative_carrier_t wAC_BLE = {.cps = NDEF_HANDOVER_AC_CPS_ACTIVE, + * .aux_data_ref_count = 0}; + * Ndef_Handover_alternative_carrier_t wAC_Wifi = {.cps = NDEF_HANDOVER_AC_CPS_ACTIVE, + * .aux_data_ref_count = 0}; + * + * NDEF_AddAlternativeCarrier(&wAC_BREDR,"urn:nfc:handover:bredr", NULL,&HandoverRecord ); + * NDEF_AddAlternativeCarrier(&wAC_BLE,"urn:nfc:handover:ble", NULL,&HandoverRecord ); + * NDEF_AddAlternativeCarrier(&wAC_Wifi,"urn:nfc:handover:wifi", NULL,&HandoverRecord ); + * @note + * 1. In this example a single `Ndef_Handover_alternative_carrier_t` could have been used, as the parameters are the same for all ACs. + * 2. If more than one NDEF record is required to provide the AC connection details, the `aux_data_ref_count` must specify the number of additional records. + * + * Ndef_Handover_alternative_carrier_t wAC_Wifi = {.cps = NDEF_HANDOVER_AC_CPS_ACTIVE, + * .aux_data_ref_count = 2}; + * Then, it's required to initialize an array of pointers to these Auxiliary Data Reference, as: + * + * char *aux_data_ref1 = "urn:nfc:handover:wifi:aux_data_ref1"; + * char *aux_data_ref2 = "urn:nfc:handover:wifi:aux_data_ref2"; + * char *wifi_aux_ref_data_array[2] = {aux_data_ref1,aux_data_ref2}; + * And then provide this array as the 3rd argument to the 'NDEF_AddAlternativeCarrier' function: + * + * NDEF_AddAlternativeCarrier(&wAC_Wifi,"urn:nfc:handover:wifi", wifi_aux_ref_data_array,&HandoverRecord ); + * 6. Call the `NDEF_WriteHandover` function to finalize the NDEF message and write it to the tag. + * + * NDEF_WriteHandover(&HandoverRecord, NDEF_Buffer); + * 7. Then call other functions (from the libNDEF or not) to add records, describing the Alternative Carriers, to the NDEF message: + * + * NDEF_AppendBluetoothOOB ( &w_ble_oob, "urn:nfc:handover:ble" ); + * NDEF_AppendBluetoothOOB ( &w_bredr_oob, "urn:nfc:handover:bredr" ); + * @note + * 1. The ID of these additional records (2nd argument in the above example) must match the Data Reference provided within the Handover record. + * 2. If Auxiliary Data References are expected they must also be added to the NDEF message, with their ID matching the ID provided to the Alternative Carrier record. + * + * @section Reading_Handover Reading through a Handover Request message + * 1. Read the 1st record of the NDEF message: + * + * sRecordInfo_t rRecord; + * NDEF_ReadNDEF(NDEF_Buffer); + * NDEF_IdentifyBuffer(rRecord,NDEF_Buffer); + * 2. Decode the handover: + * + * Ndef_Handover_t rHandover; + * NDEF_ReadHandover(&rRecord , &rHandover ); + * 3. Read all Alternative Carrier records, and their Auxiliary Data References if any. + * + * uint8_t ac_index, aux_index; + * for(ac_index=0;ac_indexaux_data_ref_start; + uint8_t current_aux = 0; + uint8_t* aux_id; + uint8_t aux_id_length; + + if((pAC->aux_data_ref_start == NULL) || + (pAC->aux_data_ref_end == NULL) || + (pAC->aux_data_ref_count == 0) || + (aux_data_nb >= pAC->aux_data_ref_count)) + return NDEF_ERROR; + + + while((current_aux < aux_data_nb) && (pData < pAC->aux_data_ref_end)) + { + aux_id_length = *pData++; + aux_id = pData; + pData += aux_id_length; + current_aux++; + } + + pData = pAC->aux_data_ref_end; + /* if ac has been found */ + if(current_aux == aux_data_nb) + { + /* let's now look for the corresponding record - must be after the Handover record */ + do { + status = NDEF_IdentifyBuffer(pRecord,pData); + if(status != NDEF_OK) return status; + pData = pAC->ac_record.PayloadBufferAdd; + + if((pRecord->IDLength == aux_id_length) && + !memcmp(pRecord->ID, aux_id,aux_id_length)) + { + /* this is the record we were looking for, so exit */ + return NDEF_OK; + } + + // go to next record + pData = pRecord->PayloadBufferAdd + pRecord->PayloadLength; + + } while (!(pRecord->RecordFlags & MB_Mask)); + + } + // if we go there, it means that the record ID is not found + return NDEF_ERROR; +} + + + +/** + * @brief This function reads the NDEF message and retrieves the nth Alternative Carrier record if present. + * @param ac_nb Position of the Alternative Carrier Reference in the Handover record. + * @param pHandover Pointer to the Handover record where to find the AC Reference Data. + * @param pAC Pointer used to return the output Alternative Carrier record. + * @retval NDEF_OK The Alternative Carrier record has been retrieved. + * @retval NDEF_ERROR Not able to find the Alternative Carrier in the NDEF message. + */ +uint16_t NDEF_ReadAC( uint8_t ac_nb, Ndef_Handover_t *pHandover , Ndef_Handover_alternative_carrier_t *pAC ) +{ + uint16_t status; + uint8_t* pData = pHandover->ac_start; + uint8_t current_ac = 0; + uint8_t* ac_id; + uint8_t ac_id_length; + sRecordInfo_t NestedRecord; + uint8_t ac_found = 0; + + if((pHandover->ac_start == NULL) || + (pHandover->ac_end == NULL) || + (pHandover->nb_alternative_carrier == 0) || + (ac_nb >= pHandover->nb_alternative_carrier)) + return NDEF_ERROR; + + // Default handover init + pAC->aux_data_ref_count = 0; + + while((current_ac <= ac_nb)&&(current_ac <= pHandover->nb_alternative_carrier) && (pData < pHandover->ac_end)) + { + status = NDEF_IdentifyBuffer(&NestedRecord,pData); + if(status != NDEF_OK) return status; + // go to payload address + pData = NestedRecord.PayloadBufferAdd; + + if(!memcmp(NestedRecord.Type,NDEF_HANDOVER_ALTERNATIVE_CARRIER_TYPE_STR,strlen(NDEF_HANDOVER_ALTERNATIVE_CARRIER_TYPE_STR))) + { + if(current_ac == ac_nb) + { + // parse the AC now + pAC->cps = pData[0] & NDEF_HANDOVER_AC_CPS_MASK; + ac_id_length = pData[1]; + ac_id = &pData[2]; + pAC->aux_data_ref_count = pData[2 + ac_id_length]; + pAC->aux_data_ref_start = &pData[3 + ac_id_length]; + pAC->aux_data_ref_end = pData + NestedRecord.PayloadLength; + ac_found = 1; + } + current_ac++; + } + // go to next record + pData += NestedRecord.PayloadLength; + } + pData = pHandover->ac_end; + /* if ac has been found */ + if(ac_found) + { + /* let's now look for the corresponding record - must be after the Handover record */ + do { + status = NDEF_IdentifyBuffer(&pAC->ac_record,pData); + if(status != NDEF_OK) return status; + pData = pAC->ac_record.PayloadBufferAdd; + + if((pAC->ac_record.IDLength == ac_id_length) && + !memcmp(pAC->ac_record.ID, ac_id,ac_id_length)) + { + /* this is the record we were looking for, so exit */ + return NDEF_OK; + } + + // go to next record + pData = pAC->ac_record.PayloadBufferAdd + pAC->ac_record.PayloadLength; + // TO DO: add a security condition to avoid infinite loop if NDEF file is corrupted + } while (!(pAC->ac_record.RecordFlags & ME_Mask)); + + } + // if we go there, it means that the record ID is not found + return NDEF_ERROR; +} + + +/** + * @brief This function reads a record and retrieves the Handover information if present. + * @param pRecord Pointer on the record structure to be read. + * @param pHandover Pointer used to return the Handover information. + * @retval NDEF_OK Handover information has been retrieved from the record. + * @retval NDEF_ERROR Not able to read the Handover information from the record. + */ +uint16_t NDEF_ReadHandover(sRecordInfo_t *pRecord , Ndef_Handover_t *pHandover ) +{ + uint16_t status; + uint8_t* pData = pRecord->PayloadBufferAdd; + uint8_t* pEnd = pData + pRecord->PayloadLength; + sRecordInfo_t NestedRecord; + + /* Default Handover Structure init */ + pHandover->version =0; + pHandover->nb_alternative_carrier =0; + pHandover->has_cr = 0; + pHandover->ac_start = NULL; + pHandover->ac_end = NULL; + + /* A Handover record should never be the end of the NDEF message */ + if(pRecord->RecordFlags & ME_Mask) + return NDEF_ERROR; + + if( !memcmp(pRecord->Type,NDEF_HANDOVER_REQUEST_TYPE_STR,strlen(NDEF_HANDOVER_REQUEST_TYPE_STR)) ) + { + pHandover->type = NDEF_HANDOVER_REQUEST_TYPE; + } else if ( !memcmp(pRecord->Type,NDEF_HANDOVER_SELECT_TYPE_STR,strlen(NDEF_HANDOVER_SELECT_TYPE_STR)) ) + { + pHandover->type = NDEF_HANDOVER_SELECT_TYPE; + } else { + /* This is not a Handover record! */ + return NDEF_ERROR; + } + + pHandover->version = *pData++; + + /* Following records are nested into Hr/s record */ + while (pData < pEnd) + { + status = NDEF_IdentifyBuffer(&NestedRecord,pData); + if(status != NDEF_OK) return status; + /* save record address */ + uint8_t* pACRecord = pData; + /* go to payload address */ + pData = NestedRecord.PayloadBufferAdd; + + /* Parse Collision Resolution if Handover request */ + if(pHandover->type == NDEF_HANDOVER_REQUEST_TYPE) + { + + if(!memcmp(NestedRecord.Type,NDEF_HANDOVER_COLLISION_RESOLUTION_TYPE_STR,strlen(NDEF_HANDOVER_COLLISION_RESOLUTION_TYPE_STR))) + { + pHandover->has_cr = 1; + pHandover->cr_random_number = *(uint16_t*)pData; + } + } + + /* Parse AlternativeCarriers just to know how many they are */ + else if(!memcmp(NestedRecord.Type,NDEF_HANDOVER_ALTERNATIVE_CARRIER_TYPE_STR,strlen(NDEF_HANDOVER_ALTERNATIVE_CARRIER_TYPE_STR))) + { + pHandover->nb_alternative_carrier++; + if(pHandover->ac_start == NULL) + pHandover->ac_start = pACRecord; + pHandover->ac_end = pData + NestedRecord.PayloadLength; + /* don't parse the AC now */ + } + else { + /* this is an unexpected type, just ignore it */ + } + /* go to next record */ + pData += NestedRecord.PayloadLength; + + } + + return NDEF_OK; +} + +/** + * @brief This function prepares the Handover record with the data given in the Handover structure. + * @param pHandover Pointer on structure containing the handover basic information. + * @param pRecord Pointer used to return the prepared Handover record. + * @retval NDEF_OK The record has been prepared. + * @retval NDEF_ERROR The record has not been prepared. + */ +uint16_t NDEF_CreateHandover(Ndef_Handover_t *pHandover, sRecordInfo_t* pRecord ) +{ + uint16_t status = NDEF_ERROR; + + /* Use a static buffer to prepare the Handover record */ + pRecord->PayloadBufferAdd = NDEF_Record_Buffer; + /* Alternative, where the user must first allocate the Payload buffer in the record: + * if (pRecord->PayloadBufferAdd == NULL) + * return NDEF_ERROR; + */ + + /* Handover MUST be the first record (SR mask to be updated when actually writing the record) */ + pRecord->RecordFlags = MB_Mask | ME_Mask | TNF_WellKnown; + + if(pHandover->type == NDEF_HANDOVER_SELECT_TYPE) + { + pRecord->TypeLength = strlen(NDEF_HANDOVER_SELECT_TYPE_STR); + memcpy(pRecord->Type, NDEF_HANDOVER_SELECT_TYPE_STR,pRecord->TypeLength); + } + else if (pHandover->type == NDEF_HANDOVER_REQUEST_TYPE) + { + pRecord->TypeLength = strlen(NDEF_HANDOVER_SELECT_TYPE_STR); + memcpy(pRecord->Type, NDEF_HANDOVER_REQUEST_TYPE_STR,pRecord->TypeLength); + } + else + return NDEF_ERROR; + + pRecord->PayloadLength = sizeof(pHandover->version); + *pRecord->PayloadBufferAdd = pHandover->version; + + /* Don't write the record for now, additionnal Alternative Carriers to come as nested records. */ + + return status; +} + + +/** + * @brief This function adds an Alternative Carrier record to a Handover record using the data given in the AC structure. + * @param pAC Pointer on input AC structure. + * @param CarrierDataRef String with the Alternative Carrier Data Reference (ID of the corresponding record in the NDEF message). + * @param AuxDataRefID Array with pointers to the Auxiliary Data References (as many as defined in pAC structure). + * @param pRecord Pointer on the Handover record to be filled with the AC data, must have been previously initialized with the NDEF_CreateHandover function. + * @retval NDEF_OK The Handover record has been updated with AC information. + * @retval NDEF_ERROR The Handover record cannot be updated with the AC information. + * @retval NDEF_ERROR_MEMORY_INTERNAL The internal buffer for records is too small to add the AC information. + */ +uint16_t NDEF_AddAlternativeCarrier(Ndef_Handover_alternative_carrier_t *pAC,char *CarrierDataRef, char **AuxDataRefID, sRecordInfo_t* pRecord ) +{ + /* Specific buffer to prepare the Alternative Carrier record */ + uint8_t NDEF_AlternativeCarrier_Buffer[NDEF_AC_BUFFER_SIZE]; + + /* check that there is enough space in the buffers */ + pAC->ac_record.PayloadLength = NDEF_GetACDataLength(pAC,CarrierDataRef,AuxDataRefID); + if(((pRecord->PayloadLength + pAC->ac_record.PayloadLength) > NDEF_RECORD_MAX_SIZE) || + (pAC->ac_record.PayloadLength > NDEF_AC_BUFFER_SIZE)) + return NDEF_ERROR_MEMORY_INTERNAL; + + /* Use specific buffer to prepare the nested record */ + uint8_t *pData = NDEF_AlternativeCarrier_Buffer; + pAC->ac_record.PayloadBufferAdd = pData; + /* Following line is an alternative where the user must allocate the payload buffer of the ac_record: + * uint8_t* pData = pAC->ac_record.PayloadBufferAdd ; + */ + + if ((pRecord->PayloadBufferAdd == NULL) || + (pRecord->PayloadLength == 0)) + return NDEF_ERROR; + + /* AC is not the first record */ + pAC->ac_record.RecordFlags = TNF_WellKnown; + + pAC->ac_record.TypeLength = strlen(NDEF_HANDOVER_ALTERNATIVE_CARRIER_TYPE_STR); + memcpy(pAC->ac_record.Type, NDEF_HANDOVER_ALTERNATIVE_CARRIER_TYPE_STR,pAC->ac_record.TypeLength); + + /* Length : cps byte + data ref length byte + auxiliary data ref count byte + data ref length */ + *pData++ = pAC->cps & NDEF_HANDOVER_AC_CPS_MASK; + *pData++ = strlen(CarrierDataRef); + memcpy(pData, CarrierDataRef, strlen(CarrierDataRef)); + pData += strlen(CarrierDataRef); + *pData++ = pAC->aux_data_ref_count; + + uint8_t AuxDataIndex; + for(AuxDataIndex = 0;AuxDataIndexaux_data_ref_count;AuxDataIndex++) + { + *pData++ = strlen(AuxDataRefID[AuxDataIndex]); + memcpy(pData, AuxDataRefID[AuxDataIndex], strlen(AuxDataRefID[AuxDataIndex])); + pData += strlen(AuxDataRefID[AuxDataIndex]); + } + + /* Append the nested record right after the Handover record - increase its length accordingly */ + pRecord->PayloadLength += NDEF_WriteRecord(&pAC->ac_record,pRecord->PayloadBufferAdd + pRecord->PayloadLength); + return NDEF_OK; +} + + +/** + * @brief This function returns the length of an Alternative Carrier record data (excluding the record metadata). + * @param pAC Pointer on the input AC structure. + * @param CarrierDataRef String with the Alternative Carrier Data Reference. + * @param AuxDataRefID Array with the Auxiliary Data References (as many as defined in the pAC structure). + * @return The computed length in bytes corresponding to the provided Alternative Carrier information. + */ +uint32_t NDEF_GetACDataLength(Ndef_Handover_alternative_carrier_t *pAC,char *CarrierDataRef, char **AuxDataRefID) +{ + uint8_t AuxDataIndex; + + /* First compute the Data length */ + uint32_t length = 1 + // cps + 1 + // Carrier data ref length + strlen(CarrierDataRef) + // Carrier data ref + 1 + // auxiliary data count + pAC->aux_data_ref_count * 1; // auxiliary data lengths + + /* Then adds the length of the Auxiliary Data */ + for(AuxDataIndex = 0;AuxDataIndexaux_data_ref_count;AuxDataIndex++) + { + length += strlen(AuxDataRefID[AuxDataIndex]); + } + + return length; +} + +/** + * @brief This function writes the Handover record into the memory. + * @param pRecord Pointer on the input Handover record. + * @param pNdef Pointer to a NDEF buffer (used to prepare the data before actual writing to the memory). + * @retval NDEF_OK The memory has been written. + * @retval NDEF_ERROR_MEMORY_INTERNAL Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED Tag locked, cannot be write. + */ +uint16_t NDEF_WriteHandover( sRecordInfo_t* pRecord , uint8_t* pNdef) +{ + /* Note: in case of Handover Select for no matching alternative carrier, the ME bit flag must be set by the caller */ + + uint32_t Size = NDEF_WriteRecord(pRecord,pNdef); + return NDEF_WriteNDEF(Size,pNdef); +} + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_MyApp.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_MyApp.c new file mode 100644 index 0000000..e634de4 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_MyApp.c @@ -0,0 +1,277 @@ +/** + ****************************************************************************** + * @file lib_NDEF_MyApp.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage the NDEF file of a private application. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_MyApp.h" + + +/** @addtogroup NFC_libraries + * @{ + * @brief This is the library used to manage the content of the TAG (data) + * But also the specific feature of the tag, for instance + * password, gpio... + */ + + +/** @addtogroup libNFC_FORUM + * @{ + * @brief This part of the library manage data which follow NFC forum organisation. + */ + +/** + * @brief This buffer contains the data send/received by TAG + */ +extern uint8_t NDEF_Buffer []; + +/** @defgroup libMyApp_Private_Functions + * @{ + */ + +static void NDEF_Extract_M24SRDiscoveryApp_Input( sRecordInfo_t *pRecordStruct, sMyAppInfo *pMyAppStruct ); + +/** + * @brief This function read the NDEF file and store application data in a structure. + * @param pRecordStruct : Pointer on the record structure. + * @param pMyAppStruct : pointer on the structure to fill. + */ +static void NDEF_Extract_M24SRDiscoveryApp_Input( sRecordInfo_t *pRecordStruct, sMyAppInfo *pMyAppStruct ) +{ + uint8_t* pPayload; + uint8_t* pLook4Word; + uint16_t BackGroundColor, FontColor; + uint8_t i; + + /* Read record header */ + pPayload = (uint8_t*)(pRecordStruct->PayloadBufferAdd); + + /* initialize struct in case not matching found */ + for( i = 0; i < 8; i++ ) + { + /* Set the Back Color */ + pMyAppStruct->LineX[i].BackGroundColor = 0xFFFF; + /* Set the Text Color */ + pMyAppStruct->LineX[i].FontColor = 0x0000; + /* Set the line number */ + pMyAppStruct->LineX[i].LineNb = i + 1; + /* Set the line content */ + memcpy( pMyAppStruct->LineX[i].String, " ", 20 ); + } + + pLook4Word = pPayload; + + for( i = 0; i < 4; i++ ) + { + pMyAppStruct->LedBlinkConf.LedConf[i] = *pLook4Word; + pLook4Word++; + } + pMyAppStruct->LedBlinkConf.Speed = *pLook4Word; + pLook4Word++; + + for( i = 0; i < 8; i++ ) + { + /* Set the line number */ + pMyAppStruct->LineX[i].LineNb = *pLook4Word; + pLook4Word++; + /* Set the Back Color */ + BackGroundColor = (uint16_t)(*pLook4Word << 8); + BackGroundColor = BackGroundColor | (uint16_t)(*++pLook4Word ); + pMyAppStruct->LineX[i].BackGroundColor = BackGroundColor; + pLook4Word++; + /* Set the Text Color */ + FontColor = (uint16_t)(*pLook4Word << 8); + FontColor = FontColor | (uint16_t)(*++pLook4Word); + pMyAppStruct->LineX[i].FontColor = FontColor; + pLook4Word++; + /* Set the line content */ + memcpy( pMyAppStruct->LineX[i].String, (char*)pLook4Word, 20 ); + pLook4Word += 20; + } + +} + +/** + * @} + */ + +/** @defgroup libMyApp_Public_Functions + * @{ + * @brief This file is used to manage proprietary NDEF (stored or loaded in tag) + */ + +/** + * @brief This function read NDEF and retrieve Application information if any. + * @param pRecordStruct : Pointer on the record structure. + * @param pMyAppStruct : pointer on the structure to fill. + * @retval NDEF_OK : NDEF file data read in the tag. + * @retval NDEF_ERROR : not able to read NDEF in tag. + */ +uint16_t NDEF_ReadMyApp( sRecordInfo_t *pRecordStruct, sMyAppInfo *pMyAppStruct ) +{ + uint16_t status = NDEF_ERROR; + + if( pRecordStruct->NDEF_Type == M24SR_DISCOVERY_APP_TYPE ) + { + NDEF_Extract_M24SRDiscoveryApp_Input( pRecordStruct, pMyAppStruct ); + status = NDEF_OK; + } + else + { + status = NDEF_ERROR; + } + + return status; +} + +/** + * @brief This function write the NDEF file with the Application data given in the structure. + * @brief Only used for debug purpose in this firmware version. + * @param pMyAppStruct : pointer on structure that contain the application information. + * @retval NDEF_OK : NDEF file data written in the tag. + * @retval NDEF_ERROR : not able to store NDEF in tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be write. + */ +uint16_t NDEF_WriteMyApp( sMyAppInfo *pMyAppStruct ) +{ + uint16_t status = NDEF_ERROR; + uint16_t DataSize; + uint32_t PayloadSize; + uint8_t i; + uint8_t* pPayload; + + +/* External Type Record Header */ +/************************************/ +/* 7 | 6 | 5 | 4 | 3 | 2 1 0 */ +/*----------------------------------*/ +/* MB ME CF SR IL TNF */ /* <---- IL=0, CF=0 and SR=1 TNF=4 NFC Forum external type*/ +/*----------------------------------*/ +/* TYPE LENGTH */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 3 */ /* <---- Not Used */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 2 */ /* <---- Not Used */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 1 */ /* <---- Not Used */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 0 */ /* The payload will always be 5 + 25*8=205 bytes for this application */ +/*----------------------------------*/ +/* ID LENGTH */ /* <---- Not Used */ +/*----------------------------------*/ +/* TYPE */ /* st.com:m24sr_discovery_democtrl */ +/*----------------------------------*/ +/* ID */ /* <---- Not Used */ +/************************************/ + + + /* fill URI record header */ + NDEF_Buffer[0] = 0xD4; /* Record Flag */ + NDEF_Buffer[1] = M24SR_DISCOVERY_APP_STRING_LENGTH; + NDEF_Buffer[2] = 0x00; /* Will be filled at the end when payload size is known */ + + memcpy( &NDEF_Buffer[3], M24SR_DISCOVERY_APP_STRING, M24SR_DISCOVERY_APP_STRING_LENGTH ); + + pPayload = &NDEF_Buffer[ 3 + M24SR_DISCOVERY_APP_STRING_LENGTH]; + PayloadSize = 0; + + /**************************************************************/ + /* BLINK CONFIG data */ + + /* led 1 blinking */ + *pPayload = 0x03; + pPayload++; + /* led 2 blinking */ + *pPayload = 0x02; + pPayload++; + /* led 3 blinking */ + *pPayload = 0x02; + pPayload++; + /* led 4 blinking */ + *pPayload = 0x03; + pPayload++; + /* speed */ + *pPayload = 0x03; + pPayload++; + + PayloadSize += 5; + + /**************************************************************/ + + /**************************************************************/ + /* SCREEN config data */ + for( i = 0; i < 8; i++ ) + { + /* Line number */ + *pPayload = (uint8_t)(i + 1); + pPayload++; + /* Background color */ + *pPayload = 0xFF - (0xFF/i); + pPayload++; + *pPayload = 0xFF - (0xFF/i); + pPayload++; + /* Font Color */ + *pPayload = 0xFF/i; + pPayload++; + *pPayload = 0xFF/i; + pPayload++; + /* String */ + memcpy( pPayload, "ABCDEFGHIJKLMNOPQRST", 20 ); + pPayload += 20; + + PayloadSize += 25; + + } + + NDEF_Buffer[2] = PayloadSize & 0x000000FF; + + DataSize = PayloadSize + 5 + M24SR_DISCOVERY_APP_STRING_LENGTH; + + /* Write NDEF */ + status = NfcTag_WriteNDEF( DataSize, NDEF_Buffer ); + + + return status; +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_SMS.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_SMS.c new file mode 100644 index 0000000..a0a6082 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_SMS.c @@ -0,0 +1,370 @@ +/** + ****************************************************************************** + * @file lib_NDEF_SMS.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage NDEF file that represent SMS. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_SMS.h" + + +/** @addtogroup NFC_libraries + * @{ + * @brief This is the library used to manage the content of the TAG (data) + * But also the specific feature of the tag, for instance + * password, gpo... + */ + + +/** @addtogroup libNFC_FORUM + * @{ + * @brief This part of the library manage data which follow NFC forum organisation. + */ + +/** + * @brief This buffer contains the data send/received by TAG + */ +extern uint8_t NDEF_Buffer []; + +/** @defgroup libSMS_Private_Functions + * @{ + */ + +static void NDEF_FillSMSStruct( uint8_t* pPayload, uint32_t PayloadSize, sSMSInfo *pSMSStruct ); +static void NDEF_ReadURI_SMS( sRecordInfo_t *pRecordStruct, sSMSInfo *pSMSStruct ); + +/** + * @brief This function fill SMS structure with information of NDEF message. + * @param pPayload : pointer on the payload data of the NDEF message. + * @param PayloadSize : number of data in the payload. + * @param pSMSStruct : pointer on the structure to fill. + */ +static void NDEF_FillSMSStruct( uint8_t* pPayload, uint32_t PayloadSize, sSMSInfo *pSMSStruct ) +{ + uint8_t* pLastByteAdd, *pLook4Word, *pEndString; + char* pKeyWord; + uint32_t SizeOfKeyWord; + pEndString = 0; + + pKeyWord = SMS_TYPE_STRING; + SizeOfKeyWord = SMS_TYPE_STRING_LENGTH; + + /* First character force to NULL in case not matching found */ + *pSMSStruct->PhoneNumber = 0; + *pSMSStruct->Message = 0; + + /* Interesting information are stored before picture if any */ + /* Moreover picture is not used in this demonstration SW */ + pLastByteAdd = (uint8_t*)(pPayload + PayloadSize); + + pLook4Word = pPayload; + while( memcmp( pLook4Word, pKeyWord, SizeOfKeyWord ) && (pLook4Word < pLastByteAdd) ) + { + pLook4Word++; + } + + /* Retrieve phone number */ + if( pLook4Word != pLastByteAdd ) + { + pLook4Word += SizeOfKeyWord; + pEndString = pLook4Word; + while( memcmp( pEndString, URI_FIRST_DATA_END, URI_FIRST_DATA_END_LENGTH ) && (pEndString < pLastByteAdd) ) + { + pEndString++; + } + if( pEndString != pLastByteAdd ) + { + memcpy( pSMSStruct->PhoneNumber, pLook4Word, pEndString-pLook4Word ); + /* add end of string character */ + pSMSStruct->PhoneNumber[pEndString-pLook4Word] = 0; + } + } + pEndString += URI_FIRST_DATA_END_LENGTH; + pLook4Word = pEndString; + + /* check if e-mail subject is present */ + if( !memcmp( pLook4Word, MESSAGE_BEGIN_STRING, MESSAGE_BEGIN_STRING_LENGTH ) ) + { + pEndString += MESSAGE_BEGIN_STRING_LENGTH; + /* Retrieve message */ + memcpy( pSMSStruct->Message, pEndString, PayloadSize - (pEndString - pPayload) ); + /* add end of string character */ + pSMSStruct->Message[PayloadSize-(pEndString-pPayload)] = 0; + } +} + +/** + * @brief This function read the SMS and store data in a structure. + * @param pRecordStruct : Pointer on the record structure. + * @param pSMSStruct : pointer on the structure to fill. + */ +static void NDEF_ReadURI_SMS( sRecordInfo_t *pRecordStruct, sSMSInfo *pSMSStruct ) +{ + uint8_t* pPayload; + uint32_t PayloadSize; + + PayloadSize = pRecordStruct->PayloadLength; + + /* Read record header */ + pPayload = (uint8_t*)(pRecordStruct->PayloadBufferAdd); + + if( pRecordStruct->NDEF_Type == URI_SMS_TYPE ) + NDEF_FillSMSStruct( pPayload , PayloadSize, pSMSStruct ); + +} + +/** + * @} + */ + +/** @defgroup libSMS_Public_Functions + * @{ + * @brief This file is used to manage SMS (stored or loaded in tag) + */ + +/** + * @brief This function read NDEF and retrieve SMS information if any. + * @param pRecordStruct : Pointer on the record structure. + * @param pSMSStruct : pointer on the structure to fill. + * @retval NDEF_OK : SMS information from NDEF have been retrieve. + * @retval NDEF_ERROR : Not able to retrieve SMS information. + */ +uint16_t NDEF_ReadSMS( sRecordInfo_t *pRecordStruct, sSMSInfo *pSMSStruct ) +{ + uint16_t status = NDEF_ERROR; + sRecordInfo_t *pSPRecordStruct; + uint32_t PayloadSize, RecordPosition; + uint8_t* pData; + + if( pRecordStruct->NDEF_Type == URI_SMS_TYPE ) + { + NDEF_ReadURI_SMS( pRecordStruct, pSMSStruct ); + status = NDEF_OK; + } + else if( pRecordStruct->NDEF_Type == SMARTPOSTER_TYPE ) + { + for( RecordPosition = 0; RecordPosition < pRecordStruct->NbOfRecordInSPPayload; RecordPosition++ ) + { + pSPRecordStruct = pRecordStruct->SPRecordStructAdd[RecordPosition]; + if( pSPRecordStruct->NDEF_Type == URI_SMS_TYPE ) + { + NDEF_ReadURI_SMS( pSPRecordStruct, pSMSStruct ); + status = NDEF_OK; + } + if( pSPRecordStruct->NDEF_Type == TEXT_TYPE ) + { + PayloadSize = pSPRecordStruct->PayloadLength; + + /* The instruction content the UTF-8 language code that is not used here */ + pData = (uint8_t*)pSPRecordStruct->PayloadBufferAdd; + PayloadSize -= *pData + 1; /* remove not usefull data */ + pData += *pData + 1; /* set pointer on usefull data */ + + memcpy( pSMSStruct->Information, pData, PayloadSize ); + /* add end of string character */ + pSMSStruct->Information[PayloadSize] = 0; + } + } + } + + return status; +} + +/** + * @brief This function write the NDEF file with the SMS data given in the structure. + * @param pSMSStruct : pointer on structure that contain the SMS information. + * @retval NDEF_OK : NDEF file data written in the tag. + * @retval NDEF_ERROR : not able to store NDEF in tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be write. + */ +uint16_t NDEF_WriteSMS( sSMSInfo *pSMSStruct ) +{ + uint16_t status = NDEF_ERROR, Offset = 0; + + NDEF_PrepareSMSMessage( pSMSStruct, NDEF_Buffer, &Offset ); + + status = NfcTag_WriteNDEF( Offset , NDEF_Buffer ); + + return status; +} + +/** + * @brief This function write the NDEF file with the SMS data given in the structure. + * @param pSMSStruct : pointer on structure that contain the SMS information. + * @param pNDEFMessage : pointer on the NDEF message. + * @param size : to store the size of the NDEF message generated. + */ +void NDEF_PrepareSMSMessage( sSMSInfo *pSMSStruct, uint8_t *pNDEFMessage, uint16_t *size ) +{ + uint16_t Offset = 0; + uint32_t smsSize = 0; + uint32_t infoSize= 0; + uint32_t totalSize = 0; + + /* SMS is an URI but can be included in a smart poster to add text to give instruction to user for instance */ + + /* SMS (smart poster) Record Header */ +/************************************/ +/* 7 | 6 | 5 | 4 | 3 | 2 1 0 */ +/*----------------------------------*/ +/* MB ME CF SR IL TNF */ /* <---- CF=0, IL=0 and SR=1 TNF=1 NFC Forum Well-known type*/ +/*----------------------------------*/ +/* TYPE LENGTH */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 3 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 2 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 1 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 0 */ +/*----------------------------------*/ +/* ID LENGTH */ /* <---- Not Used */ +/*----------------------------------*/ +/* TYPE */ +/*----------------------------------*/ +/* ID */ /* <---- Not Used */ +/************************************/ + + /* SMS : 1+sms:+tel+1+body=+message */ + smsSize = 1 + SMS_TYPE_STRING_LENGTH + strlen(pSMSStruct->PhoneNumber) + URI_FIRST_DATA_END_LENGTH + + MESSAGE_BEGIN_STRING_LENGTH + strlen(pSMSStruct->Message); + + /* Check if a Smart poster is needed */ + if( pSMSStruct->Information[0] != '\0' ) + { + /* Info : 1+2+info */ + infoSize = 1 + ISO_ENGLISH_CODE_STRING_LENGTH + strlen(pSMSStruct->Information); + /* Total */ + totalSize = 4 + smsSize + 4 + infoSize; + if( smsSize > 255 ) totalSize += 3; /* Normal Email size */ + if( infoSize > 255 ) totalSize += 3; /* Normal Info size */ + + /* SmartPoster header */ + if( totalSize > 255 ) + { + pNDEFMessage[Offset++] = 0xC1; + pNDEFMessage[Offset++] = SMART_POSTER_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (totalSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (totalSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (totalSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = totalSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = 0xD1; + pNDEFMessage[Offset++] = SMART_POSTER_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (uint8_t)totalSize; + } + memcpy( &pNDEFMessage[Offset], SMART_POSTER_TYPE_STRING, SMART_POSTER_TYPE_STRING_LENGTH ); + Offset += SMART_POSTER_TYPE_STRING_LENGTH; + } + + /* SMS header */ + pNDEFMessage[Offset] = 0x81; + if( smsSize < 256 ) pNDEFMessage[Offset] |= 0x10; // Set the SR bit + if( pSMSStruct->Information[0] == '\0' ) pNDEFMessage[Offset] |= 0x40; // Set the ME bit + Offset++; + + pNDEFMessage[Offset++] = URI_TYPE_STRING_LENGTH; + if( smsSize > 255 ) + { + pNDEFMessage[Offset++] = (smsSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (smsSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (smsSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = smsSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = (uint8_t)smsSize; + } + memcpy( &pNDEFMessage[Offset], URI_TYPE_STRING, URI_TYPE_STRING_LENGTH ); + Offset += URI_TYPE_STRING_LENGTH; + + /* SMS payload */ + pNDEFMessage[Offset++] = URI_ID_0x00; + memcpy( &pNDEFMessage[Offset], SMS_TYPE_STRING, SMS_TYPE_STRING_LENGTH ); + Offset += SMS_TYPE_STRING_LENGTH; + memcpy( &pNDEFMessage[Offset], pSMSStruct->PhoneNumber, strlen(pSMSStruct->PhoneNumber) ); + Offset += strlen( pSMSStruct->PhoneNumber ); + memcpy( &pNDEFMessage[Offset], URI_FIRST_DATA_END, URI_FIRST_DATA_END_LENGTH ); + Offset += URI_FIRST_DATA_END_LENGTH; + + memcpy( &pNDEFMessage[Offset], MESSAGE_BEGIN_STRING, MESSAGE_BEGIN_STRING_LENGTH ); + Offset += MESSAGE_BEGIN_STRING_LENGTH; + memcpy( &pNDEFMessage[Offset], pSMSStruct->Message, strlen(pSMSStruct->Message) ); + Offset += strlen( pSMSStruct->Message ); + + /* Information header */ + if( pSMSStruct->Information[0] != '\0' ) + { + if( infoSize > 255 ) + { + pNDEFMessage[Offset++] = 0x41; + pNDEFMessage[Offset++] = TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (infoSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (infoSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (infoSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = infoSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = 0x51; + pNDEFMessage[Offset++] = TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (uint8_t)infoSize; + } + + memcpy( &pNDEFMessage[Offset], TEXT_TYPE_STRING, TEXT_TYPE_STRING_LENGTH ); + Offset += TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = ISO_ENGLISH_CODE_STRING_LENGTH; /* UTF-8 with x byte language code */ + memcpy( &pNDEFMessage[Offset], ISO_ENGLISH_CODE_STRING, ISO_ENGLISH_CODE_STRING_LENGTH ); + Offset += ISO_ENGLISH_CODE_STRING_LENGTH; + + /* Information payload */ + memcpy( &pNDEFMessage[Offset], pSMSStruct->Information, strlen(pSMSStruct->Information) ); + Offset += strlen( pSMSStruct->Information ); + } + + *size = (uint16_t)(Offset); +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Text.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Text.c new file mode 100644 index 0000000..7c68969 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Text.c @@ -0,0 +1,185 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Text.h + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage Text NDEF file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_Text.h" +#include "stdlib.h" + +/** @addtogroup NFC_libraries + * @{ + * @brief This is the library used to manage the content of the TAG (data) + * But also the specific feature of the tag, for instance + * password, gpo... + */ + + +/** @addtogroup libNFC_FORUM + * @{ + * @brief This part of the library manage data which follow NFC forum organisation. + */ + +/** + * @brief This buffer contains the data send/received by TAG + */ +extern uint8_t NDEF_Buffer []; + +/** + * @} + */ + +/** @defgroup libEmail_Public_Functions + * @{ + * @brief This file is used to manage Email (stored or loaded in tag) + */ + +/** + * @brief This function write the text in the TAG. + * @param text : text to write. + * @retval NDEF_OK : NDEF file data written in the tag. + * @retval NDEF_ERROR : not able to store NDEF in tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be write. + */ +uint16_t NDEF_WriteText( char *text ) +{ + uint16_t status = NDEF_ERROR; + uint32_t textSize, Offset = 0; + + + /* TEXT : 1+en+message */ + textSize = 3 + strlen(text); + + /* TEXT header */ + NDEF_Buffer[Offset] = 0xD1; + if( textSize < 256 ) NDEF_Buffer[Offset] |= 0x10; // Set the SR bit + Offset++; + + NDEF_Buffer[Offset++] = TEXT_TYPE_STRING_LENGTH; + if( textSize > 255 ) + { + NDEF_Buffer[Offset++] = (textSize & 0xFF000000) >> 24; + NDEF_Buffer[Offset++] = (textSize & 0x00FF0000) >> 16; + NDEF_Buffer[Offset++] = (textSize & 0x0000FF00) >> 8; + NDEF_Buffer[Offset++] = textSize & 0x000000FF; + } + else + { + NDEF_Buffer[Offset++] = (uint8_t)textSize; + } + memcpy( &NDEF_Buffer[Offset], TEXT_TYPE_STRING, TEXT_TYPE_STRING_LENGTH ); + Offset += TEXT_TYPE_STRING_LENGTH; + + /* TEXT payload */ + NDEF_Buffer[Offset++] = ISO_ENGLISH_CODE_STRING_LENGTH; + memcpy( &NDEF_Buffer[Offset], ISO_ENGLISH_CODE_STRING, ISO_ENGLISH_CODE_STRING_LENGTH ); + Offset += ISO_ENGLISH_CODE_STRING_LENGTH; + + memcpy( &NDEF_Buffer[Offset], text, strlen(text) ); + Offset += strlen(text); + + status = NfcTag_WriteNDEF( Offset , NDEF_Buffer ); + + return status; +} + + +/** + * @brief This function the Text information in a record if any. + * @param pRecordStruct Pointer on a NDEF record structure. + * @param pText A pointer on a text information structure, used to return the text & its metadata. + * @retval NDEF_OK Text information has been retrieved. + * @retval NDEF_ERROR The record is not a Text record. + * @retval NDEF_ERROR_MEMORY_INTERNAL Language code or Text length is too big for the buffers. + */ +uint16_t NDEF_ReadText( sRecordInfo_t *pRecordStruct, NDEF_Text_info_t *pText ) +{ + uint16_t status = NDEF_ERROR; + + if( pRecordStruct->NDEF_Type == TEXT_TYPE ) + { + /* Get the text metadata (status byte (encoding & language code length) + language code) */ + NDEF_Text_metadata_t *text_record_info = (NDEF_Text_metadata_t *)pRecordStruct->PayloadBufferAdd; + + uint32_t text_length = pRecordStruct->PayloadLength /* record length */ + - text_record_info->language_length /* minus language code length */ + - sizeof(uint8_t); /* minus the status byte length */ + +#ifdef NDEF_DYN_ALLOC + if(text_record_info->language_length >= NDEF_TEXT_LANGUAGE_CODE_MAX_LENGTH) +#else + if((text_record_info->language_length >= NDEF_TEXT_LANGUAGE_CODE_MAX_LENGTH) || + (text_length >= NDEF_TEXT_MAX_LENGTH)) +#endif + { + /* One of the text info structure buffer is too small */ + return NDEF_ERROR_MEMORY_INTERNAL; + } + + /* Retrieve the encoding */ + pText->encoding = (NDEF_Text_encoding_t)text_record_info->encoding; + + /* Save the language code string (adding null char at the end) */ + memcpy(&pText->language_code,text_record_info->language,text_record_info->language_length); + pText->language_code[text_record_info->language_length] = '\0'; + + /* Copy the text string itself (adding null char at the end) */ +#ifdef NDEF_DYN_ALLOC + pText->text = malloc(text_length + 1); + if(pText->text != NULL) +#endif + { + memcpy(pText->text, text_record_info->language + text_record_info->language_length,text_length); + pText->text[text_length] = '\0'; + } + status = NDEF_OK; + } + else + { + /* Not a text record, exit in error */ + status = NDEF_ERROR; + } + + return status; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_URI.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_URI.c new file mode 100644 index 0000000..c752f16 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_URI.c @@ -0,0 +1,539 @@ +/** + ****************************************************************************** + * @file lib_NDEF_URI.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage NDEF file that represent URI. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_URI.h" + +/** @addtogroup NFC_libraries + * @{ + * @brief This is the library used to manage the content of the TAG (data) + * But also the specific feature of the tag, for instance + * password, gpo... + */ + + +/** @addtogroup libNFC_FORUM + * @{ + * @brief This part of the library manage data which follow NFC forum organisation. + */ + +/** + * @brief This buffer contains the data send/received by TAG + */ +extern uint8_t NDEF_Buffer []; + +/** @defgroup libURI_Private_Functions + * @{ + */ + +static void NDEF_Parse_WellKnowType( sRecordInfo_t *pRecordStruct, sURI_Info* pURI ); + +/** + * @brief This function read the URI information and store data in a structure. + * @param pRecordStruct : Pointer on the record structure. + * @param pURI : pointer on the structure to fill. + */ +static void NDEF_Parse_WellKnowType( sRecordInfo_t *pRecordStruct, sURI_Info* pURI ) +{ + uint32_t PayloadSize; + uint8_t Offset; + uint8_t* pPayload; + + pPayload = (uint8_t*)(pRecordStruct->PayloadBufferAdd); + + switch( *pPayload ) + { + case URI_ID_0x01: + memcpy( pURI->protocol, URI_ID_0x01_STRING, strlen(URI_ID_0x01_STRING) ); + Offset = strlen( URI_ID_0x01_STRING ); + break; + + case URI_ID_0x02: + memcpy( pURI->protocol, URI_ID_0x02_STRING, strlen(URI_ID_0x02_STRING) ); + Offset = strlen( URI_ID_0x02_STRING ); + break; + + case URI_ID_0x03: + memcpy( pURI->protocol, URI_ID_0x03_STRING, strlen(URI_ID_0x03_STRING) ); + Offset = strlen( URI_ID_0x03_STRING ); + break; + + case URI_ID_0x04: + memcpy( pURI->protocol, URI_ID_0x04_STRING, strlen(URI_ID_0x04_STRING) ); + Offset = strlen( URI_ID_0x04_STRING ); + break; + + case URI_ID_0x05: + memcpy( pURI->protocol, URI_ID_0x05_STRING, strlen(URI_ID_0x05_STRING) ); + Offset = strlen( URI_ID_0x05_STRING ); + break; + + case URI_ID_0x06: + memcpy( pURI->protocol, URI_ID_0x06_STRING, strlen(URI_ID_0x06_STRING) ); + Offset = strlen( URI_ID_0x06_STRING ); + break; + + case URI_ID_0x07: + memcpy( pURI->protocol, URI_ID_0x07_STRING, strlen(URI_ID_0x07_STRING) ); + Offset = strlen( URI_ID_0x07_STRING ); + break; + + case URI_ID_0x08: + memcpy( pURI->protocol, URI_ID_0x08_STRING, strlen(URI_ID_0x08_STRING) ); + Offset = strlen( URI_ID_0x08_STRING ); + break; + + case URI_ID_0x09: + memcpy( pURI->protocol, URI_ID_0x09_STRING, strlen(URI_ID_0x09_STRING) ); + Offset = strlen( URI_ID_0x09_STRING ); + break; + + case URI_ID_0x0A: + memcpy( pURI->protocol, URI_ID_0x0A_STRING, strlen(URI_ID_0x0A_STRING) ); + Offset = strlen( URI_ID_0x0A_STRING ); + break; + + case URI_ID_0x0B: + memcpy( pURI->protocol, URI_ID_0x0B_STRING, strlen(URI_ID_0x0B_STRING) ); + Offset = strlen( URI_ID_0x0B_STRING ); + break; + + case URI_ID_0x0C: + memcpy( pURI->protocol, URI_ID_0x0C_STRING, strlen(URI_ID_0x0C_STRING) ); + Offset = strlen( URI_ID_0x0C_STRING ); + break; + + case URI_ID_0x0D: + memcpy( pURI->protocol, URI_ID_0x0D_STRING, strlen(URI_ID_0x0D_STRING) ); + Offset = strlen( URI_ID_0x0D_STRING ); + break; + + case URI_ID_0x0E: + memcpy( pURI->protocol, URI_ID_0x0E_STRING, strlen(URI_ID_0x0E_STRING) ); + Offset = strlen( URI_ID_0x0E_STRING ); + break; + + case URI_ID_0x0F: + memcpy( pURI->protocol, URI_ID_0x0F_STRING, strlen(URI_ID_0x0F_STRING) ); + Offset = strlen( URI_ID_0x0F_STRING ); + break; + + case URI_ID_0x10: + memcpy( pURI->protocol, URI_ID_0x10_STRING, strlen(URI_ID_0x10_STRING) ); + Offset = strlen( URI_ID_0x10_STRING ); + break; + + case URI_ID_0x11: + memcpy( pURI->protocol, URI_ID_0x11_STRING, strlen(URI_ID_0x11_STRING) ); + Offset = strlen( URI_ID_0x11_STRING ); + break; + + case URI_ID_0x12: + memcpy( pURI->protocol, URI_ID_0x12_STRING, strlen(URI_ID_0x12_STRING) ); + Offset = strlen( URI_ID_0x12_STRING ); + break; + + case URI_ID_0x13: + memcpy( pURI->protocol, URI_ID_0x13_STRING, strlen(URI_ID_0x13_STRING) ); + Offset = strlen( URI_ID_0x13_STRING ); + break; + + case URI_ID_0x14: + memcpy( pURI->protocol, URI_ID_0x14_STRING, strlen(URI_ID_0x14_STRING) ); + Offset = strlen( URI_ID_0x14_STRING ); + break; + + case URI_ID_0x15: + memcpy( pURI->protocol, URI_ID_0x15_STRING, strlen(URI_ID_0x15_STRING) ); + Offset = strlen( URI_ID_0x15_STRING ); + break; + + case URI_ID_0x16: + memcpy( pURI->protocol, URI_ID_0x16_STRING, strlen(URI_ID_0x16_STRING) ); + Offset = strlen( URI_ID_0x16_STRING ); + break; + + case URI_ID_0x17: + memcpy( pURI->protocol, URI_ID_0x17_STRING, strlen(URI_ID_0x17_STRING) ); + Offset = strlen( URI_ID_0x17_STRING ); + break; + + case URI_ID_0x18: + memcpy( pURI->protocol, URI_ID_0x18_STRING, strlen(URI_ID_0x18_STRING) ); + Offset = strlen( URI_ID_0x18_STRING ); + break; + + case URI_ID_0x19: + memcpy( pURI->protocol, URI_ID_0x19_STRING, strlen(URI_ID_0x19_STRING) ); + Offset = strlen( URI_ID_0x19_STRING ); + break; + + case URI_ID_0x1A: + memcpy( pURI->protocol, URI_ID_0x1A_STRING, strlen(URI_ID_0x1A_STRING) ); + Offset = strlen( URI_ID_0x1A_STRING ); + break; + + case URI_ID_0x1B: + memcpy( pURI->protocol, URI_ID_0x1B_STRING, strlen(URI_ID_0x1B_STRING) ); + Offset = strlen( URI_ID_0x1B_STRING ); + break; + + case URI_ID_0x1C: + memcpy( pURI->protocol, URI_ID_0x1C_STRING, strlen(URI_ID_0x1C_STRING) ); + Offset = strlen( URI_ID_0x1C_STRING ); + break; + + case URI_ID_0x1D: + memcpy( pURI->protocol, URI_ID_0x1D_STRING, strlen(URI_ID_0x1D_STRING) ); + Offset = strlen( URI_ID_0x1D_STRING ); + break; + + case URI_ID_0x1E: + memcpy( pURI->protocol, URI_ID_0x1E_STRING, strlen(URI_ID_0x1E_STRING) ); + Offset = strlen( URI_ID_0x1E_STRING ); + break; + + case URI_ID_0x1F: + memcpy( pURI->protocol, URI_ID_0x1F_STRING, strlen(URI_ID_0x1F_STRING) ); + Offset = strlen( URI_ID_0x1F_STRING ); + break; + + case URI_ID_0x20: + memcpy( pURI->protocol, URI_ID_0x20_STRING, strlen(URI_ID_0x20_STRING) ); + Offset = strlen( URI_ID_0x20_STRING ); + break; + + case URI_ID_0x21: + memcpy( pURI->protocol, URI_ID_0x21_STRING, strlen(URI_ID_0x21_STRING) ); + Offset = strlen( URI_ID_0x21_STRING ); + break; + + case URI_ID_0x22: + memcpy( pURI->protocol, URI_ID_0x22_STRING, strlen(URI_ID_0x22_STRING) ); + Offset = strlen( URI_ID_0x22_STRING ); + break; + + case URI_ID_0x23: + memcpy( pURI->protocol, URI_ID_0x23_STRING, strlen(URI_ID_0x23_STRING) ); + Offset = strlen( URI_ID_0x23_STRING ); + break; + + default: + Offset = 0; + /* Should not happened */ + break; + } + /* add end of string character */ + pURI->protocol[Offset] = '\0'; + + pPayload++; /* go after well know byte */ + + PayloadSize = pRecordStruct->PayloadLength; + + PayloadSize = PayloadSize - 1; /* remove well know byte */ + + memcpy( pURI->URI_Message, pPayload, PayloadSize ); + /* add end of string character */ + pURI->URI_Message[PayloadSize] = '\0'; + +} + +/** + * @} + */ + +/** @defgroup libURI_Public_Functions + * @{ + * @brief This file is used to manage URI (stored or loaded in tag) + */ + +/** + * @brief This function read NDEF and retrieve URI information if any. + * @param pRecordStruct : Pointer on the record structure. + * @param pURI : pointer on the structure to fill. + * @retval NDEF_OK : URI information from NDEF have been retrieved. + * @retval NDEF_ERROR : Not able to retrieve URI information. + */ +uint16_t NDEF_ReadURI( sRecordInfo_t *pRecordStruct, sURI_Info *pURI ) +{ + uint16_t status = NDEF_ERROR; + sRecordInfo_t *pSPRecordStruct; + uint32_t PayloadSize, RecordPosition; + uint8_t* pData; + + if( pRecordStruct->NDEF_Type == WELL_KNOWN_ABRIDGED_URI_TYPE ) + { + NDEF_Parse_WellKnowType( pRecordStruct, pURI ); + status = NDEF_OK; + } + else if( pRecordStruct->NDEF_Type == SMARTPOSTER_TYPE ) + { + for( RecordPosition = 0; RecordPosition < pRecordStruct->NbOfRecordInSPPayload; RecordPosition++ ) + { + pSPRecordStruct = pRecordStruct->SPRecordStructAdd[RecordPosition]; + if( pSPRecordStruct->NDEF_Type == WELL_KNOWN_ABRIDGED_URI_TYPE ) + { + NDEF_Parse_WellKnowType( pSPRecordStruct, pURI ); + status = NDEF_OK; + } + if( pSPRecordStruct->NDEF_Type == TEXT_TYPE ) + { + PayloadSize = pSPRecordStruct->PayloadLength; + + /* The instruction content the UTF-8 language code that is not used here */ + pData = (uint8_t*)pSPRecordStruct->PayloadBufferAdd; + PayloadSize -= *pData + 1; /* remove not usefull data */ + pData += *pData + 1; + + memcpy( pURI->Information, pData, PayloadSize ); + } + } + } + else + { + status = NDEF_ERROR; + } + + return status; +} + +/** + * @brief This function prepare the NDEF message with the URI data given in the structure. + * @param pURI : pointer on structure that contain the URI information. + * @param pNDEFMessage : pointer on the NDEF message. + * @param size : to store the size of the NDEF message generated. + */ +void NDEF_PrepareURIMessage( sURI_Info *pURI, uint8_t *pNDEFMessage, uint16_t *size ) +{ + uint32_t uriSize, totalSize, Offset = 0; + uint32_t infoSize = 0; + char type; + + /* An URI can be included in a smart poster to add text to give instruction to user for instance */ + + /* URI (smart poster) Record Header */ +/************************************/ +/* 7 | 6 | 5 | 4 | 3 | 2 1 0 */ +/*----------------------------------*/ +/* MB ME CF SR IL TNF */ /* <---- CF=0, IL=0 and SR=1 TNF=1 NFC Forum Well-known type*/ +/*----------------------------------*/ +/* TYPE LENGTH */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 3 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 2 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 1 */ /* <---- Used only if SR=0 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 0 */ +/*----------------------------------*/ +/* ID LENGTH */ /* <---- Not Used */ +/*----------------------------------*/ +/* TYPE */ +/*----------------------------------*/ +/* ID */ /* <---- Not Used */ +/************************************/ + + /* We need to know the URI type in order to define if an abreviation is available */ + type = getUriType( pURI->protocol ); + + /* URI : 1+URI for abreviate protocol*/ + if( type != URI_ID_0x00 ) + uriSize = 1 + strlen(pURI->URI_Message); + else /*: 1+protocol+URI else*/ + uriSize = 1 + strlen(pURI->protocol) + strlen(pURI->URI_Message); + + /* Check if a Smart poster is needed */ + if( pURI->Information[0] != '\0' ) + { + /* Info : 1+2+info */ + infoSize = 1 + ISO_ENGLISH_CODE_STRING_LENGTH + strlen(pURI->Information); + /* Total */ + totalSize = 4 + uriSize + 4 + infoSize; + if( uriSize > 255 ) totalSize += 3; /* Normal URI size */ + if( infoSize > 255 ) totalSize += 3; /* Normal Info size */ + + /* SmartPoster header */ + if( totalSize > 255 ) + { + pNDEFMessage[Offset++] = 0xC1; + pNDEFMessage[Offset++] = SMART_POSTER_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (totalSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (totalSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (totalSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = totalSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = 0xD1; + pNDEFMessage[Offset++] = SMART_POSTER_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (uint8_t)totalSize; + } + memcpy( &pNDEFMessage[Offset], SMART_POSTER_TYPE_STRING, SMART_POSTER_TYPE_STRING_LENGTH ); + Offset += SMART_POSTER_TYPE_STRING_LENGTH; + } + + /* URI header */ + pNDEFMessage[Offset] = 0x81; + if( uriSize < 256 ) pNDEFMessage[Offset] |= 0x10; // Set the SR bit + if( pURI->Information[0] == '\0' ) pNDEFMessage[Offset] |= 0x40; // Set the ME bit + Offset++; + + pNDEFMessage[Offset++] = URI_TYPE_STRING_LENGTH; + if( uriSize > 255 ) + { + pNDEFMessage[Offset++] = (uriSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (uriSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (uriSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = uriSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = (uint8_t)uriSize; + } + memcpy( &pNDEFMessage[Offset], URI_TYPE_STRING, URI_TYPE_STRING_LENGTH ); + Offset += URI_TYPE_STRING_LENGTH; + + pNDEFMessage[Offset++] = type; + if( type == URI_ID_0x00 ) // No abreviation + { + memcpy( &pNDEFMessage[Offset], pURI->protocol, strlen(pURI->protocol) ); + Offset += strlen(pURI->protocol); + } + + memcpy( &pNDEFMessage[Offset], pURI->URI_Message, strlen(pURI->URI_Message) ); + Offset += strlen(pURI->URI_Message); + + /* Information header */ + if( pURI->Information[0] != '\0' ) + { + if( infoSize > 255 ) + { + pNDEFMessage[Offset++] = 0x41; + pNDEFMessage[Offset++] = TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (infoSize & 0xFF000000) >> 24; + pNDEFMessage[Offset++] = (infoSize & 0x00FF0000) >> 16; + pNDEFMessage[Offset++] = (infoSize & 0x0000FF00) >> 8; + pNDEFMessage[Offset++] = infoSize & 0x000000FF; + } + else + { + pNDEFMessage[Offset++] = 0x51; + pNDEFMessage[Offset++] = TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = (uint8_t)infoSize; + } + + memcpy( &pNDEFMessage[Offset], TEXT_TYPE_STRING, TEXT_TYPE_STRING_LENGTH ); + Offset+=TEXT_TYPE_STRING_LENGTH; + pNDEFMessage[Offset++] = ISO_ENGLISH_CODE_STRING_LENGTH; /* UTF-8 with x byte language code */ + memcpy( &pNDEFMessage[Offset], ISO_ENGLISH_CODE_STRING, ISO_ENGLISH_CODE_STRING_LENGTH ); + Offset += ISO_ENGLISH_CODE_STRING_LENGTH; + + /* Information payload */ + memcpy( &pNDEFMessage[Offset], pURI->Information, strlen(pURI->Information) ); + Offset += strlen(pURI->Information); + } + + *size = Offset; + +} +/** + * @brief This function write the NDEF file with the URI data given in the structure. + * @param pURI : pointer on structure that contain the URI information. + * @retval NDEF_OK : NDEF file data written in the tag. + * @retval NDEF_ERROR : not able to store NDEF in tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL : Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED : CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG : Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED : Tag locked, cannot be write. + */ +uint16_t NDEF_WriteURI( sURI_Info *pURI ) +{ + uint16_t status = NDEF_ERROR, Offset = 0; + + NDEF_PrepareURIMessage( pURI, NDEF_Buffer, &Offset ); + + status = NfcTag_WriteNDEF( Offset , NDEF_Buffer ); + + return status; +} + +char getUriType( char *protocol ) +{ + if( !memcmp( protocol, URI_ID_0x01_STRING, strlen(URI_ID_0x01_STRING) ) ) return URI_ID_0x01; + else if( !memcmp( protocol, URI_ID_0x02_STRING, strlen(URI_ID_0x02_STRING) ) ) return URI_ID_0x02; + else if( !memcmp( protocol, URI_ID_0x03_STRING, strlen(URI_ID_0x03_STRING) ) ) return URI_ID_0x03; + else if( !memcmp( protocol, URI_ID_0x04_STRING, strlen(URI_ID_0x04_STRING) ) ) return URI_ID_0x04; + else if( !memcmp( protocol, URI_ID_0x05_STRING, strlen(URI_ID_0x05_STRING) ) ) return URI_ID_0x05; + else if( !memcmp( protocol, URI_ID_0x06_STRING, strlen(URI_ID_0x06_STRING) ) ) return URI_ID_0x06; + else if( !memcmp( protocol, URI_ID_0x07_STRING, strlen(URI_ID_0x07_STRING) ) ) return URI_ID_0x07; + else if( !memcmp( protocol, URI_ID_0x08_STRING, strlen(URI_ID_0x08_STRING) ) ) return URI_ID_0x08; + else if( !memcmp( protocol, URI_ID_0x09_STRING, strlen(URI_ID_0x09_STRING) ) ) return URI_ID_0x09; + else if( !memcmp( protocol, URI_ID_0x0A_STRING, strlen(URI_ID_0x0A_STRING) ) ) return URI_ID_0x0A; + else if( !memcmp( protocol, URI_ID_0x0B_STRING, strlen(URI_ID_0x0B_STRING) ) ) return URI_ID_0x0B; + else if( !memcmp( protocol, URI_ID_0x0C_STRING, strlen(URI_ID_0x0C_STRING) ) ) return URI_ID_0x0C; + else if( !memcmp( protocol, URI_ID_0x0D_STRING, strlen(URI_ID_0x0D_STRING) ) ) return URI_ID_0x0D; + else if( !memcmp( protocol, URI_ID_0x0E_STRING, strlen(URI_ID_0x0E_STRING) ) ) return URI_ID_0x0E; + else if( !memcmp( protocol, URI_ID_0x0F_STRING, strlen(URI_ID_0x0F_STRING) ) ) return URI_ID_0x0F; + else if( !memcmp( protocol, URI_ID_0x10_STRING, strlen(URI_ID_0x10_STRING) ) ) return URI_ID_0x10; + else if( !memcmp( protocol, URI_ID_0x11_STRING, strlen(URI_ID_0x11_STRING) ) ) return URI_ID_0x11; + else if( !memcmp( protocol, URI_ID_0x12_STRING, strlen(URI_ID_0x12_STRING) ) ) return URI_ID_0x12; + else if( !memcmp( protocol, URI_ID_0x13_STRING, strlen(URI_ID_0x13_STRING) ) ) return URI_ID_0x13; + else if( !memcmp( protocol, URI_ID_0x14_STRING, strlen(URI_ID_0x14_STRING) ) ) return URI_ID_0x14; + else if( !memcmp( protocol, URI_ID_0x15_STRING, strlen(URI_ID_0x15_STRING) ) ) return URI_ID_0x15; + else if( !memcmp( protocol, URI_ID_0x16_STRING, strlen(URI_ID_0x16_STRING) ) ) return URI_ID_0x16; + else if( !memcmp( protocol, URI_ID_0x17_STRING, strlen(URI_ID_0x17_STRING) ) ) return URI_ID_0x17; + else if( !memcmp( protocol, URI_ID_0x18_STRING, strlen(URI_ID_0x18_STRING) ) ) return URI_ID_0x18; + else if( !memcmp( protocol, URI_ID_0x19_STRING, strlen(URI_ID_0x19_STRING) ) ) return URI_ID_0x19; + else if( !memcmp( protocol, URI_ID_0x1A_STRING, strlen(URI_ID_0x1A_STRING) ) ) return URI_ID_0x1A; + else if( !memcmp( protocol, URI_ID_0x1B_STRING, strlen(URI_ID_0x1B_STRING) ) ) return URI_ID_0x1B; + else if( !memcmp( protocol, URI_ID_0x1C_STRING, strlen(URI_ID_0x1C_STRING) ) ) return URI_ID_0x1C; + else if( !memcmp( protocol, URI_ID_0x1D_STRING, strlen(URI_ID_0x1D_STRING) ) ) return URI_ID_0x1D; + else if( !memcmp( protocol, URI_ID_0x1E_STRING, strlen(URI_ID_0x1E_STRING) ) ) return URI_ID_0x1E; + else if( !memcmp( protocol, URI_ID_0x1F_STRING, strlen(URI_ID_0x1F_STRING) ) ) return URI_ID_0x1F; + else if( !memcmp( protocol, URI_ID_0x20_STRING, strlen(URI_ID_0x20_STRING) ) ) return URI_ID_0x20; + else if( !memcmp( protocol, URI_ID_0x21_STRING, strlen(URI_ID_0x21_STRING) ) ) return URI_ID_0x21; + else if( !memcmp( protocol, URI_ID_0x22_STRING, strlen(URI_ID_0x22_STRING) ) ) return URI_ID_0x22; + else if( !memcmp( protocol, URI_ID_0x23_STRING, strlen(URI_ID_0x23_STRING) ) ) return URI_ID_0x23; + else return URI_ID_0x00; // No abreviation for this protocol +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Vcard.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Vcard.c new file mode 100644 index 0000000..ee09f74 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Vcard.c @@ -0,0 +1,644 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Vcard.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file help to manage NDEF file that represent Vcard. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2015 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_Vcard.h" + + +/** @addtogroup lib_NDEF_Vcard + * @ingroup libNDEF + * @{ + * @brief This part of the library manage the data which follow NFC forum organisation. + */ + +/* This buffer contains the data sent/received by TAG */ +extern uint8_t NDEF_Buffer []; + +static void NDEF_FillVcardStruct( uint8_t* pPayload, uint32_t PayloadSize, char* pKeyWord, uint32_t SizeOfKeyWord, uint8_t* pString ); +static void NDEF_ExtractVcard( sRecordInfo_t *pRecordStruct, sVcardInfo *pVcardStruct ); + +/** + * @brief This function extracts a Vcard particular property from a vCard. + * @param pPayload Pointer on the vCard payload data of the vCard record. + * @param PayloadSize Number of bytes in the vCard payload. + * @param pKeyWord Pointer on the vCard property keyword to look for. + * @param SizeOfKeyWord Number of bytes of the vCard property keyword we are looking for. + * @param pString Pointer on a string used to return the vCard property read. + */ +static void NDEF_FillVcardStruct( uint8_t* pPayload, uint32_t PayloadSize, char* pKeyWord, uint32_t SizeOfKeyWord, uint8_t* pString ) +{ + uint8_t* pLastByteAdd, *pLook4Word, *pEndString; + + /* First character force to NULL in case not matching found */ + *pString = 0; + + pLastByteAdd = pPayload; + while( memcmp( pLastByteAdd, JPEG, JPEG_STRING_SIZE ) && (pLastByteAdd < (pPayload + PayloadSize)) ) + { + pLastByteAdd++; + } + + pLook4Word = pPayload; + while( memcmp( pLook4Word, pKeyWord, SizeOfKeyWord ) && (pLook4Word < pLastByteAdd) ) + { + pLook4Word++; + } + + /* Word found */ + if( pLook4Word != pLastByteAdd ) + { + pLook4Word += SizeOfKeyWord; + pEndString = pLook4Word; + while( memcmp( pEndString, LIMIT, LIMIT_STRING_SIZE ) && (*pEndString!='\n') && (pEndString < pLastByteAdd) ) + { + pEndString++; + } + if( pEndString != pLastByteAdd ) + { + memcpy( pString, pLook4Word, pEndString-pLook4Word ); + /* add end of string character */ + pString += pEndString - pLook4Word; + *pString = '\0'; + } + } +} + +/** + * @brief This function reads a Vcard record and stores data in a `sVcardInfo` structure. + * @param pRecordStruct Pointer on the vCard record structure. + * @param pVcardStruct Pointer on the `sCardInfo` structure to fill. + */ +static void NDEF_ExtractVcard( sRecordInfo_t *pRecordStruct, sVcardInfo *pVcardStruct ) +{ + uint32_t PayloadSize; + uint8_t* pPayload; + + + PayloadSize = pRecordStruct->PayloadLength; + + /* Read record header */ + pPayload = (uint8_t*)(pRecordStruct->PayloadBufferAdd); + + NDEF_FillVcardStruct( pPayload, PayloadSize, VERSION, VERSION_STRING_SIZE, (uint8_t*)(pVcardStruct->Version) ); + if( !memcmp( pVcardStruct->Version, VCARD_VERSION_2_1, VCARD_VERSION_2_1_SIZE ) ) + { + NDEF_FillVcardStruct( pPayload, PayloadSize, FIRSTNAME, FIRSTNAME_STRING_SIZE, (uint8_t*)(pVcardStruct->FirstName) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, TITLE, TITLE_STRING_SIZE, (uint8_t*)(pVcardStruct->Title) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, ORG, ORG_STRING_SIZE, (uint8_t*)(pVcardStruct->Org) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, HOME_ADDRESS, HOME_ADDRESS_STRING_SIZE, (uint8_t*)(pVcardStruct->HomeAddress) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, GEN_ADDRESS, strlen(GEN_ADDRESS), (uint8_t*)(pVcardStruct->Address) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, WORK_ADDRESS, WORK_ADDRESS_STRING_SIZE, (uint8_t*)(pVcardStruct->WorkAddress) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, HOME_TEL, HOME_TEL_STRING_SIZE, (uint8_t*)(pVcardStruct->HomeTel) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, WORK_TEL, WORK_TEL_STRING_SIZE, (uint8_t*)(pVcardStruct->WorkTel) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, CELL_TEL, CELL_TEL_STRING_SIZE, (uint8_t*)(pVcardStruct->CellTel) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, HOME_EMAIL, HOME_EMAIL_STRING_SIZE, (uint8_t*)(pVcardStruct->HomeEmail) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, GEN_EMAIL, strlen(GEN_EMAIL), (uint8_t*)(pVcardStruct->Email) ); + NDEF_FillVcardStruct( pPayload, PayloadSize, WORK_EMAIL, WORK_EMAIL_STRING_SIZE, (uint8_t*)(pVcardStruct->WorkEmail) ); + } + else if( !memcmp( pVcardStruct->Version, VCARD_VERSION_3_0, VCARD_VERSION_3_0_SIZE ) ) + { + /* need to be implemented */ + } + else + { + /* maybe new version but not supported in this sw */ + } + +} + +/** + * @brief This function reads a Vcard record and stores data in a `sVcardInfo` structure. + * @param pRecordStruct Pointer on the vCard record structure. + * @param pVcardStruct Pointer on the `sCardInfo` structure to fill. + * @retval NDEF_OK The Vcard information has been retrieved. + * @retval NDEF_ERROR Not able to retrieve the Vcard information. + */ +uint16_t NDEF_ReadVcard( sRecordInfo_t *pRecordStruct, sVcardInfo *pVcardStruct ) +{ + uint16_t status = NDEF_ERROR; + + if( pRecordStruct->NDEF_Type == VCARD_TYPE ) + { + NDEF_ExtractVcard( pRecordStruct, pVcardStruct ); + status = NDEF_OK; + } + + return status; +} + +/** + * @brief This function writes a NDEF message to the NFC tag with the Vcard data given in a `sVcardInfo` structure. + * @param pVcardStruct Pointer on a `sVcardInfo` structure containing the Vcard information. + * @retval NDEF_OK NDEF file data written in the tag. + * @retval NDEF_ERROR Not able to store the NDEF in tag. + * @retval NDEF_ERROR_MEMORY_INTERNAL Cannot write to tag. + * @retval NDEF_ERROR_NOT_FORMATED CCFile data not supported or not present. + * @retval NDEF_ERROR_MEMORY_TAG Size not compatible with memory. + * @retval NDEF_ERROR_LOCKED Tag locked, cannot be write. + */ +uint16_t NDEF_WriteVcard( sVcardInfo *pVcardStruct ) +{ + uint16_t status = NDEF_ERROR, Offset = 0; + + NDEF_PrepareVcardMessage( pVcardStruct, NDEF_Buffer, &Offset ); + + status = NfcTag_WriteNDEF( Offset , NDEF_Buffer ); + + return status; +} + +/** + * @brief This function computes the size of a Vcard record from the data given in the `sVcardInfo` structure. + * @param pVcardStruct Pointer on a `sVcardInfo` structure containing the Vcard information. + * @return vCard record data size in bytes (excluding record metadata). + */ +uint32_t NDEF_GetVcardLength( sVcardInfo *pVcardStruct) +{ + + uint32_t PayloadSize = 0; + + /* "BEGIN:VCARD\r\n" */ + PayloadSize += BEGIN_STRING_SIZE; + PayloadSize += VCARD_STRING_SIZE; + PayloadSize += LIMIT_STRING_SIZE; + + /* "VERSION:2.1\r\n" */ + PayloadSize += VERSION_STRING_SIZE; + PayloadSize += VCARD_VERSION_2_1_SIZE; + PayloadSize += LIMIT_STRING_SIZE; + + /* "N:\r\n" */ + if(*pVcardStruct->Name != '\0') + { + PayloadSize += VCARD_NAME_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->Name ); + PayloadSize += LIMIT_STRING_SIZE; + } + /* "FN:\r\n" */ + if(*pVcardStruct->FirstName != '\0') + { + PayloadSize += FIRSTNAME_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->FirstName ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->Title != '\0') + { + /* "TITLE:\r\n" */ + PayloadSize += TITLE_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->Title ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->Org != '\0') + { + /* "ORG:\r\n" */ + PayloadSize += ORG_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->Org ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->Url != '\0') + { + /* "URL:\r\n" */ + PayloadSize += URL_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->Url ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->HomeAddress != '\0') + { + /* "ADR;HOME:\r\n" */ + PayloadSize += HOME_ADDRESS_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->HomeAddress ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->WorkAddress != '\0') + { + /* "ADR;WORK:\r\n" */ + PayloadSize += WORK_ADDRESS_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->WorkAddress ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->HomeTel != '\0') + { + /* "TEL;HOME:\r\n" */ + PayloadSize += HOME_TEL_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->HomeTel ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->WorkTel != '\0') + { + /* "TEL;WORK:\r\n" */ + PayloadSize += WORK_TEL_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->WorkTel ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->CellTel != '\0') + { + /* "TEL;CELL:\r\n" */ + PayloadSize += CELL_TEL_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->CellTel ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->HomeEmail != '\0') + { + /* "EMAIL;HOME:\r\n" */ + PayloadSize += HOME_EMAIL_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->HomeEmail ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->WorkEmail != '\0') + { + /* "EMAIL;WORK:\r\n" */ + PayloadSize += WORK_EMAIL_STRING_SIZE; + PayloadSize += strlen( pVcardStruct->WorkEmail ); + PayloadSize += LIMIT_STRING_SIZE; + } + if((pVcardStruct->Picture != NULL) && (pVcardStruct->Picture != 0)) + { + PayloadSize += strlen(PICTURE_PHOTO); + PayloadSize += strlen(JPEG); + PayloadSize++; + PayloadSize += strlen(PICTURE_BASE64); + PayloadSize++; + PayloadSize += pVcardStruct->PictureSize; + } + + /* "END:VCARD\r\n" */ + PayloadSize += END_STRING_SIZE; + PayloadSize += VCARD_STRING_SIZE; + /* PayloadSize += LIMIT_STRING_SIZE;*/ + + return PayloadSize; + +} + +/** + * @brief This function write the NDEF file with the Vcard data given in the structure. + * @param pVcardStruct : pointer on structure that contain the Vcard information. + * @param pNDEFMessage : pointer on the NDEF message. + * @param size : to store the size of the NDEF message generated. + */ +void NDEF_PrepareVcardMessage( sVcardInfo *pVcardStruct, uint8_t *pNDEFMessage, uint16_t *size ) +{ + + uint32_t PayloadSize = 0; + + /* Vcard Record Header */ +/************************************/ +/* 7 | 6 | 5 | 4 | 3 | 2 1 0 */ +/*----------------------------------*/ +/* MB ME CF SR IL TNF */ /* <---- CF=0, IL=0 and SR=0 TNF=2 NFC Forum Media type*/ +/*----------------------------------*/ +/* TYPE LENGTH */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 3 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 2 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 1 */ +/*----------------------------------*/ +/* PAYLOAD LENGTH 0 */ +/*----------------------------------*/ +/* ID LENGTH */ /* <---- Not Used */ +/*----------------------------------*/ +/* TYPE */ +/*----------------------------------*/ +/* ID */ /* <---- Not Used */ +/************************************/ + + /* As we don't have embedded a jpeg encoder/decoder in this firmware */ + /* We have made the choice to manage only string content of the vCard */ + /* For demonstration purpose in order to fill the 8kB of the M24SR */ + /* We have embedded a NDEF vCard in the STM32 to be able to fill M24SR */ + + /* fill record header */ + uint32_t length = NDEF_GetVcardLength(pVcardStruct); + if(length >= 0xFF) + { + pNDEFMessage[0] = 0xC2; /* Record Flag */ + pNDEFMessage[1] = XVCARD_TYPE_STRING_LENGTH; + pNDEFMessage[5] = length & 0xff; + pNDEFMessage[4] = (length>>8) & 0xff; + pNDEFMessage[3] = (length>>16) & 0xff; + pNDEFMessage[2] = length>>24; + memcpy( &pNDEFMessage[6], XVCARD_TYPE_STRING, XVCARD_TYPE_STRING_LENGTH ); + + /* Payload is positionned in the NDEF after record header */ + PayloadSize = 6 + XVCARD_TYPE_STRING_LENGTH; + } else { + pNDEFMessage[0] = 0xD2; /* Record Flag */ + pNDEFMessage[1] = XVCARD_TYPE_STRING_LENGTH; + pNDEFMessage[2] = length; + memcpy( &pNDEFMessage[3], XVCARD_TYPE_STRING, XVCARD_TYPE_STRING_LENGTH ); + + /* Payload is positionned in the NDEF after record header */ + PayloadSize = 3 + XVCARD_TYPE_STRING_LENGTH; + } + + /* "BEGIN:VCARD\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], BEGIN, BEGIN_STRING_SIZE ); + PayloadSize += BEGIN_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], VCARD,VCARD_STRING_SIZE ); + PayloadSize += VCARD_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + + /* "VERSION:2.1\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], VERSION, VERSION_STRING_SIZE ); + PayloadSize += VERSION_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], VCARD_VERSION_2_1, VCARD_VERSION_2_1_SIZE ); + PayloadSize += VCARD_VERSION_2_1_SIZE; + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + + /* "N:\r\n" */ + if(*pVcardStruct->Name != '\0') + { + memcpy( &pNDEFMessage[PayloadSize], VCARD_NAME, VCARD_NAME_STRING_SIZE ); + PayloadSize += VCARD_NAME_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->Name, strlen(pVcardStruct->Name) ); + PayloadSize += strlen( pVcardStruct->Name ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + /* "FN:\r\n" */ + if(*pVcardStruct->FirstName != '\0') + { + memcpy( &pNDEFMessage[PayloadSize], FIRSTNAME, FIRSTNAME_STRING_SIZE ); + PayloadSize += FIRSTNAME_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->FirstName, strlen(pVcardStruct->FirstName) ); + PayloadSize += strlen( pVcardStruct->FirstName ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->HomeTel != '\0') + { + + /* "TEL;HOME:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], HOME_TEL, HOME_TEL_STRING_SIZE ); + PayloadSize += HOME_TEL_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->HomeTel, strlen(pVcardStruct->HomeTel) ); + PayloadSize += strlen( pVcardStruct->HomeTel ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->WorkTel != '\0') + { + + /* "TEL;WORK:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], WORK_TEL, WORK_TEL_STRING_SIZE ); + PayloadSize += WORK_TEL_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->WorkTel, strlen(pVcardStruct->WorkTel) ); + PayloadSize += strlen( pVcardStruct->WorkTel ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->CellTel != '\0') + { + + /* "TEL;CELL:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], CELL_TEL, CELL_TEL_STRING_SIZE ); + PayloadSize += CELL_TEL_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->CellTel, strlen(pVcardStruct->CellTel) ); + PayloadSize += strlen( pVcardStruct->CellTel ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->HomeEmail != '\0') + { + + /* "EMAIL;HOME:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], HOME_EMAIL, HOME_EMAIL_STRING_SIZE ); + PayloadSize += HOME_EMAIL_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->HomeEmail, strlen(pVcardStruct->HomeEmail) ); + PayloadSize += strlen( pVcardStruct->HomeEmail ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->WorkEmail != '\0') + { + + /* "EMAIL;WORK:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], WORK_EMAIL, WORK_EMAIL_STRING_SIZE ); + PayloadSize += WORK_EMAIL_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->WorkEmail, strlen(pVcardStruct->WorkEmail) ); + PayloadSize += strlen( pVcardStruct->WorkEmail ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->HomeAddress != '\0') + { + + /* "ADR;HOME:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], HOME_ADDRESS, HOME_ADDRESS_STRING_SIZE ); + PayloadSize += HOME_ADDRESS_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->HomeAddress, strlen(pVcardStruct->HomeAddress) ); + PayloadSize += strlen( pVcardStruct->HomeAddress ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->WorkAddress != '\0') + { + + /* "ADR;WORK:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], WORK_ADDRESS, WORK_ADDRESS_STRING_SIZE ); + PayloadSize += WORK_ADDRESS_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->WorkAddress, strlen(pVcardStruct->WorkAddress) ); + PayloadSize += strlen( pVcardStruct->WorkAddress ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->Org != '\0') + { + + /* "ORG:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], ORG, ORG_STRING_SIZE ); + PayloadSize += ORG_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->Org, strlen(pVcardStruct->Org) ); + PayloadSize += strlen( pVcardStruct->Org ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->Title != '\0') + { + /* "TITLE:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], TITLE, TITLE_STRING_SIZE ); + PayloadSize += TITLE_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->Title, strlen(pVcardStruct->Title) ); + PayloadSize += strlen( pVcardStruct->Title ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + if(*pVcardStruct->Url != '\0') + { + /* "URL:\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], URL, URL_STRING_SIZE ); + PayloadSize += URL_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], pVcardStruct->Url, strlen(pVcardStruct->Url) ); + PayloadSize += strlen( pVcardStruct->Url ); + memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); + PayloadSize += LIMIT_STRING_SIZE; + } + + if((pVcardStruct->Picture != NULL) && (pVcardStruct->PictureSize != 0)) + { + memcpy(&pNDEFMessage[PayloadSize],PICTURE_PHOTO,strlen(PICTURE_PHOTO)); + PayloadSize += strlen(PICTURE_PHOTO); + memcpy(&pNDEFMessage[PayloadSize],JPEG,strlen(JPEG)); + PayloadSize += strlen(JPEG); + pNDEFMessage[PayloadSize] = ';'; + PayloadSize++; + memcpy(&pNDEFMessage[PayloadSize],PICTURE_BASE64,strlen(PICTURE_BASE64)); + PayloadSize += strlen(PICTURE_BASE64); + pNDEFMessage[PayloadSize] = ':'; + PayloadSize++; + memcpy(&pNDEFMessage[PayloadSize],pVcardStruct->Picture,pVcardStruct->PictureSize); + PayloadSize += pVcardStruct->PictureSize; + } + + /* "END:VCARD\r\n" */ + memcpy( &pNDEFMessage[PayloadSize], END, END_STRING_SIZE ); + PayloadSize += END_STRING_SIZE; + memcpy( &pNDEFMessage[PayloadSize], VCARD, VCARD_STRING_SIZE ); + PayloadSize += VCARD_STRING_SIZE; +// memcpy( &pNDEFMessage[PayloadSize], LIMIT, LIMIT_STRING_SIZE ); +// PayloadSize += LIMIT_STRING_SIZE; + + *size = (uint16_t)(PayloadSize); /* Must not count the 2 byte that represent the NDEF size */ +/* + PayloadSize -= 6 + VCARD_TYPE_STRING_LENGTH; + + pNDEFMessage[2] = (PayloadSize & 0xFF000000) >> 24; + pNDEFMessage[3] = (PayloadSize & 0x00FF0000) >> 16; + pNDEFMessage[4] = (PayloadSize & 0x0000FF00) >> 8; + pNDEFMessage[5] = PayloadSize & 0x000000FF; + */ +} + + +/** + * @brief This function extracts binary data from a base64 representation. + * @param input64 : pointer on the input data in base64. + * @param binary : returned binary data. + * @return Updated pointer on the input64 buffer (normal increment is 4 base64 char for 3 bytes of binary data, but special char are ignored) +*/ +static uint8_t* from_base64(uint8_t *input64, uint32_t* binary) +{ + /* Read 4 base64 character & translate them into 3 bytes binary */ + *binary = 0; + uint8_t base64_6bits; + int i = 0; + while(i<4) + { + + if((*input64 >= 'A') && (*input64 <= 'Z')) + { + base64_6bits = *(input64++) - 'A'; + } else if ((*input64 >= 'a') && (*input64 <= 'z')) + { + base64_6bits = *(input64++) - 'a' + 26; + } else if ((*input64 >= '0') && (*input64 <= '9')) { + base64_6bits = *(input64++) - '0' + 52; + } else if (*input64 == '+') + { + base64_6bits = 62; + input64++; + } else if (*input64 == '/') + { + base64_6bits = 63; + input64++; + } else if (*input64 == '=') { + base64_6bits = 0; + input64++; + } else { + input64++; + continue; + } + + *binary |= base64_6bits << (6*(3-i)); + i++; + } + *binary = ((*binary & 0xFF0000)>>16) | ((*binary & 0xFF)<<16) | (*binary & 0xFF00); + return input64; +} + + +/** + * @brief This function return the picture stored in a VCARD. + * @param pPayload : pointer on the payload data of the NDEF message. + * @param PayloadSize : number of data in the payload. + * @param pPict : Pointer on the dpicture buffer (must be big enough to contain the picture - warning: no check is done in the function). + */ +int NDEF_getVcardPicture( uint8_t* pPayload, uint32_t PayloadSize, uint8_t* pPict ) +{ + uint8_t* pSrcPict; + + + /* Let's find the picture */ + pSrcPict = pPayload; + while( memcmp( pSrcPict, JPEG, JPEG_STRING_SIZE ) && (pSrcPict < (pPayload + PayloadSize)) ) + { + pSrcPict++; + } + while( (*pSrcPict != ':') && (pSrcPict < (pPayload + PayloadSize)) ) + { + pSrcPict++; + } + /* Picture start at next char */ + pSrcPict++; + + + /* Word found */ + while( memcmp( pSrcPict, LIMIT, LIMIT_STRING_SIZE ) && memcmp( pSrcPict, END, END_STRING_SIZE ) && (*pSrcPict!='\n') && (pSrcPict < (pPayload + PayloadSize) ) ) + { + uint32_t binary24; + pSrcPict = from_base64(pSrcPict, &binary24); + /* copy the 3 bytes read from the base64 data */ + memcpy( pPict, &binary24, 3); + pPict += 3; + /* Ignore any line breaks */ + while (*pSrcPict == 0x0A) + { + pSrcPict++; + } + } + + if(pSrcPict >= (pPayload + PayloadSize)) + { + /* problem when parsing the picture */ + return 1; + } else { + /* picture found */ + return 0; + } +} + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2015 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Wifi.c b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Wifi.c new file mode 100644 index 0000000..9ee9f7d --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/lib_NDEF_Wifi.c @@ -0,0 +1,367 @@ +/** + ****************************************************************************** + * @file lib_NDEF_Wifi.c + * @author Central LAB + * @version $Revision:$ + * @date $Date:$ + * @ingroup LibNDEF_Wifi + * @brief This file helps to manage a NDEF message representing a Wifi Token. + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "lib_NDEF_Wifi.h" +#define ATTRIBUTE_ID_SSID_LSB 0X10 +#define ATTRIBUTE_ID_SSID_MSB 0X45 + + +#define ATTRIBUTE_ID_NETWORK_LSB 0X10 +#define ATTRIBUTE_ID_NETWORK_MSB 0X27 + + +/** @addtogroup lib_NDEF_Wifi Wifi OOB library (WPS) + * @ingroup libNDEF + * @brief This module is used to manage a Wifi Out-Of-Band NDEF message, to start a communication based on Wifi. + * @details The Wifi OOB format is described by the Wifi Protected Setup specification. + * It consists in a list of data elements formated as type-length-value. + * This module allows to build, write & read such data embedded in a NDEF message. + * @section Wifi_Library_Usage Wifi NDEF library usage + * @subsection Write_Wifi_OOB How to write a Wifi OOB + * The Wifi OOB written in a NDEF record by this module has the following structure: + * - Version + * - Credential + - Network index + - SSID + - Authentication Type + - Encryption Type + - Network Key + - MAC Address + - Vendor Extension + - Network Key Shareable + - Vendor Extension + - Version2 + + To write a Wifi OOB, the user must: + 1. Instanciate & initialize a `sWifiTokenInfo` structure, such as: + + sWifiTokenInfo wps_oob = {.NetworkSSID = "MY_SSID", + .AuthenticationType = NDEF_WIFI_AUTHENTICATION_NONE, + .EncryptionType = NDEF_WIFI_ENCRYPTION_NONE, + .NetworkKey = "01234567"}; + @note + 1. `AuthenticationType` & `EncryptionType` fields must respectively be values from enums: `Ndef_Wifi_Authentication_t` & `Ndef_Wifi_Encryption_t`. + 2. If the `Network key` is set to an empty string, the library sets it to `00000000`.\n + Even if 0-length Network Key is supposed to be supported, smartphones dont necessarily accept it. + + 2. Call the `NDEF_WriteWifiToken` function on a pointer on the previous struct instance: + + NDEF_WriteWifiToken(&wps_oob); + * @subsection Read_Wifi_OOB How to read a Wifi OOB + * 1. Read the 1st record of the NDEF message: + * + * sRecordInfo_t rRecord; + * NDEF_ReadNDEF(NDEF_Buffer); + * NDEF_IdentifyBuffer(rRecord,NDEF_Buffer); + * 2. Decode the Wifi OOB: + * + * sWifiTokenInfo wps; + * NDEF_ReadWifiToken(&record, &wps); + * @note + * Only the `NetworkSSID` & `NetworkKey` are extracted from the Wifi OOB, other fields of the `sWifiTokenInfo` structure are left un-initialized. + * @{ + */ + +/* This buffer contains the data send/received by the TAG */ +extern uint8_t NDEF_Buffer [NDEF_MAX_SIZE]; + + +static void NDEF_FillWifiTokenStruct( uint8_t* pPayload, uint32_t PayloadSize, sWifiTokenInfo *pWifiTokenStruct); +static void NDEF_Read_WifiToken ( struct sRecordInfo *pRecordStruct, sWifiTokenInfo *pWifiTokenStruct ); + +/** + * @brief This function fills a WifiToken structure with information from the NDEF message. + * @param pPayload Pointer on the payload data of the NDEF message. + * @param PayloadSize number of data in the payload. + * @param pWifiTokenStruct pointer on the structure to fill. + * @retval NONE + */ +static void NDEF_FillWifiTokenStruct( uint8_t* pPayload, uint32_t PayloadSize, sWifiTokenInfo *pWifiTokenStruct) +{ + uint8_t* pLastByteAdd,data1,data2,*temp,*temp_br ; + uint16_t SSIDLen,NetWorkKeyLen; + uint8_t *dbg,dbg1; + + + pLastByteAdd = (uint8_t*)(pPayload + PayloadSize); + pPayload--; + + while(pPayload++ != pLastByteAdd) + { + uint8_t attribute = *pPayload; + temp_br = pPayload; + switch(attribute) + { + + case ATTRIBUTE_ID_SSID_LSB: + temp = pPayload; + dbg = temp; + dbg1 = *++dbg; + if(dbg1 == ATTRIBUTE_ID_SSID_MSB ) + { + data1 = *++dbg; + data2 = *++dbg; + SSIDLen = data1; + SSIDLen = SSIDLen << 8; + SSIDLen |= data2; + pPayload += 4; + memcpy( pWifiTokenStruct->NetworkSSID, pPayload, SSIDLen); + /* add end of string charactere */ + pWifiTokenStruct->NetworkSSID[SSIDLen] = '\0'; + pPayload += SSIDLen - 1; + } + else if(dbg1 == ATTRIBUTE_ID_NETWORK_MSB ) + { + data1 = *++dbg; + data2 = *++dbg; + NetWorkKeyLen = data1; + NetWorkKeyLen = NetWorkKeyLen << 8; + NetWorkKeyLen |= data2; + pPayload += 4; + memcpy( pWifiTokenStruct->NetworkKey, pPayload, NetWorkKeyLen); + /* add end of string charactere */ + pWifiTokenStruct->NetworkKey[NetWorkKeyLen] = '\0'; + pPayload += NetWorkKeyLen -1; + } + else + { + pPayload = temp_br; + } + + break; + + default : + ; + } + } + +} + +/** + * @brief This fonction reads the WifiToken and store data in a structure. + * @param pRecordStruct Pointer on the record structure. + * @param pWifiTokenStruct Pointer on the structure to fill. + * @retval NONE + */ +static void NDEF_Read_WifiToken ( struct sRecordInfo *pRecordStruct, sWifiTokenInfo *pWifiTokenStruct ) +{ + uint8_t* pPayload; + uint32_t PayloadSize; + + PayloadSize = pRecordStruct->PayloadLength; + + /* Read record header */ + pPayload = (uint8_t*)(pRecordStruct->PayloadBufferAdd); + + if( pRecordStruct->NDEF_Type == URI_WIFITOKEN_TYPE) + NDEF_FillWifiTokenStruct(pPayload , PayloadSize, pWifiTokenStruct); + +} + + +/** + * @brief This fonction reads a NDEF record and retrieves a WifiToken information if any. + * @param pRecordStruct Pointer on the record structure. + * @param pWifiTokenStruct Pointer on a `sWifiTokenInfo` structure to fill with the WifiToken information. + * @retval NDEF_OK WifiToken information from NDEF have been retrieved. + * @retval NDEF_ERROR Not able to retrieve the WifiToken information. + */ +uint16_t NDEF_ReadWifiToken(struct sRecordInfo *pRecordStruct, sWifiTokenInfo *pWifiTokenStruct) +{ + uint16_t status = NDEF_ERROR; + + if( pRecordStruct->NDEF_Type == URI_WIFITOKEN_TYPE ) + { + NDEF_Read_WifiToken(pRecordStruct, pWifiTokenStruct ); + status = NDEF_OK; + } + + return status; +} + + +/** + * @brief This fonction writes a NDEF message built with the WifiToken data given in the structure. + * @param pWifiTokenStruct Pointer on the structure containing the WifiToken information. + * @retval NDEF_OK The NDEF message has been successfully written. + * @retval NDEF_ERROR Not able to store the NDEF message inside the tag. + */ +uint16_t NDEF_WriteWifiToken ( sWifiTokenInfo *pWifiTokenStruct ) +{ + uint16_t status = NDEF_ERROR; + uint8_t* pPayload,initStage = 0; + uint16_t DataSize; + uint32_t PayloadSize,SSIDSize,SSIDKeySize; + + if(pWifiTokenStruct->NetworkKey[0] == '\0') + { + /* Empty network key is not supported by Phones */ + strcpy(pWifiTokenStruct->NetworkKey, NDEF_WIFI_DEFAULT_NETWORK_KEY); + } + + uint8_t configToken1[] = {0x10,0x4A, /* Attribute ID : Version*/ + 0x00,0x01, /* Attribute ID Length*/ + 0x10, /* Version 1.0*/ + 0x10,0x0E, /* Attribute ID Credential*/ + 0x00,0x48, /* Attribute ID Length*/ + 0x10,0x26, /* Attribute ID : Network Index*/ + 0x00,0x01, /* Attribute Length*/ + 0x01, /* Index */ + 0x10,0x45, /* Attribute ID :SSID*/ + + }; + + /* Fill SSID length + SSID between configToken1 and configToken3*/ + + uint8_t configToken3[] = {0x10,0x03, /* Attribute ID :Authentication Type*/ + 0x00,0x02, /* Attribute Length*/ + 0x00,0x01, /* Attribute Type : Open*/ + 0x10,0x0F, /* Attribute ID : Encryption Type*/ + 0x00,0x02, /* Attribute Length*/ + 0x00,0x01, /* Encryption Type : None*/ + 0x10,0x27}; /* Attribute ID : Network Key */ + + + /*Fill SSID KEY Length and SSID Key between configToken3 and configToken5*/ + + uint8_t configToken5[] = {0x10,0x20, /* Attribute ID : MAC Address */ + 0x00,0x06, /* Attribute Length*/ + 0, /*MAC-ADDRESS*/ + 0, /*MAC-ADDRESS*/ + 0, /*MAC-ADDRESS*/ + 0, /*MAC-ADDRESS*/ + 0, /*MAC-ADDRESS*/ + 0, /*MAC-ADDRESS*/ + 0x10,0x49, /* Attribute ID : Vendor Extension */ + 0x00,0x06, /* Attribute Length*/ + 0x00,0x37,0x2A, /* Vendor ID:WFA*/ + 0x02, /* Subelement ID:Network Key Shareable*/ + 0x01, /* Subelement Length*/ + 0x01, /*Network Key Shareable : TRUE*/ + 0x10,0x49, /* Attribute ID : Vendor Extension */ + 0x00,0x06,/* Attribute Length*/ + 0x00,0x37,0x2A,/* Vendor ID:WFA*/ + 0x00, /* Subelement ID:Version2*/ + 0x01, /* Subelement Length:1*/ + 0x20 /* Version2*/ + }; + + + /* Set size of the tokens */ + const uint32_t CONFIG_TOKEN_1 = sizeof(configToken1); + const uint32_t CONFIG_TOKEN_3 = sizeof(configToken3); + const uint32_t CONFIG_TOKEN_5 = sizeof(configToken5); + + /* Update Token3 for Autentication & Encryption Types, their default value is coded in token3 */ + configToken3[CONFIG_TOKEN_3_AUTHENTICATION_TYPE_INDEX] = pWifiTokenStruct->AuthenticationType & 0xFF; + configToken3[CONFIG_TOKEN_3_ENCRYPTION_TYPE_INDEX] = pWifiTokenStruct->EncryptionType & 0xFF; + + /* fill Wifi record header */ + NDEF_Buffer[FIRST_RECORD_OFFSET] = 0xD2; /* Record Flag */ + NDEF_Buffer[FIRST_RECORD_OFFSET+1] = WIFITOKEN_TYPE_STRING_LENGTH; + NDEF_Buffer[FIRST_RECORD_OFFSET+2] = 76; /* needs to be autocalculated - done at the end */ + + memcpy(&NDEF_Buffer[FIRST_RECORD_OFFSET+3], WIFITOKEN_TYPE_STRING, WIFITOKEN_TYPE_STRING_LENGTH); + + pPayload = &NDEF_Buffer[FIRST_RECORD_OFFSET+3+WIFITOKEN_TYPE_STRING_LENGTH]; + PayloadSize = 0; + + /* Compute credential length */ + + uint16_t credential_length = 5 + // Network index + 4 + // SSID type + length + strlen(pWifiTokenStruct->NetworkSSID) + // SSID + CONFIG_TOKEN_3 + + 2 + // Network key length + strlen(pWifiTokenStruct->NetworkKey) + // Network KEY + CONFIG_TOKEN_5; + + /* update credential length */ + configToken1[CONFIG_TOKEN_1_CREDENTIAL_LENGTH_INDEX + 1] = credential_length & 0xff; + configToken1[CONFIG_TOKEN_1_CREDENTIAL_LENGTH_INDEX] = credential_length>>8; + + + for(initStage=0;initStageNetworkSSID); + *pPayload = 0x00; pPayload++; + *pPayload = SSIDSize & 0x000000FF; pPayload++; + + strcpy((char*)pPayload,pWifiTokenStruct->NetworkSSID); + pPayload = pPayload + strlen(pWifiTokenStruct->NetworkSSID); + + for(initStage=0;initStageNetworkKey); + *pPayload = 0x00; pPayload++; + *pPayload = SSIDKeySize & 0x000000FF; pPayload++; + + memcpy((char*)pPayload,pWifiTokenStruct->NetworkKey,SSIDKeySize); + pPayload = pPayload + SSIDKeySize; + + for(initStage=0;initStage= NFCTAG_NOTSET) + return NDEF_ERROR; + + if(protocol == NFCTAG_TYPE1) + ccFileOffset = 10; + else if (protocol == NFCTAG_TYPE2) + ccFileOffset = 12; + else + ccFileOffset = 0; + + CurrentProtocol = protocol; + return NDEF_OK; +} + +uint16_t NfcTag_ReadNDEF( uint8_t* pData ) +{ + uint16_t status = NDEF_ERROR; + switch (CurrentProtocol) + { + case NFCTAG_TYPE4: + status = NfcType4_ReadNDEF(pData); + break; + case NFCTAG_TYPE3: + status = NfcType3_ReadNDEF(pData); + break; + case NFCTAG_TYPE5: + case NFCTAG_TYPE2: + case NFCTAG_TYPE1: + status = NfcType5_ReadNDEF(pData); + break; + default: + status = NDEF_ERROR; + break; + } + return status; +} + + +uint16_t NfcTag_WriteNDEF(uint16_t Length , uint8_t *pData ) +{ + uint16_t status = NDEF_ERROR; + switch (CurrentProtocol) + { + case NFCTAG_TYPE4: + status = NfcType4_WriteNDEF(Length, pData); + break; + case NFCTAG_TYPE3: + status = NfcType3_WriteNDEF(Length,pData); + break; + case NFCTAG_TYPE5: + case NFCTAG_TYPE2: + case NFCTAG_TYPE1: + status = NfcType5_WriteNDEF(Length, pData); + break; + default: + status = NDEF_ERROR; + break; + } + return status; +} + +uint16_t NfcTag_GetLength(uint16_t* Length) +{ + uint16_t status = NDEF_ERROR; + switch (CurrentProtocol) + { + case NFCTAG_TYPE4: + status = NfcType4_GetLength(Length); + break; + case NFCTAG_TYPE3: + status = NfcType3_GetLength(Length); + break; + case NFCTAG_TYPE5: + case NFCTAG_TYPE2: + case NFCTAG_TYPE1: + status = NfcType5_GetLength(Length); + break; + default: + status = NDEF_ERROR; + break; + } + return status; +} \ No newline at end of file diff --git a/src/hydranfc_v2/lib/ndef/src/tagtype3_wrapper.c b/src/hydranfc_v2/lib/ndef/src/tagtype3_wrapper.c new file mode 100644 index 0000000..3aed5d7 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/tagtype3_wrapper.c @@ -0,0 +1,83 @@ +#include "lib_wrapper.h" +#include "lib_NDEF.h" + +typedef struct __attribute__((packed)) { + uint8_t Ver; + uint8_t Nbr; + uint8_t Nbw; + uint16_t NmaxB; + uint8_t rfu[4]; + uint8_t WriteFlag; + uint8_t RWFlag; + uint8_t Ln[3]; + uint16_t Checksum; +} TT3_Attr_Info_t; + +static TT3_Attr_Info_t NDEF_Attr_Info; +uint16_t NfcType3_GetLength(uint16_t* Length) +{ + uint32_t t3NdefLen; + uint8_t err = BSP_NFCTAG_ReadData(&NDEF_Attr_Info,0,16); + if(err != NFCTAG_OK) + { + return NDEF_ERROR; + } + t3NdefLen = NDEF_Attr_Info.Ln[0] << 16 | + NDEF_Attr_Info.Ln[1] << 8 | + NDEF_Attr_Info.Ln[2]; + if(t3NdefLen < 0x10000) + *Length = t3NdefLen; + else + return NFCTAG_ERROR; + + return NDEF_OK; +} + +uint16_t NfcType3_ReadNDEF( uint8_t* pData ) +{ + uint16_t length; + uint8_t err; + uint16_t status = NfcType3_GetLength(&length); + if(status != NDEF_OK) + { + return status; + } + err = BSP_NFCTAG_ReadData(pData,16,length); + if(err != NFCTAG_OK) + { + return NDEF_ERROR; + } + return NDEF_OK; + +} + +uint16_t NfcType3_WriteNDEF(uint16_t Length, uint8_t* pData ) +{ + uint8_t err = BSP_NFCTAG_WriteData(pData,16,Length); + if(err != NFCTAG_OK) + { + return NDEF_ERROR; + } + + err = BSP_NFCTAG_ReadData(&NDEF_Attr_Info,0,16); + if(err != NFCTAG_OK) + { + return NDEF_ERROR; + } + // update the length field + NDEF_Attr_Info.Ln[0] = (Length >> 16) & 0xFF; + NDEF_Attr_Info.Ln[1] = (Length >> 8) & 0xFF; + NDEF_Attr_Info.Ln[2] = Length & 0xFF; + err = BSP_NFCTAG_WriteData(&NDEF_Attr_Info,0,16); + if(err != NFCTAG_OK) + { + return NDEF_ERROR; + } + + return NDEF_OK; +} + +uint16_t NfcType3_WriteProprietary(uint16_t Length, uint8_t* pData ) +{ + return NDEF_ERROR; +} diff --git a/src/hydranfc_v2/lib/ndef/src/tagtype4_wrapper.c b/src/hydranfc_v2/lib/ndef/src/tagtype4_wrapper.c new file mode 100644 index 0000000..44a4563 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/tagtype4_wrapper.c @@ -0,0 +1,50 @@ +#include "lib_wrapper.h" +#include "lib_NDEF.h" + +uint16_t NfcType4_GetLength(uint16_t* Length) +{ + uint8_t err = BSP_NFCTAG_ReadData(Length,0,2); + *Length = (*Length & 0xFF) << 8 | (*Length & 0xFF00) >> 8; + + if(err != NFCTAG_OK) + { + return NDEF_ERROR; + } + return NDEF_OK; +} + +uint16_t NfcType4_ReadNDEF( uint8_t* pData ) +{ + uint16_t length; + uint8_t err; + uint16_t status = NfcType4_GetLength(&length); + if(status != NDEF_OK) + { + return status; + } + err = BSP_NFCTAG_ReadData(pData,2,length); + if(err != NFCTAG_OK) + { + return NDEF_ERROR; + } + return NDEF_OK; + +} + +uint16_t NfcType4_WriteNDEF(uint16_t Length, uint8_t* pData ) +{ + uint8_t txLen[2]; + txLen[0] = Length >> 8; + txLen[1] = Length & 0xFF; + uint16_t status = BSP_NFCTAG_WriteData(txLen, 0, 2); + if(status != NDEF_OK) + { + return status; + } + return BSP_NFCTAG_WriteData(pData, 2, Length); +} + +uint16_t NfcType4_WriteProprietary(uint16_t Length, uint8_t* pData ) +{ + return NDEF_ERROR; +} diff --git a/src/hydranfc_v2/lib/ndef/src/tagtype5_wrapper.c b/src/hydranfc_v2/lib/ndef/src/tagtype5_wrapper.c new file mode 100644 index 0000000..0eae5e4 --- /dev/null +++ b/src/hydranfc_v2/lib/ndef/src/tagtype5_wrapper.c @@ -0,0 +1,498 @@ +/** + ****************************************************************************** + * @file tagtype5_wrapper.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file provides an abstraction layer to the libNDEF for the NFC Forum Type5 Tag. + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "tagtype5_wrapper.h" + +/** @addtogroup Tag_Type_5 Type 5 Tag library + * @ingroup libNFC_FORUM + * @{ + * @brief This module provides an abstraction layer to the NDEF library for the NFC Forum Type5 Tag. + * @details These functions manage the specificities of the Type5 Tag accesses.\n + * The NFC Forum defines specific Capability Containers for the Type5 Tags. + * The Capability Container provides basic information on how a tag can be accessed. + * Depending on the memory size of the tag, 2 different CC will be used: + * 1. 4-bytes Capability Container (Memory Size < 16kbits): + * |Byte0 |Byte1 |Byte2 |Byte3 | + * |:------------:|:---------------------------:|:-----------:|:--------------:| + * | Magic Number | Version & Access Conditions | Memory Size | NFC Type 5 Tag | + * 2. 8-bytes Capability Container (Memory Size > 16kbits): + * |Byte0 |Byte1 |Byte2|Byte3 |Byte4|Byte5|Byte6 |Byte7 | + * |:------------:|:---------------------------:|:---:|:--------------:|:---:|:---:|:---------:|:---------:| + * | Magic Number | Version & Access Conditions | 00h | NFC Type 5 Tag |RFU |RFU |Memory Size|Memory Size| + * @section Type5_Tag_Usage How to write a Type5 Tag Capability Container + * 1. Initialize the Capacity Container structure with the Tag compliant values: + - Example for a 4kbits memory tag: + + CCFileStruct.MagicNumber = NFCT5_MAGICNUMBER_E1_CCFILE; + CCFileStruct.Version = NFCT5_VERSION_V1_0; + CCFileStruct.MemorySize = 0x40; + CCFileStruct.TT5Tag = 0x0; + + - Example for a 64kbits memory tag: + + CCFileStruct.MagicNumber = NFCT5_MAGICNUMBER_E2_CCFILE; + CCFileStruct.Version = NFCT5_VERSION_V1_0; + CCFileStruct.MemorySize = NFCT5_EXTENDED_CCFILE; + CCFileStruct.ExtMemorySize = 0x400; + CCFileStruct.TT5Tag = 0x1; + + 2. Call the `NfcType5_TT5Init` function to write the Capability Container to the Tag: + + NfcType5_TT5Init(); + + */ + +/** @brief Capability Container structure instance (global). */ +sCCFileInfo CCFileStruct; +uint16_t ccFileOffset = 0; + +/** + * @brief This function reads the data stored in the NDEF message. + * @param pData Pointer on the buffer used to store the read data. + * @retval NDEF_ERROR_MEMORY_INTERNAL The buffer is too small for the NDEF message. + * @retval NDEF_ERROR_NOT_FORMATED No Capability Container detected. + * @retval NDEF_ERROR Error when reading the NDEF message. + * @retval NDEF_OK NDEF message successfully read. + */ +uint16_t NfcType5_ReadNDEF( uint8_t* pData ) +{ + uint16_t status = NDEF_ERROR; + TT5_TLV_t tlv; + uint8_t tlv_size = 0; + uint16_t DataLength; + + /* Detect NDEF message in memory */ + status = NfcType5_NDEFDetection( ); + if( status != NDEF_OK ) + { + return status; + } + + /* Read TL of Type 5 */ + status = BSP_NFCTAG_ReadData( (uint8_t*)&tlv, CCFileStruct.NDEF_offset, sizeof(TT5_TLV_t) ); + if( status != NDEF_OK ) + { + return status; + } + + /* Check if L is on 3 or 1 byte and update length in buffer */ + if( tlv.Length == NFCT5_3_BYTES_L_TLV ) + { + tlv_size = 4; + DataLength = ((tlv.Length16 >> 8)&0xff) | ((tlv.Length16&0xff)<<8); + } + else + { + tlv_size = 2; + DataLength = tlv.Length; + } + /* If too many data to write return error */ + if( DataLength > NDEF_MAX_SIZE ) + { + return NDEF_ERROR_MEMORY_INTERNAL; + } + + /* Check CC file is in the correct mode to proceed */ + if( CCFileStruct.State == TT5_INITIALIZED ) + { + return NDEF_OK; + } + + if( DataLength > 0 ) + { + /* Read NDEF */ + if( BSP_NFCTAG_ReadData( (pData), CCFileStruct.NDEF_offset + tlv_size, DataLength ) != NFCTAG_OK ) + { + return NDEF_ERROR; + } + } + + return NDEF_OK; +} + +/** + * @brief This function writes data in the NFC Tag. + * @param Type Type of the data: NDEF or Proprietary + * @param Length Number of bytes to write. + * @param pData Pointer on the buffer to copy. + * @retval NDEF_ERROR_MEMORY_INTERNAL Memory size is too small for the data. + * @retval NDEF_ERROR_NOT_FORMATED No Capability Container detected. + * @retval NDEF_ERROR Error when writing the Tag. + * @retval NDEF_OK The data has been successfully written. + */ +uint16_t NfcType5_WriteData(uint8_t Type, uint16_t Length , uint8_t *pData ) +{ + TT5_TLV_t tlv; + uint8_t tlv_size; + uint32_t offset; + uint8_t NfcT5_Terminator = NFCT5_TERMINATOR_TLV; + + uint32_t max_length = BSP_NFCTAG_GetByteSize() /* Memory size */ + - ((Length >= 0xFF) ? 4 : 2) /* - TLV length */ + - sizeof(NfcT5_Terminator) /* - Terminator TLV */ + - CCFileStruct.NDEF_offset; /* - CCfile length */ + + /* If too many data to write return error */ + if( Length > max_length ) + { + return NDEF_ERROR_MEMORY_TAG; + } + + /* Detect NDEF message in memory */ + if( NfcType5_NDEFDetection( ) != NDEF_OK ) + { + return NDEF_ERROR; + } + + /* Prepare TLV */ + tlv.Type = Type; + if(Length >= 0xFF) + { + tlv.Length = NFCT5_3_BYTES_L_TLV; + tlv.Length16 = ((Length&0xff)<<8) | ((Length>>8)&0xff) ; + tlv_size = 4; + + } else { + tlv.Length = Length; + tlv_size = 2; + } + + offset = CCFileStruct.NDEF_offset; + /* Start write TLV to EEPROM */ + if(BSP_NFCTAG_WriteData( (uint8_t*)&tlv, offset, tlv_size )!= NFCTAG_OK) + return NDEF_ERROR; + offset += tlv_size; + + /* Continue write TLV data to EEPROM */ + if(BSP_NFCTAG_WriteData( pData , offset, Length ) != NFCTAG_OK ) + return NDEF_ERROR; + offset +=Length; + + /* Write Terminator TLV */ + if(BSP_NFCTAG_WriteData( &NfcT5_Terminator, offset, sizeof(NfcT5_Terminator) ) != NFCTAG_OK) + return NDEF_ERROR; + + return NDEF_OK; + +} + +/** + * @brief This function writes a NDEF message in the NFC Tag. + * @param Length Number of bytes to write. + * @param pData Pointer on the buffer to copy. + * @retval NDEF_ERROR_MEMORY_INTERNAL Memory size is too small for the data. + * @retval NDEF_ERROR_NOT_FORMATED No Capability Container detected. + * @retval NDEF_ERROR Error when writing the Tag. + * @retval NDEF_OK The data has been successfully written. + */ +uint16_t NfcType5_WriteNDEF(uint16_t Length , uint8_t *pData ) +{ + return NfcType5_WriteData(NFCT5_NDEF_MSG_TLV,Length,pData); +} + +/** + * @brief This function writes a Proprietary message to the NFC Tag. + * @param Length Number of byte to write. + * @param pData Pointer on the buffer to copy. + * @retval NDEF_ERROR_MEMORY_INTERNAL Memory size is too small for the data. + * @retval NDEF_ERROR_NOT_FORMATED No Capability Container detected. + * @retval NDEF_ERROR Error when writing the Tag. + * @retval NDEF_OK The data has been successfully written. + */ +uint16_t NfcTag_WriteProprietary(uint16_t Length , uint8_t *pData ) +{ + return NfcType5_WriteData(NFCT5_PROPRIETARY_TLV,Length,pData); +} + + +/** + * @brief This functions writes the Capability Container in the NFC Tag. + * @param pCCBuffer Pointer on the buffer containnig the Capability Container. + * @retval NDEF_ERROR Error when writing the Tag. + * @retval NDEF_OK The CC has been successfully written. + */ +uint16_t NfcType5_WriteCCFile( const uint8_t * const pCCBuffer ) +{ + NFCTAG_StatusTypeDef ret_value; + + /* Write first block of CCFile */ + ret_value = BSP_NFCTAG_WriteData( pCCBuffer, 0x00, 0x4 ); + + /* If extended memory writes the next 4 bytes */ + if( (pCCBuffer[2] == 0x00) && (ret_value == NFCTAG_OK) ) + { + ret_value = BSP_NFCTAG_WriteData( pCCBuffer + 4, 0x04, 4 ); + } + + if( ret_value != NFCTAG_OK ) + { + return NDEF_ERROR; + } + + return NDEF_OK; +} + +/** + * @brief This functions reads the Capability Container from the NFC Tag. + * @param pCCBuffer Pointer on the buffer used to store the CC. + * @retval NDEF_ERROR Error when reading the Tag. + * @retval NDEF_OK The CC has been successfully read. + */ +uint16_t NfcType5_ReadCCFile( uint8_t * const pCCBuffer ) +{ + NFCTAG_StatusTypeDef ret_value; + + /* Read 4 bytes of CC File */ + ret_value = BSP_NFCTAG_ReadData( pCCBuffer, ccFileOffset, 4 ); + + /* If extended memory reads the next 4 bytes */ + if( (pCCBuffer[2] == 0x00) && (ret_value == NFCTAG_OK) ) + { + ret_value = BSP_NFCTAG_ReadData( pCCBuffer + 4, ccFileOffset + 0x04, 4 ); + } + + if( ret_value != NFCTAG_OK ) + { + return NDEF_ERROR; + } + + return NDEF_OK; +} + +/** + * @brief This function initializes the Capability Container and an empty NDEF message in a NFC Tag. + * @details The Capability Container content is defined by the global variable `CCFileStruct`. + * @retval NDEF_ERROR The Tag has not been initialized. + * @retval NDEF_OK The Tag has been successfully initialized. + */ +uint16_t NfcType5_TT5Init( void ) +{ + NFCTAG_StatusTypeDef ret_value = NFCTAG_OK; + uint16_t status; + uint8_t accbuffer[8]; + uint8_t cdata; + + /* Prepare buffer to update CCFile */ + accbuffer[0] = CCFileStruct.MagicNumber; + accbuffer[1] = CCFileStruct.Version; + accbuffer[2] = CCFileStruct.MemorySize; + accbuffer[3] = CCFileStruct.TT5Tag; + CCFileStruct.NDEF_offset = ccFileOffset + 0x04; + + /* If extended memory prepare the length bytes */ + if( CCFileStruct.MemorySize == NFCT5_EXTENDED_CCFILE ) + { + accbuffer[6] = (uint8_t)(CCFileStruct.ExtMemorySize >> 8); + accbuffer[7] = (uint8_t)(CCFileStruct.ExtMemorySize & 0xFF); + CCFileStruct.NDEF_offset = ccFileOffset + 0x08; + } + + /* Update CCFile */ + status = NfcType5_WriteCCFile( accbuffer ); + if( status != NDEF_OK ) + { + return status; + } + + /* Update NDEF TLV for INITIALIZED state */ + /* Update T */ + cdata = NFCT5_NDEF_MSG_TLV; + ret_value = BSP_NFCTAG_WriteData( &cdata, CCFileStruct.NDEF_offset, 1 ); + if( ret_value != NFCTAG_OK ) + { + return NDEF_ERROR; + } + + /* Update L */ + cdata = 0x00; + ret_value = BSP_NFCTAG_WriteData( &cdata, (CCFileStruct.NDEF_offset + 1), 1 ); + if( ret_value != NFCTAG_OK ) + { + return NDEF_ERROR; + } + + return NDEF_OK; +} + +/** + * @brief This function detects a NDEF message in a Type 5 Tag. + * @details It first detects the Capability Container and then look for the NDEF TLV. + * The `CCfileStruct` global variable is updated accordingly with what is detected. + * @retval NDEF_OK NDEF message Tag Type 5 detected. + * @retval NDEF_ERROR_NOT_FORMATED Device is not a NFC Tag Type 5 Tag. + */ +uint16_t NfcType5_NDEFDetection( void ) +{ + uint8_t acc_buffer[8]; + TT5_TLV_t tlv_detect; + uint16_t status; + uint32_t memory_size; + + CCFileStruct.State = TT5_NO_NDEF; + + /* Read CCFile */ + status = NfcType5_ReadCCFile( acc_buffer ); + if( status != NDEF_OK ) + { + return status; + } + + /* Check Byte 0 is equal to magic number */ + if( ( acc_buffer[0] != NFCT5_MAGICNUMBER_E1_CCFILE ) && ( acc_buffer[0] != NFCT5_MAGICNUMBER_E2_CCFILE ) ) + { + return NDEF_ERROR_NOT_FORMATED; + } + /* Check Version number */ + else if( ( (acc_buffer[1]&0xFC) != 0x40 ) && ((acc_buffer[1]&0xFC) != 0x10 ) ) + { + return NDEF_ERROR_NOT_FORMATED; + } + + /* Check if CCFile is on 4 Bytes or 8 Bytes */ + if( acc_buffer[2] == 0x00 ) + { + /* Update CCFIle structure */ + CCFileStruct.MemorySize = 0x0; + CCFileStruct.ExtMemorySize = (uint16_t)acc_buffer[6]; + CCFileStruct.ExtMemorySize = ( CCFileStruct.ExtMemorySize << 8 ) | acc_buffer[7]; + memory_size = CCFileStruct.ExtMemorySize; + CCFileStruct.NDEF_offset = ccFileOffset + 8; + } + else + { + /* Update CCFIle structure */ + CCFileStruct.MemorySize = acc_buffer[2]; + CCFileStruct.ExtMemorySize = 0x0; + memory_size = CCFileStruct.MemorySize; + CCFileStruct.NDEF_offset = ccFileOffset + 4; + } + + /* Update CCFIle structure */ + CCFileStruct.MagicNumber = (TT5_MagicNumber_t)acc_buffer[0]; + CCFileStruct.Version = acc_buffer[1]; + CCFileStruct.TT5Tag = acc_buffer[3]; + + /* Search for position of NDEF TLV in memory and tag status */ + while( ( BSP_NFCTAG_ReadData( (uint8_t *)&tlv_detect, CCFileStruct.NDEF_offset, sizeof(TT5_TLV_t) ) == NFCTAG_OK ) && ( CCFileStruct.NDEF_offset < memory_size ) ) + { + /* Detect first NDEF Message in memory */ + if( tlv_detect.Type == NFCT5_NDEF_MSG_TLV ) + { + if( tlv_detect.Length == 0x00 ) + { + CCFileStruct.State = TT5_INITIALIZED; + } + else + { + if( CCFileStruct.Version & 0x3 ) + { + CCFileStruct.State = TT5_READ; + } + else + { + CCFileStruct.State = TT5_READ_WRITE; + } + } + return NDEF_OK; + } + /* If Proprietary NDEF jump to end of proprietary message */ + else if(( tlv_detect.Type == NFCT5_PROPRIETARY_TLV ) || + ( tlv_detect.Type == NFCT1_LOCK_CONTROL_TLV ) || + ( tlv_detect.Type == NFCT1_MEMORY_CONTROL_TLV )) + { + if( tlv_detect.Length == NFCT5_3_BYTES_L_TLV ) + { + CCFileStruct.NDEF_offset = CCFileStruct.NDEF_offset + tlv_detect.Length16 + 4; + continue; + } + else + { + CCFileStruct.NDEF_offset = CCFileStruct.NDEF_offset + tlv_detect.Length + 2; + continue; + } + } + /* if Terminator no NDEF detected */ + else if( tlv_detect.Type == NFCT5_TERMINATOR_TLV ) + { + return NDEF_ERROR_NOT_FORMATED; + } + + CCFileStruct.NDEF_offset++; + } + + return NDEF_ERROR_NOT_FORMATED; +} + + + +/** + * @brief This function reads and return the size of the NDEF message in the NFC tag. + * @param Length Pointer on the NDEF size to be returned. + * @retval NDEF_ERROR_NOT_FORMATED Device is not a NFC Tag Type 5 Tag. + * @retval NDEF_ERROR The NDEF message size has not been read. + * @retval NDEF_OK The NDEF message size has been retrieved. + */ +uint16_t NfcType5_GetLength(uint16_t* Length) +{ + + uint16_t status = NDEF_ERROR; + TT5_TLV_t tlv; + + /* Detect NDEF message in memory */ + status = NfcType5_NDEFDetection( ); + if( status != NDEF_OK ) + { + return status; + } + + /* Read TL of Type 5 */ + status = BSP_NFCTAG_ReadData( (uint8_t*)&tlv, CCFileStruct.NDEF_offset, sizeof(TT5_TLV_t) ); + if( status != NFCTAG_OK ) + { + return NDEF_ERROR; + } + + if(tlv.Length != NFCT5_3_BYTES_L_TLV) + { + *Length = tlv.Length; + } else { + *Length = ((tlv.Length16 >> 8)&0xff) | ((tlv.Length16 & 0xff) << 8); + } + + return NDEF_OK; + +} + + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2016 STMicroelectronics *****END OF FILE****/ diff --git a/src/hydranfc_v2/lib/st25r/inc/st25r.h b/src/hydranfc_v2/lib/st25r/inc/st25r.h new file mode 100644 index 0000000..fa6d387 --- /dev/null +++ b/src/hydranfc_v2/lib/st25r/inc/st25r.h @@ -0,0 +1,59 @@ + +#include "stdint.h" +#include "rfal_nfca.h" +#include "rfal_nfcb.h" +#include "rfal_nfcf.h" +#include "rfal_nfcv.h" +#include "rfal_st25tb.h" +#include "rfal_isoDep.h" +#include "rfal_nfcDep.h" + +#ifndef _ST25R_ +#define _ST25R_ + +/** Type for Callback for long waiting time */ +typedef uint8_t (BSP_NFCTAG_WaitingCallback_t)(void); +/** Callback for NFCA long waiting time */ +extern BSP_NFCTAG_WaitingCallback_t *BSP_NFCTAG_WaitingCb; + +/** Type tag definition */ +typedef enum { + BSP_NFCTAG_NFCA = 0, /** NFCA type tag */ + BSP_NFCTAG_NFCB, /** NFCB type tag */ + BSP_NFCTAG_ST25TB, /** ST25TB type tag */ + BSP_NFCTAG_NFCF, /** NFCF type tag */ + BSP_NFCTAG_NFCV /** NFCV type tag */ +} BSP_NFCTAG_Protocol_Id_t; + +/** Device information structure - based on RFAL but adapted for NDEF support */ +typedef struct { + BSP_NFCTAG_Protocol_Id_t type; /* Device's type */ + union { + 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; + union { + rfalIsoDepDevice isoDep; /* ISO-DEP instance */ + rfalNfcDepDevice nfcDep; /* NFC-DEP instance */ + }proto; /* Device's protocol */ + uint8_t NdefSupport; /* The device supports Ndef */ +} BSP_NFCTAG_Device_t; + +/** Porotcol API structure */ +typedef struct { +uint8_t (*activate)(void); /** Activation phase API */ +uint8_t (*read_data)(uint8_t* , uint32_t , uint32_t ); /** Read method */ +uint8_t (*write_data)(uint8_t* , uint32_t , uint32_t ); /** Write method */ +} BSP_NFCTAG_Protocol_t; + +uint8_t BSP_NFCTAG_Activate(BSP_NFCTAG_Device_t * device); +uint8_t BSP_NFCTAG_ReadData(uint8_t* buffer, uint32_t offset, uint32_t length); +uint8_t BSP_NFCTAG_WriteData(uint8_t* buffer, uint32_t offset, uint32_t length); +uint16_t BSP_NFCTAG_GetByteSize(void); +uint8_t BSP_NFCTAG_T4_SelectFile(uint16_t fileId); +uint8_t BSP_NFCTAG_CheckVicinity(void); + +#endif // _ST25R_ diff --git a/src/hydranfc_v2/lib/st25r/src/st25r.c b/src/hydranfc_v2/lib/st25r/src/st25r.c new file mode 100644 index 0000000..6485a57 --- /dev/null +++ b/src/hydranfc_v2/lib/st25r/src/st25r.c @@ -0,0 +1,1152 @@ +/** + ****************************************************************************** + * @file st25_discovery_st25r.c + * @author MMY Application Team + * @version $Revision$ + * @date $Date$ + * @brief This file provides set of firmware functions to manage nfc tags + * from a ST25 Reader perspective (rfal based). + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ +#include "st25r.h" +#include "hydranfc_v2_common.h" +#include "utils.h" + +/* Hold current selected NFC device instance */ +static BSP_NFCTAG_Device_t *Current = NULL; +/* Hold current protocol set */ +static BSP_NFCTAG_Protocol_t *CurrentProtocol = NULL; + +/* NFC T2 Read command */ +static uint8_t t2tReadReq[] = {0x30, 0x00}; /* T2T READ Block:0 */ +/* NFC T2 Write command */ +static uint8_t t2tWriteReq[] = {0xA2, 0x00, 0x00, 0x00, 0x00, 0x00}; /* T2T READ Block:0 */ +/* NFC T3 Check command */ +static uint8_t t3tCheckReq[] = {0x06, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, + 0x88, 0x01, 0x09, 0x00, 0x01, 0x80, 0x00}; /* T3T Check/Read command */ +/* NFC T3 Update command */ +static uint8_t t3tUpdateReq[] = {0x08, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, + 0x88, 0x01, 0x09, 0x00, 0x01, 0x80, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; /* T3T Update command */ +/* NFC T4 Select Ndef App command */ +static uint8_t t4tSelectNdefApp[] = {0x00, 0xA4, 0x04, 0x00, 0x07, 0xD2, 0x76, + 0x00, 0x00, 0x85, 0x01, 0x01, 0x00}; +/* NFC T4 Select File command */ +static uint8_t t4tSelectFile[] = {0x00, 0xA4, 0x00, 0x0C, 0x02, 0x00, 0x01}; +/* NFC T4 Write command */ +static uint8_t t4tWriteData[] = {0x00, 0xD6, 0x00, 0x00, 0x00}; +/* NFC T4 Read Binary command */ +/* Offset Length */ +static uint8_t t4tReadBinary[] = {0x00, 0xB0, 0x00, 0x00, 0x00}; + +/* NFC T4 Success code */ +static uint8_t t4Success[] = {0x90, 0x00}; + +/****************** NFCA *****************************/ +/* NFCA RX Buffer length in bytes */ +#define BSP_NFCTAG_NFCA_RXBUF_LENGTH 0xFF +static uint8_t BSP_NFCTAG_ReadData_NfcA(uint8_t *buffer, uint32_t offset, + uint32_t length); + +/* NFCA callback when waiting for a for long latency tag response */ +BSP_NFCTAG_WaitingCallback_t *BSP_NFCTAG_WaitingCb = NULL; + +/* Sends a T4 command, and waits the response */ +static ReturnCode t4tSendCommand(uint8_t *txBuf, uint16_t txLen, + rfalIsoDepBufFormat *rxBuf, uint16_t *rxBufLen) +{ + + ReturnCode err; + rfalIsoDepTxRxParam isoDepTxRx; + rfalIsoDepBufFormat isoDepTxBuf; /* ISO-DEP Tx buffer format (with header/prologue) */ + bool rxChaining = false; /* Rx chaining flag */ + + memcpy(isoDepTxBuf.inf, txBuf, txLen); + + isoDepTxRx.DID = RFAL_ISODEP_NO_DID; + isoDepTxRx.ourFSx = RFAL_ISODEP_FSX_KEEP; + isoDepTxRx.FSx = Current->proto.isoDep.info.FSx; + isoDepTxRx.dFWT = Current->proto.isoDep.info.dFWT; + isoDepTxRx.FWT = Current->proto.isoDep.info.FWT; + isoDepTxRx.txBuf = &isoDepTxBuf; + isoDepTxRx.txBufLen = txLen; + isoDepTxRx.isTxChaining = false; + isoDepTxRx.rxBuf = rxBuf; + isoDepTxRx.rxLen = rxBufLen; + isoDepTxRx.isRxChaining = &rxChaining; + + /*******************************************************************************/ + /* Trigger a RFAL ISO-DEP Transceive */ + err = rfalIsoDepStartTransceive(isoDepTxRx); + if (err != ERR_NONE) + { + return err; + } + do { + do { + err = rfalIsoDepGetTransceiveStatus(); + rfalWorker(); + // user callback when timeout is too long! + if (BSP_NFCTAG_WaitingCb != NULL) + { + if (!BSP_NFCTAG_WaitingCb()) + return err; + } + } while (err == ERR_BUSY); + } while ((err == ERR_NONE) && *isoDepTxRx.isRxChaining); + return err; +} + +/** + * @brief Selects the T4 tag file based on its fileId. + * @param fileId Id of the file to be selected + * @returns the command status, 0 is a success, other values are errors + */ +uint8_t BSP_NFCTAG_T4_SelectFile(uint16_t fileId) +{ + ReturnCode err; + rfalIsoDepBufFormat rxBuf; + uint16_t rxBufLen = sizeof(rxBuf); + + t4tSelectFile[5] = fileId >> 8; + t4tSelectFile[6] = fileId & 0xFF; + err = t4tSendCommand(t4tSelectFile, sizeof(t4tSelectFile), &rxBuf, + &rxBufLen); + if ((err != ERR_NONE) || (rxBuf.inf[0] != 0x90) + || (rxBuf.inf[1] != 0x00)) + { + return NFCTAG_ERROR; + } + + return NFCTAG_OK; +} + +/* NFCA Tag activation stage (Select Tag and NDEF file) */ +static uint8_t BSP_NFCTAG_Activate_NfcA(void) +{ + ReturnCode err; + rfalNfcaSensRes sensRes; + rfalNfcaSelRes selRes; + rfalIsoDepBufFormat rxBuf; + uint16_t rxBufLen = sizeof(rxBuf); + uint16_t ndefFileId; + + if (Current->type != BSP_NFCTAG_NFCA) + { + return NFCTAG_ERROR; + } + + // By default: claim that Ndef is not supported + Current->NdefSupport = 0; + + rfalFieldOnAndStartGT(); /* Turns the Field On and starts GT timer */ + rfalNfcaPollerInitialize(); + err = rfalNfcaPollerCheckPresence(RFAL_14443A_SHORTFRAME_CMD_WUPA, + &sensRes); /* Wake up all cards */ + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + + if (Current->dev.nfca.type != RFAL_NFCA_T1T) { + err = rfalNfcaPollerSelect(Current->dev.nfca.nfcId1, + Current->dev.nfca.nfcId1Len, &selRes); /* Select specific device */ + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + } else { + rfalT1TPollerInitialize(); + // Ndef are supported + Current->NdefSupport = 1; + } + + if (Current->dev.nfca.type == RFAL_NFCA_T4T) + { + /*******************************************************************************/ + rfalIsoDepInitialize(); + + /* Perform ISO-DEP (ISO14443-4) activation: RATS and PPS if supported */ + err = rfalIsoDepPollAHandleActivation( + (rfalIsoDepFSxI)RFAL_ISODEP_FSDI_DEFAULT, + RFAL_ISODEP_NO_DID, + RFAL_BR_848 /* RFAL_BR_424 RFAL_BR_106 */, + &Current->proto.isoDep); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + err = t4tSendCommand(t4tSelectNdefApp, sizeof(t4tSelectNdefApp), + &rxBuf, &rxBufLen); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + if (memcmp(t4Success, rxBuf.inf, sizeof(t4Success))) + { + return NFCTAG_RESPONSE_ERROR; + } + + // get NDEF file Id from CCfile + BSP_NFCTAG_T4_SelectFile(0xE103); + BSP_NFCTAG_ReadData_NfcA((uint8_t*)&ndefFileId, 9, 2); + ndefFileId = (ndefFileId >> 8) | ((ndefFileId & 0xFF) << 8); + err = BSP_NFCTAG_T4_SelectFile(ndefFileId); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + // Ndef are supported + Current->NdefSupport = 1; + } + return NFCTAG_OK; +} + +/* NFCA Tag read data method */ +static uint8_t BSP_NFCTAG_ReadData_NfcA(uint8_t *buffer, uint32_t offset, + uint32_t length) +{ + uint8_t rxBuf[RFAL_ISODEP_DEFAULT_FSC + RFAL_ISODEP_PROLOGUE_SIZE]; + uint16_t rxBufLen = 0xF0; + uint8_t err; + // read bytes + uint16_t rxLen = rxBufLen; + + uint16_t readBytes = 0; + uint16_t currentOffset = offset; + uint16_t currentLength = length; + while (currentLength > 0) + { + + switch (Current->dev.nfca.type) + { + /*******************************************************************************/ + case RFAL_NFCA_T1T: + /* To perform presence check, on this example a T1T Read command is used */ + err = rfalT1TPollerRall(Current->dev.nfca.nfcId1, rxBuf, + rxBufLen, &rxLen); + if ((rxLen < (length + currentOffset)) || (rxLen < 2)) + { + // Read all read less than expected length + // could be because of rxBufLen < tag length + return NFCTAG_ERROR; + } + rxLen = length; + memcpy(buffer, &rxBuf[currentOffset], length); + break; + + /*******************************************************************************/ + case RFAL_NFCA_T2T: + // 4 bytes blocks + t2tReadReq[1] = currentOffset / 4; + /* To perform presence check, on this example a T2T Read command is used */ + err = rfalTransceiveBlockingTxRx(t2tReadReq, + sizeof(t2tReadReq), rxBuf, rxBufLen, + &rxLen, RFAL_TXRX_FLAGS_DEFAULT, + rfalConvMsTo1fc(20)); + rxLen -= currentOffset % 4; + if (rxLen > currentLength) + rxLen = currentLength; + memcpy(buffer + readBytes, &rxBuf[currentOffset % 4], + rxLen); + break; + + /*******************************************************************************/ + case RFAL_NFCA_T4T: + t4tReadBinary[2] = (currentOffset) >> 8; + t4tReadBinary[3] = (currentOffset) & 0xFF; + t4tReadBinary[4] = + (currentLength) > rxBufLen ? + rxBufLen : + (currentLength); + + err = t4tSendCommand(t4tReadBinary, + sizeof(t4tReadBinary), + (rfalIsoDepBufFormat*)&rxBuf, &rxLen); + if (rxLen > 2) + { + rxLen -= 2; // status bytes + if (rxLen > currentLength) + rxLen = currentLength; + memcpy(buffer + readBytes, + &((rfalIsoDepBufFormat*)rxBuf)->inf[0], + rxLen); + } else { + rxLen = 0; + } + break; + default: + return NFCTAG_ERROR; + } + if ((err != ERR_NONE) || (rxLen == 0)) + { + return NFCTAG_ERROR; + } else { + currentOffset += rxLen; + currentLength -= rxLen; + readBytes += rxLen; + } + } // while (currentLength > 0) + return NFCTAG_OK; +} + +/* NFCA Tag write data method */ +uint8_t BSP_NFCTAG_WriteData_NfcA(uint8_t *buffer, uint32_t offset, + uint32_t length) +{ + uint8_t rxBuf[RFAL_ISODEP_DEFAULT_FSC + RFAL_ISODEP_PROLOGUE_SIZE]; + uint16_t rxLen = 0xF0; + uint8_t status = 0xFF; + uint16_t currentOffset = offset; + uint16_t lastOffset = offset + length; + uint16_t nbBytesToWrite = length; + uint8_t cmd[256 + 5 + 10]; + uint8_t nbBytesWritten = 0; + uint8_t block[10] = {0}; + + while (currentOffset < lastOffset) + { + + switch (Current->dev.nfca.type) + { + /*******************************************************************************/ + case RFAL_NFCA_T1T: + // -2 as H0 & H1 are not considered for block id + status = rfalT1TPollerWrite(Current->dev.nfca.nfcId1, + currentOffset - 2, *buffer); + if (status != ERR_NONE) + return NFCTAG_ERROR; + currentOffset++; + buffer++; + break; + + /*******************************************************************************/ + case RFAL_NFCA_T2T: + { + /* Manage offset and length for block based memories */ + uint8_t blockInternalOffset = currentOffset % 4; + uint8_t blockInternalLength = 4 - (currentOffset % 4); + blockInternalLength = + blockInternalLength > nbBytesToWrite ? + nbBytesToWrite : + blockInternalLength; + + if ((blockInternalOffset) || (blockInternalLength % 4)) + { + // 4 bytes block + t2tReadReq[1] = currentOffset / 4; + status = rfalTransceiveBlockingTxRx(t2tReadReq, + sizeof(t2tReadReq), block, 0xF0, + &rxLen, RFAL_TXRX_FLAGS_DEFAULT, + rfalConvMsTo1fc(20)); + if (status != ERR_NONE) + { + return NFCTAG_ERROR; + } + // remove first byte (tag status) + memcpy(&block[blockInternalOffset], buffer, + blockInternalLength); + buffer += blockInternalLength; + nbBytesWritten = blockInternalLength; + + } else { + memcpy(block, buffer, 4); + buffer += 4; + nbBytesWritten = 4; + } + + t2tWriteReq[1] = currentOffset / 4; + memcpy(&t2tWriteReq[2], block, 4); + status = rfalTransceiveBlockingTxRx(t2tWriteReq, + sizeof(t2tWriteReq), rxBuf, 0xF0, + &rxLen, RFAL_TXRX_FLAGS_DEFAULT, + rfalConvMsTo1fc(20)); + if (status >= ERR_INCOMPLETE_BYTE) + status = ERR_NONE; + if (status != ERR_NONE) + return NFCTAG_ERROR; + currentOffset += nbBytesWritten; + } + break; + + /*******************************************************************************/ + case RFAL_NFCA_T4T: + memcpy(cmd, t4tWriteData, sizeof(t4tWriteData)); + cmd[2] = offset >> 8; + cmd[3] = offset & 0xFF; + cmd[4] = length; + memcpy(&cmd[5], buffer, length); + status = t4tSendCommand(cmd, + sizeof(t4tWriteData) + length, + (rfalIsoDepBufFormat*)&rxBuf, &rxLen); + currentOffset += length; + if (memcmp(&rxBuf[1], t4Success, sizeof(t4Success))) + { + // not a success code + return NFCTAG_ERROR; + } + break; + } + } + + if (status == ERR_NONE) + return NFCTAG_OK; + else + return NFCTAG_ERROR; +} + +/* NFCA Api */ +static BSP_NFCTAG_Protocol_t apiNfcA = { + .activate = &BSP_NFCTAG_Activate_NfcA, + .read_data = &BSP_NFCTAG_ReadData_NfcA, + .write_data = &BSP_NFCTAG_WriteData_NfcA +}; + +/****************** NFCB *****************************/ +/* NFCB Tag activation (Select tag & NDEF file) */ +static uint8_t BSP_NFCTAG_Activate_NfcB(void) +{ + uint8_t err; + rfalNfcbSensbRes sensbRes; + uint8_t sensbResLen; + + Current->NdefSupport = 0; + + rfalFieldOnAndStartGT(); /* Turns the Field On and starts GT timer */ + if (Current->type == BSP_NFCTAG_ST25TB) + { + rfalSt25tbPollerInitialize(); + rfalFieldOnAndStartGT(); + + err = rfalSt25tbPollerCheckPresence( + &Current->dev.st25tb.chipID); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + err = rfalSt25tbPollerSelect(Current->dev.st25tb.chipID); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + + } + if (Current->type == BSP_NFCTAG_NFCB) + { + rfalIsoDepBufFormat rxBuf; + uint16_t rxBufLen = sizeof(rxBuf); + rfalNfcbPollerInitialize(); + + err = rfalNfcbPollerCheckPresence(RFAL_NFCB_SENS_CMD_ALLB_REQ, + RFAL_NFCB_SLOT_NUM_1, &sensbRes, &sensbResLen); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + + rfalIsoDepInitialize(); + err = rfalIsoDepPollBHandleActivation( + (rfalIsoDepFSxI)RFAL_ISODEP_FSDI_DEFAULT, + RFAL_ISODEP_NO_DID, RFAL_BR_424, 0x00, + &Current->dev.nfcb, NULL, 0, + &Current->proto.isoDep); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + err = t4tSendCommand(t4tSelectNdefApp, sizeof(t4tSelectNdefApp), + &rxBuf, &rxBufLen); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + + err = BSP_NFCTAG_T4_SelectFile(0x0001); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + Current->NdefSupport = 1; + } + return NFCTAG_OK; +} + +/* NFCB Tag read data method */ +static uint8_t BSP_NFCTAG_ReadData_NfcB(uint8_t *buffer, uint32_t offset, + uint32_t length) +{ + uint8_t err; + uint8_t rxBuf[4]; + if (Current->type == BSP_NFCTAG_ST25TB) + { + uint16_t readBytes = 0; + while (readBytes < length) + { + uint16_t currentOffset = (offset + readBytes); + uint16_t blockAddr = currentOffset / 4; + // bytes still to be read + uint32_t remainingBytes = length - readBytes; + // bytes to read in current block + uint8_t bytesInBlock = 4 - (currentOffset % 4); + bytesInBlock = bytesInBlock > remainingBytes ? + remainingBytes : bytesInBlock; + err = rfalSt25tbPollerReadBlock(blockAddr, + (rfalSt25tbBlock*)rxBuf); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + memcpy(buffer + readBytes, &rxBuf[currentOffset % 4], + bytesInBlock); + readBytes += bytesInBlock; + } + } else if (Current->type == BSP_NFCTAG_NFCB) { + uint8_t rxBuf[RFAL_ISODEP_DEFAULT_FSC + + RFAL_ISODEP_PROLOGUE_SIZE]; + uint16_t rxBufLen = 0xF0; + uint8_t err; + // read bytes + uint16_t rxLen = rxBufLen; + + uint16_t readBytes = 0; + uint16_t currentOffset = offset; + uint16_t currentLength = length; + while (currentLength > 0) + { + t4tReadBinary[2] = (currentOffset) >> 8; + t4tReadBinary[3] = (currentOffset) & 0xFF; + t4tReadBinary[4] = + (currentLength) > rxBufLen ? + rxBufLen : + (currentLength); + + err = t4tSendCommand(t4tReadBinary, + sizeof(t4tReadBinary), + (rfalIsoDepBufFormat*)&rxBuf, &rxLen); + if (rxLen > 2) + { + rxLen -= 2; // status bytes + if (rxLen > currentLength) + rxLen = currentLength; + memcpy(buffer + readBytes, + &((rfalIsoDepBufFormat*)rxBuf)->inf[0], + rxLen); + } else { + rxLen = 0; + } + if ((err != ERR_NONE) || (rxLen == 0)) + { + return NFCTAG_ERROR; + } else { + currentOffset += rxLen; + currentLength -= rxLen; + readBytes += rxLen; + } + } + } + return NFCTAG_OK; +} + +/* NFCB Tag write data method */ +static uint8_t BSP_NFCTAG_WriteData_NfcB(uint8_t *buffer, uint32_t offset, + uint32_t length) +{ + uint8_t rxBuf[0xFF]; + uint16_t rxLen = 0xF0; + uint8_t status = 0xFF; + uint16_t currentOffset = offset; + uint16_t lastOffset = offset + length; + uint16_t nbBytesToWrite = length; + uint8_t cmd[256 + 5 + 10]; + uint8_t nbBytesWritten = 0; + + while (currentOffset < lastOffset) + { + switch (Current->type) + { + case BSP_NFCTAG_ST25TB: + { + /* Manage offset and length for block based memories */ + rfalSt25tbBlock block; + uint8_t blockInternalOffset = currentOffset % 4; + uint8_t blockInternalLength = 4 - (currentOffset % 4); + blockInternalLength = + blockInternalLength > nbBytesToWrite ? + nbBytesToWrite : + blockInternalLength; + + if ((blockInternalOffset) || (blockInternalLength % 4)) + { + // 4 bytes block + status = rfalSt25tbPollerReadBlock( + currentOffset / 4, &block); + if (status != ERR_NONE) + { + return NFCTAG_ERROR; + } + + memcpy(&block[blockInternalOffset], buffer, + blockInternalLength); + buffer += blockInternalLength; + nbBytesWritten = blockInternalLength; + + } else { + memcpy(&block, buffer, 4); + buffer += 4; + nbBytesWritten = 4; + } + + status = rfalSt25tbPollerWriteBlock(currentOffset / 4, + (const rfalSt25tbBlock*)&block); + + if (status != ERR_NONE) + return NFCTAG_ERROR; + currentOffset += nbBytesWritten; + } + break; + case BSP_NFCTAG_NFCB: + memcpy(cmd, t4tWriteData, sizeof(t4tWriteData)); + cmd[2] = offset >> 8; + cmd[3] = offset & 0xFF; + cmd[4] = length; + memcpy(&cmd[5], buffer, length); + status = t4tSendCommand(cmd, + sizeof(t4tWriteData) + length, + (rfalIsoDepBufFormat*)&rxBuf, &rxLen); + currentOffset += length; + break; + } + } + + if (status == ERR_NONE) + return NFCTAG_OK; + else + return NFCTAG_ERROR; + +} + +/* NFCB Api */ +static BSP_NFCTAG_Protocol_t apiNfcB = { + .activate = &BSP_NFCTAG_Activate_NfcB, + .read_data = &BSP_NFCTAG_ReadData_NfcB, + .write_data = &BSP_NFCTAG_WriteData_NfcB +}; + +/****************** NFCF *****************************/ +/* NFCF Tag Select */ +static uint8_t BSP_NFCTAG_Activate_NfcF(void) +{ + rfalFieldOff(); /* Turns the Field On and starts GT timer */ + HAL_Delay(500); + rfalFieldOnAndStartGT(); /* Turns the Field On and starts GT timer */ + rfalNfcfPollerInitialize(RFAL_BR_212); + + uint8_t testBuf[32]; + // to do: add a check for NDEF support + if (CurrentProtocol->read_data(testBuf, 0, 16) != ERR_NONE) + Current->NdefSupport = 0; + else + Current->NdefSupport = 1; + + return NFCTAG_OK; +} + +/* NFCF read data method */ +static uint8_t BSP_NFCTAG_ReadData_NfcF(uint8_t *buffer, uint32_t offset, + uint32_t length) +{ + uint8_t err; + uint8_t txRxBuf[0xFF]; + uint16_t rxBufLen = 0xF0; + // read bytes + uint16_t rxLen = rxBufLen; + uint16_t firstBlock = (offset / 16); + uint16_t lastBlock = (length + offset - 1) / 16; + uint16_t blockNumber = lastBlock - firstBlock + 1; + memset(txRxBuf, 0, rxBufLen); + + /* To perform presence check, on this example a T3T Check/Read command is used */ + memcpy(&t3tCheckReq[1], Current->dev.nfcf.sensfRes.NFCID2, + RFAL_NFCF_NFCID2_LEN); /* Assign device's NFCID for Check command */ + t3tCheckReq[12] = blockNumber; + memcpy(txRxBuf, t3tCheckReq, sizeof(t3tCheckReq)); + int i = 0; + int blockId; + for (blockId = firstBlock; blockId <= lastBlock; blockId++) + { + txRxBuf[13 + i * 2] = 0x80; + txRxBuf[14 + i * 2] = blockId; + i++; + } + err = rfalTransceiveBlockingTxRx(txRxBuf, + sizeof(t3tCheckReq) + ((blockNumber - 1) * 2), txRxBuf, + rxBufLen, &rxLen, RFAL_TXRX_FLAGS_DEFAULT, + rfalConvMsTo1fc(20)); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + if ((int)((int)rxLen - 13 - (int)(offset % 16)) < (int)length) + { + return NFCTAG_RESPONSE_ERROR; + } + + memcpy(buffer, &txRxBuf[13 + (offset % 16)], length); + return NFCTAG_OK; +} + +/* NFCF write data method */ +static uint8_t BSP_NFCTAG_WriteData_NfcF(uint8_t *buffer, uint32_t offset, + uint32_t length) +{ + uint8_t err; + uint8_t txRxBuf[0xFF]; + uint16_t rxBufLen = 0xF0; + // read bytes + uint16_t rxLen = rxBufLen; + uint16_t firstBlock = (offset / 16); + uint16_t lastBlock = (length + offset - 1) / 16; + + memcpy(&t3tUpdateReq[1], Current->dev.nfcf.sensfRes.NFCID2, + RFAL_NFCF_NFCID2_LEN); /* Assign device's NFCID for Check command */ + + int currentOffset = offset; + int blockId; + for (blockId = firstBlock; blockId <= lastBlock; blockId++) + { + int currentLength = 16 - currentOffset % 16; + currentLength = currentLength > length ? length : currentLength; + + t3tUpdateReq[14] = blockId; + + BSP_NFCTAG_ReadData_NfcF(&t3tUpdateReq[15], blockId * 16, 16); + memcpy(&t3tUpdateReq[15] + currentOffset % 16, buffer, + currentLength); + + err = rfalTransceiveBlockingTxRx(t3tUpdateReq, + sizeof(t3tUpdateReq), txRxBuf, rxBufLen, &rxLen, + RFAL_TXRX_FLAGS_DEFAULT, rfalConvMsTo1fc(20)); + if (err != ERR_NONE) + { + return NFCTAG_ERROR; + } + currentOffset += currentLength; + length -= currentLength; + buffer += currentLength; + } + + return NFCTAG_OK; +} + +/* NFCF Api */ +static BSP_NFCTAG_Protocol_t apiNfcF = { + .activate = &BSP_NFCTAG_Activate_NfcF, + .read_data = &BSP_NFCTAG_ReadData_NfcF, + .write_data = &BSP_NFCTAG_WriteData_NfcF +}; + +/****************** NFCV*****************************/ +/* NFCV RX buffer length in bytes */ +#define BSP_NFCTAG_NFCV_RXBUF_LENGTH 0xFF +/* T5 read single block command */ +static uint8_t t5ExtReadSingleBlock[] = {0x22, 0x30, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +static uint8_t vicExtReadSingleBlock[] = {0x2A, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +/* T5 read multiple block command */ +static uint8_t t5ExtReadMultipleBlock[] = {0x22, 0x33, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +static uint8_t vicExtReadMultipleBlock[] = {0x2A, 0x23, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; +/* T5 default block size */ +static uint16_t t5BlockSize = 4; +static uint8_t isVicinity = 0; +static uint8_t t5MultipleBlockSupport = 0; + +uint8_t BSP_NFCTAG_CheckVicinity() +{ + uint8_t *uid; + if (Current == NULL) + { + return 0; + } + if (Current->type != BSP_NFCTAG_NFCV) + { + return 0; + } + uid = Current->dev.nfcv.InvRes.UID; + if ((uid[7] == 0xE0) && (uid[6] == 0x02) + && + ((uid[5] == 0x44) || (uid[5] == 0x45) + || (uid[5] == 0x46) || + (uid[5] == 0x2C) || (uid[5] == 0x2D) + || (uid[5] == 0x2E) || + (uid[5] == 0x5C) || (uid[5] == 0x5D) + || (uid[5] == 0x5E) || + (uid[5] == 0x4C) || (uid[5] == 0x4D) + || (uid[5] == 0x4E))) + { + return 1; + } + return 0; +} + +/* NFCV tag activation (set block size) */ +static uint8_t BSP_NFCTAG_Activate_NfcV(void) +{ + if (Current->type == BSP_NFCTAG_NFCV) + { + uint8_t status; + uint8_t rxBuf[16]; + + isVicinity = BSP_NFCTAG_CheckVicinity(); + + // let's consider it supports read multiple block + t5MultipleBlockSupport = 1; + + // make sure the field is on + rfalFieldOnAndStartGT(); + + status = rfalNfcvPollerReadSingleBlock(0x22, + Current->dev.nfcv.InvRes.UID, 0, rxBuf, 16, + &t5BlockSize); + + // don't count the status byte + t5BlockSize--; + if (status == ERR_NONE) + { + Current->NdefSupport = 1; + + } else { + // assume block size is 4 + t5BlockSize = 4; + Current->NdefSupport = 0; + } + return NFCTAG_OK; + } else { + Current = NULL; + return NFCTAG_ERROR; + } +} + +/* NFCV Tag read data */ +static uint8_t BSP_NFCTAG_ReadData_NfcV(uint8_t *buffer, uint32_t offset, + uint32_t length) +{ + + int i = 0; + uint16_t nbBytesRead = 0; + uint8_t status = ERR_NONE; + uint8_t *txBuf; + uint16_t txBufLen; + uint8_t rxBuf[BSP_NFCTAG_NFCV_RXBUF_LENGTH]; + + if ((Current->type != BSP_NFCTAG_NFCV) || + (length == 0)) + return NFCTAG_ERROR; + + // make sure the field is on + rfalFieldOnAndStartGT(); + + // stick with readSingleBlock + while (i < length) + { + uint32_t rxLen = length - i; + if (rxLen > 0xF0) + rxLen = 0xF0; + + // first try to use readMultipleBlock + if (t5MultipleBlockSupport) + { + if (isVicinity) + { + // use extended command + vicExtReadMultipleBlock[10] = ((offset + i) + / t5BlockSize) & 0xFF; + vicExtReadMultipleBlock[11] = ((offset + i) + / t5BlockSize) >> 8; + vicExtReadMultipleBlock[12] = ((rxLen - 1) + / t5BlockSize) & 0xFF; + txBuf = vicExtReadMultipleBlock; + txBufLen = sizeof(vicExtReadMultipleBlock); + memcpy(&txBuf[2], Current->dev.nfcv.InvRes.UID, + 8); + nbBytesRead = rxLen; + status = rfalTransceiveBlockingTxRx( + vicExtReadMultipleBlock, + txBufLen, rxBuf, + BSP_NFCTAG_NFCV_RXBUF_LENGTH, + &nbBytesRead, + RFAL_TXRX_FLAGS_DEFAULT, + rfalConvMsTo1fc(20)); + } else if ((offset + length) < 0xFF) + { + nbBytesRead = 0xF0; + status = rfalNfcvPollerReadMultipleBlocks(0x22, + Current->dev.nfcv.InvRes.UID, + (offset + i) / t5BlockSize, + (rxLen - 1) / t5BlockSize, + rxBuf, + BSP_NFCTAG_NFCV_RXBUF_LENGTH, + &nbBytesRead); + } else { + // use extended command + t5ExtReadMultipleBlock[10] = ((offset + i) + / t5BlockSize) & 0xFF; + t5ExtReadMultipleBlock[11] = ((offset + i) + / t5BlockSize) >> 8; + t5ExtReadMultipleBlock[12] = ((rxLen - 1) + / t5BlockSize) & 0xFF; + t5ExtReadMultipleBlock[13] = ((rxLen - 1) + / t5BlockSize) >> 8; + txBuf = t5ExtReadMultipleBlock; + txBufLen = sizeof(t5ExtReadMultipleBlock); + memcpy(&txBuf[2], Current->dev.nfcv.InvRes.UID, + 8); + nbBytesRead = rxLen; + status = rfalTransceiveBlockingTxRx( + t5ExtReadMultipleBlock, + txBufLen, rxBuf, + BSP_NFCTAG_NFCV_RXBUF_LENGTH, + &nbBytesRead, + RFAL_TXRX_FLAGS_DEFAULT, + rfalConvMsTo1fc(20)); + } + } + if ((status != ERR_NONE) || (!t5MultipleBlockSupport)) + { + // looks like read multiple blocks failed! + t5MultipleBlockSupport = 0; + + // try read single block + if (isVicinity) + { + vicExtReadSingleBlock[10] = ((offset + i) + / t5BlockSize) & 0xFF; + vicExtReadSingleBlock[11] = ((offset + i) + / t5BlockSize) >> 8; + txBuf = vicExtReadSingleBlock; + txBufLen = sizeof(vicExtReadSingleBlock); + nbBytesRead = t5BlockSize; + memcpy(&txBuf[2], Current->dev.nfcv.InvRes.UID, + 8); + status = rfalTransceiveBlockingTxRx( + vicExtReadSingleBlock, txBufLen, + rxBuf, + BSP_NFCTAG_NFCV_RXBUF_LENGTH, + &nbBytesRead, + RFAL_TXRX_FLAGS_DEFAULT, + rfalConvMsTo1fc(20)); + } else if (((offset + i) / t5BlockSize) < 0xFF) + { + nbBytesRead = t5BlockSize; + status = rfalNfcvPollerReadSingleBlock(0x22, + Current->dev.nfcv.InvRes.UID, + (offset + i) / t5BlockSize, + rxBuf, + BSP_NFCTAG_NFCV_RXBUF_LENGTH, + &nbBytesRead); + } else { + t5ExtReadSingleBlock[10] = ((offset + i) + / t5BlockSize) & 0xFF; + t5ExtReadSingleBlock[11] = ((offset + i) + / t5BlockSize) >> 8; + txBuf = t5ExtReadSingleBlock; + txBufLen = sizeof(t5ExtReadSingleBlock); + nbBytesRead = t5BlockSize; + memcpy(&txBuf[2], Current->dev.nfcv.InvRes.UID, + 8); + status = rfalTransceiveBlockingTxRx( + t5ExtReadSingleBlock, txBufLen, + rxBuf, + BSP_NFCTAG_NFCV_RXBUF_LENGTH, + &nbBytesRead, + RFAL_TXRX_FLAGS_DEFAULT, + rfalConvMsTo1fc(20)); + } + } + if ((status != ERR_NONE) + || (nbBytesRead < (1 + (offset + i) % 4))) + return NFCTAG_ERROR; + // remove status byte & first bytes if offset is not aligned + nbBytesRead--; + nbBytesRead -= (offset + i) % t5BlockSize; + memcpy(buffer + i, &rxBuf[1 + ((offset + i) % t5BlockSize)], + (nbBytesRead > length) ? length : nbBytesRead); + i += nbBytesRead; + } + return NFCTAG_OK; +} + +/* NFCV Tag write data */ +static uint8_t BSP_NFCTAG_WriteData_NfcV(uint8_t *buffer, uint32_t offset, + uint32_t length) +{ + uint32_t currentOffset = offset; + uint32_t lastOffset = offset + length; + uint8_t status; + uint8_t block[16] = {0}; + uint16_t nbBytesRead = 0; + uint16_t nbBytesToWrite = length; + uint8_t nbBytesWritten = 0; + + while (currentOffset < lastOffset) + { + uint8_t blockInternalOffset = currentOffset % t5BlockSize; + uint8_t blockInternalLength = t5BlockSize + - (currentOffset % t5BlockSize); + blockInternalLength = + blockInternalLength > nbBytesToWrite ? + nbBytesToWrite : + blockInternalLength; + + if ((blockInternalOffset) || (blockInternalLength % 4)) + { + status = rfalNfcvPollerReadSingleBlock(0x22, + Current->dev.nfcv.InvRes.UID, + currentOffset / t5BlockSize, block, 10, + &nbBytesRead); + if ((status != ERR_NONE) || (block[0] != 0)) + { + return NFCTAG_ERROR; + } + // remove first byte (tag status) + memmove(block, &block[1], t5BlockSize); + memcpy(&block[blockInternalOffset], buffer, + blockInternalLength); + buffer += blockInternalLength; + nbBytesWritten = blockInternalLength; + + } else { + memcpy(block, buffer, t5BlockSize); + buffer += t5BlockSize; + nbBytesWritten = t5BlockSize; + } + + status = rfalNfcvPollerWriteSingleBlock(0x22, + Current->dev.nfcv.InvRes.UID, + currentOffset / t5BlockSize, block, + t5BlockSize); + if (status != ERR_NONE) + { + return NFCTAG_ERROR; + } + currentOffset += nbBytesWritten; + } + return NFCTAG_OK; +} + +/* NFCV Api */ +static BSP_NFCTAG_Protocol_t apiNfcV = { + .activate = &BSP_NFCTAG_Activate_NfcV, + .read_data = &BSP_NFCTAG_ReadData_NfcV, + .write_data = &BSP_NFCTAG_WriteData_NfcV +}; + +/******************************* Common API ********************************/ +/** + * @brief Generic Tag activation method + * Perform required actions depending on the current selected protocol. + * E.g.: Run select command, get block size,... + * @param device the device to run activation on. + * @returns status, 0 is a success, other values are errors. + */ +uint8_t BSP_NFCTAG_Activate(BSP_NFCTAG_Device_t *device) +{ + // reset Current tag under operation + Current = NULL; + // select the protocol + switch (device->type) + { + case BSP_NFCTAG_NFCA: + CurrentProtocol = &apiNfcA; + break; + case BSP_NFCTAG_NFCB: + case BSP_NFCTAG_ST25TB: + CurrentProtocol = &apiNfcB; + break; + case BSP_NFCTAG_NFCF: + CurrentProtocol = &apiNfcF; + break; + case BSP_NFCTAG_NFCV: + CurrentProtocol = &apiNfcV; + break; + default: + CurrentProtocol = NULL; + return NFCTAG_ERROR; + } + + // set current operating tag with provided instance + Current = device; + + if ((CurrentProtocol != NULL) && (CurrentProtocol->activate != NULL)) + return CurrentProtocol->activate(); + else + return NFCTAG_ERROR; + +} + +/** + * @brief Generic Tag read method + * Perform required actions to read data from the previously activated tag. + * @param buffer Pointer on the buffer to be used to store the read data. + * @param offset Address of the tag to be read. + * @param length Number of bytes to read. + * @returns status, 0 is a success, other values are errors. + */ +uint8_t BSP_NFCTAG_ReadData(uint8_t *buffer, uint32_t offset, uint32_t length) +{ + if ((CurrentProtocol != NULL) && (CurrentProtocol->read_data != NULL)) + return CurrentProtocol->read_data(buffer, offset, length); + else + return NFCTAG_ERROR; +} + +/** + * @brief Generic Tag write method + * Perform required actions to write data to the previously activated tag. + * @param buffer Pointer on the buffer with data to write. + * @param offset Address of the tag to be written. + * @param length Number of bytes to write. + * @returns status, 0 is a success, other values are errors. + */ +uint8_t BSP_NFCTAG_WriteData(uint8_t *buffer, uint32_t offset, uint32_t length) +{ + if ((CurrentProtocol != NULL) && (CurrentProtocol->write_data != NULL)) + return CurrentProtocol->write_data(buffer, offset, length); + else + return NFCTAG_ERROR; +} + +/** + * @brief Generic method to get the tag size, in bytes + * Perform required actions to get tag size of the previously activated tag. + * @returns size of the tag in bytes + * @warning Not yest implemented - always return 512 + * @todo implement for each tag type... + */ +uint16_t BSP_NFCTAG_GetByteSize(void) +{ + return 512; +} + diff --git a/src/hydranfc_v2/rfal.mk b/src/hydranfc_v2/rfal.mk new file mode 100644 index 0000000..b23423f --- /dev/null +++ b/src/hydranfc_v2/rfal.mk @@ -0,0 +1,29 @@ +# List of all the HydraNFC v2 RFAL files +HYDRANFC_V2_RFAL_SRC = hydranfc_v2/rfal/src/rfal_analogConfig.c \ + hydranfc_v2/rfal/src/rfal_crc.c \ + hydranfc_v2/rfal/src/rfal_dpo.c \ + hydranfc_v2/rfal/src/rfal_iso15693_2.c \ + hydranfc_v2/rfal/src/rfal_isoDep.c \ + hydranfc_v2/rfal/src/rfal_nfc.c \ + hydranfc_v2/rfal/src/rfal_nfca.c \ + hydranfc_v2/rfal/src/rfal_nfcb.c \ + hydranfc_v2/rfal/src/rfal_nfcDep.c \ + hydranfc_v2/rfal/src/rfal_nfcf.c \ + hydranfc_v2/rfal/src/rfal_nfcv.c \ + hydranfc_v2/rfal/src/rfal_st25tb.c \ + hydranfc_v2/rfal/src/rfal_st25xv.c \ + hydranfc_v2/rfal/src/rfal_t1t.c \ + hydranfc_v2/rfal/src/rfal_t2t.c \ + hydranfc_v2/rfal/src/rfal_t4t.c \ + hydranfc_v2/rfal/src/st25r3916/rfal_rfst25r3916.c \ + hydranfc_v2/rfal/src/st25r3916/st25r3916.c \ + hydranfc_v2/rfal/src/st25r3916/st25r3916_aat.c \ + hydranfc_v2/rfal/src/st25r3916/st25r3916_com.c \ + hydranfc_v2/rfal/src/st25r3916/st25r3916_irq.c \ + hydranfc_v2/rfal/src/st25r3916/st25r3916_led.c + +# Required include directories +HYDRANFC_V2_RFAL_INC = ./hydranfc_v2/rfal/src \ + ./hydranfc_v2/rfal/inc \ + ./hydranfc_v2/rfal/src/st25r3916 + diff --git a/src/hydranfc_v2/rfal/STSW-ST25RFAL002.txt b/src/hydranfc_v2/rfal/STSW-ST25RFAL002.txt new file mode 100644 index 0000000..6c1f7ae --- /dev/null +++ b/src/hydranfc_v2/rfal/STSW-ST25RFAL002.txt @@ -0,0 +1,3 @@ +en.STSW-ST25RFAL002 V2.2.0 / 22-May-2020 https://www.st.com/en/embedded-software/stsw-st25rfal002.html +B.VERNOUX June 2020 src\st25r3916\st25r3916.c fixed ST25R3916_TEST_TMR_TOUT_8FC +B.VERNOUX June 2020 src\st25r3916\rfal_analogConfig.c fixed rfalAnalogConfigInitialize() when RFAL_ANALOG_CONFIG_CUSTOM is defined diff --git a/src/hydranfc_v2/rfal/doc/Release_Notes.html b/src/hydranfc_v2/rfal/doc/Release_Notes.html new file mode 100644 index 0000000..c48e0a6 --- /dev/null +++ b/src/hydranfc_v2/rfal/doc/Release_Notes.html @@ -0,0 +1,354 @@ + + + + + + + + + + + + + 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 Tunning) 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
  • +
  • Aditional 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 inconsitency 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 supression 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/src/hydranfc_v2/rfal/doc/ST25R3916_MisraComplianceReport.html b/src/hydranfc_v2/rfal/doc/ST25R3916_MisraComplianceReport.html new file mode 100644 index 0000000..7076e7c --- /dev/null +++ b/src/hydranfc_v2/rfal/doc/ST25R3916_MisraComplianceReport.html @@ -0,0 +1,8867 @@ + + + + + +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 informations:
  • +
      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 whithin 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/src/hydranfc_v2/rfal/doc/_htmresc/st_logo.png b/src/hydranfc_v2/rfal/doc/_htmresc/st_logo.png new file mode 100644 index 0000000..8b80057 Binary files /dev/null and b/src/hydranfc_v2/rfal/doc/_htmresc/st_logo.png differ diff --git a/src/hydranfc_v2/rfal/doc/rfal.chm b/src/hydranfc_v2/rfal/doc/rfal.chm new file mode 100644 index 0000000..d417709 Binary files /dev/null and b/src/hydranfc_v2/rfal/doc/rfal.chm differ diff --git a/src/hydranfc_v2/rfal/doc/rfal.chw b/src/hydranfc_v2/rfal/doc/rfal.chw new file mode 100644 index 0000000..ef87205 Binary files /dev/null and b/src/hydranfc_v2/rfal/doc/rfal.chw differ diff --git a/src/hydranfc_v2/rfal/inc/rfal_analogConfig.h b/src/hydranfc_v2/rfal/inc/rfal_analogConfig.h new file mode 100644 index 0000000..e10c463 --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_analogConfig.h @@ -0,0 +1,357 @@ + +/****************************************************************************** + * \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 Configuraiton 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/src/hydranfc_v2/rfal/inc/rfal_chip.h b/src/hydranfc_v2/rfal/inc/rfal_chip.h new file mode 100644 index 0000000..82fcf3c --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_chip.h @@ -0,0 +1,296 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/inc/rfal_dpo.h b/src/hydranfc_v2/rfal/inc/rfal_dpo.h new file mode 100644 index 0000000..72819fd --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_dpo.h @@ -0,0 +1,209 @@ + +/****************************************************************************** + * @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 methode 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 methode + * + * 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/src/hydranfc_v2/rfal/inc/rfal_isoDep.h b/src/hydranfc_v2/rfal/inc/rfal_isoDep.h new file mode 100644 index 0000000..370427e --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_isoDep.h @@ -0,0 +1,1017 @@ + +/****************************************************************************** + * \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 bufffer + * \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 + * responce 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), retieves 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/src/hydranfc_v2/rfal/inc/rfal_nfc.h b/src/hydranfc_v2/rfal/inc/rfal_nfc.h new file mode 100644 index 0000000..d8086d2 --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_nfc.h @@ -0,0 +1,415 @@ + +/****************************************************************************** + * \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_START_DISCOVERY) && ((st)= 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; /*!< Compliancy 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 */ +}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 actived + * + * \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 ); + +/*! + ***************************************************************************** + * \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/src/hydranfc_v2/rfal/inc/rfal_nfcDep.h b/src/hydranfc_v2/rfal/inc/rfal_nfcDep.h new file mode 100644 index 0000000..73c7cab --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_nfcDep.h @@ -0,0 +1,788 @@ + +/****************************************************************************** + * \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 Dividor 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 outputed, + * 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/src/hydranfc_v2/rfal/inc/rfal_nfca.h b/src/hydranfc_v2/rfal/inc/rfal_nfca.h new file mode 100644 index 0000000..47fd730 --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_nfca.h @@ -0,0 +1,464 @@ + +/****************************************************************************** + * \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 immidiatly. 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 immidiatly. 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 immidiatly. 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/src/hydranfc_v2/rfal/inc/rfal_nfcb.h b/src/hydranfc_v2/rfal/inc/rfal_nfcb.h new file mode 100644 index 0000000..891b0c0 --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_nfcb.h @@ -0,0 +1,398 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/inc/rfal_nfcf.h b/src/hydranfc_v2/rfal/inc/rfal_nfcf.h new file mode 100644 index 0000000..982ffe6 --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_nfcf.h @@ -0,0 +1,370 @@ + +/****************************************************************************** + * \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/Responce code length */ +#define RFAL_NFCF_CMD_LEN 1U /*!< Command/Responce 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 accoring to T3T 1.0 and JIS X6319-4 and + * sends it to PICC. If sucessfully, 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 accoring 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 outputed, + * 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/src/hydranfc_v2/rfal/inc/rfal_nfcv.h b/src/hydranfc_v2/rfal/inc/rfal_nfcv.h new file mode 100644 index 0000000..c256dbc --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_nfcv.h @@ -0,0 +1,772 @@ + +/****************************************************************************** + * \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_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); + +/*! Callback to be executed after a Transceive */ +typedef void (* rfalPostTxRxCallback)(void); + + +/*******************************************************************************/ +/* 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 ); + +/*! + ***************************************************************************** + * \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 ); + + + +/***************************************************************************** + * 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/src/hydranfc_v2/rfal/inc/rfal_st25tb.h b/src/hydranfc_v2/rfal/inc/rfal_st25tb.h new file mode 100644 index 0000000..d124c07 --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_st25tb.h @@ -0,0 +1,355 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/inc/rfal_st25xv.h b/src/hydranfc_v2/rfal/inc/rfal_st25xv.h new file mode 100644 index 0000000..f169262 --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_st25xv.h @@ -0,0 +1,729 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/inc/rfal_t1t.h b/src/hydranfc_v2/rfal/inc/rfal_t1t.h new file mode 100644 index 0000000..a49d961 --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_t1t.h @@ -0,0 +1,187 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/inc/rfal_t2t.h b/src/hydranfc_v2/rfal/inc/rfal_t2t.h new file mode 100644 index 0000000..bbead9e --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_t2t.h @@ -0,0 +1,153 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/inc/rfal_t4t.h b/src/hydranfc_v2/rfal/inc/rfal_t4t.h new file mode 100644 index 0000000..9d5bec9 --- /dev/null +++ b/src/hydranfc_v2/rfal/inc/rfal_t4t.h @@ -0,0 +1,365 @@ + +/****************************************************************************** + * \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 occurence */ +#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 responce 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 Satus 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/src/hydranfc_v2/rfal/src/rfal_analogConfig.c b/src/hydranfc_v2/rfal/src/rfal_analogConfig.c new file mode 100644 index 0000000..0113dad --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_analogConfig.c @@ -0,0 +1,481 @@ + +/****************************************************************************** + * \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 + * \author B.VERNOUX fixed rfalAnalogConfigInitialize() when RFAL_ANALOG_CONFIG_CUSTOM is defined + * + * \brief Funcitons 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 = 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<
© 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/src/hydranfc_v2/rfal/src/rfal_crc.h b/src/hydranfc_v2/rfal/src/rfal_crc.h new file mode 100644 index 0000000..5a71cf6 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_crc.h @@ -0,0 +1,75 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_dpo.c b/src/hydranfc_v2/rfal/src/rfal_dpo.c new file mode 100644 index 0000000..07f26ed --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_dpo.c @@ -0,0 +1,259 @@ + +/****************************************************************************** + * @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/src/hydranfc_v2/rfal/src/rfal_iso15693_2.c b/src/hydranfc_v2/rfal/src/rfal_iso15693_2.c new file mode 100644 index 0000000..2c1daa4 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_iso15693_2.c @@ -0,0 +1,533 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_iso15693_2.h b/src/hydranfc_v2/rfal/src/rfal_iso15693_2.h new file mode 100644 index 0000000..5b4acbb --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_iso15693_2.h @@ -0,0 +1,202 @@ + +/****************************************************************************** + * \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 occured, data uncorrect + * \return ERR_CRC : CRC error, data uncorrect + * \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/src/hydranfc_v2/rfal/src/rfal_isoDep.c b/src/hydranfc_v2/rfal/src/rfal_isoDep.c new file mode 100644 index 0000000..28eee39 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_isoDep.c @@ -0,0 +1,2801 @@ + +/****************************************************************************** + * \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(PARAMETRS) 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 /* Unexcpected 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 -> toogle 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_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< 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 whithin 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<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; + + /* 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/src/hydranfc_v2/rfal/src/rfal_nfc.c b/src/hydranfc_v2/rfal/src/rfal_nfc.c new file mode 100644 index 0000000..40a335c --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_nfc.c @@ -0,0 +1,1926 @@ +/** + ****************************************************************************** + * + * 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; /* Decices 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 opration 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 ) +{ + 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)); + 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, RFAL_TXRX_FLAGS_DEFAULT, 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; + + 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 succesfully 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 succesfull 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; + + /* Supress 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; + + /* Supress 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 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 perfomed (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 ) ); + } + + #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; + + /* Supress 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/src/hydranfc_v2/rfal/src/rfal_nfcDep.c b/src/hydranfc_v2/rfal/src/rfal_nfcDep.c new file mode 100644 index 0000000..fe098a3 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_nfcDep.c @@ -0,0 +1,2714 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_nfca.c b/src/hydranfc_v2/rfal/src/rfal_nfca.c new file mode 100644 index 0000000..3e99f64 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_nfca.c @@ -0,0 +1,853 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_nfcb.c b/src/hydranfc_v2/rfal/src/rfal_nfcb.c new file mode 100644 index 0000000..21d48b7 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_nfcb.c @@ -0,0 +1,504 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_nfcf.c b/src/hydranfc_v2/rfal/src/rfal_nfcf.c new file mode 100644 index 0000000..f35e16d --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_nfcf.c @@ -0,0 +1,546 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_nfcv.c b/src/hydranfc_v2/rfal/src/rfal_nfcv.c new file mode 100644 index 0000000..a3177a7 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_nfcv.c @@ -0,0 +1,870 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_st25tb.c b/src/hydranfc_v2/rfal/src/rfal_st25tb.c new file mode 100644 index 0000000..7bc7524 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_st25tb.c @@ -0,0 +1,561 @@ + +/****************************************************************************** + * \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 commiting 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/src/hydranfc_v2/rfal/src/rfal_st25xv.c b/src/hydranfc_v2/rfal/src/rfal_st25xv.c new file mode 100644 index 0000000..c4ec943 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_st25xv.c @@ -0,0 +1,529 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_t1t.c b/src/hydranfc_v2/rfal/src/rfal_t1t.c new file mode 100644 index 0000000..0b036f0 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_t1t.c @@ -0,0 +1,220 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_t2t.c b/src/hydranfc_v2/rfal/src/rfal_t2t.c new file mode 100644 index 0000000..119d1a9 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_t2t.c @@ -0,0 +1,242 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/rfal_t4t.c b/src/hydranfc_v2/rfal/src/rfal_t4t.c new file mode 100644 index 0000000..f322742 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/rfal_t4t.c @@ -0,0 +1,398 @@ + +/****************************************************************************** + * \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 ) + { + /* Extented field coding not supported */ + return ERR_PARAM; + } + + /* Check whether requested Lc fits */ + 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/src/hydranfc_v2/rfal/src/st25r3916/rfal_analogConfigTbl.h b/src/hydranfc_v2/rfal/src/st25r3916/rfal_analogConfigTbl.h new file mode 100644 index 0000000..ceb9321 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/rfal_analogConfigTbl.h @@ -0,0 +1,594 @@ + +/****************************************************************************** + * \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<
© 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/src/hydranfc_v2/rfal/src/st25r3916/rfal_features.h b/src/hydranfc_v2/rfal/src/st25r3916/rfal_features.h new file mode 100644 index 0000000..50aa595 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/rfal_features.h @@ -0,0 +1,113 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/st25r3916/rfal_rfst25r3916.c b/src/hydranfc_v2/rfal/src/st25r3916/rfal_rfst25r3916.c new file mode 100644 index 0000000..a2ddb28 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/rfal_rfst25r3916.c @@ -0,0 +1,4744 @@ + +/****************************************************************************** + * \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 SWITCHS + ****************************************************************************** + */ + +#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 */ +} 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 occours */ + 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 interoprability + */ +#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)))<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(); +} + + +/*******************************************************************************/ +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; +} + + +/*******************************************************************************/ +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(); + } + /*******************************************************************************/ + +} + + +/*******************************************************************************/ +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(); + } + /*******************************************************************************/ + + + 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 Collsion 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; + + /* Supress 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 reseted 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 speficic 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 speficic 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 Oscilator 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 reseted 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; + + 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 spliting 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; + + return ERR_NONE; +} + + +/*******************************************************************************/ +ReturnCode rfalLowPowerModeStop( void ) +{ + ReturnCode ret; + + /* 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/src/hydranfc_v2/rfal/src/st25r3916/st25r3916.c b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916.c new file mode 100644 index 0000000..4d5b477 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916.c @@ -0,0 +1,796 @@ + +/****************************************************************************** + * \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 + * \author B.VERNOUX fixed ST25R3916_TEST_TMR_TOUT_8FC + * + * \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 <= Bug exceed max value 65536 (shall be set to 20ms) */ +#define ST25R3916_TEST_TMR_TOUT_8FC (ST25R3916_TEST_TMR_TOUT * 1695U) /*!< Timeout in 8/fc <= Fix BVE 18 June 2020 */ + +/* +****************************************************************************** +* 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 ); + + /* Disabe 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 wether 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<> 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/src/hydranfc_v2/rfal/src/st25r3916/st25r3916.h b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916.h new file mode 100644 index 0000000..a9a7c95 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916.h @@ -0,0 +1,609 @@ + +/****************************************************************************** + * \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 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 */ + + +#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 arround 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/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_aat.c b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_aat.c new file mode 100644 index 0000000..f99d0e0 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_aat.c @@ -0,0 +1,329 @@ +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_aat.h b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_aat.h new file mode 100644 index 0000000..32a5ab7 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_aat.h @@ -0,0 +1,113 @@ +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_com.c b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_com.c new file mode 100644 index 0000000..31f08ce --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_com.c @@ -0,0 +1,649 @@ + +/****************************************************************************** + * \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 ) +{ + if( !(( (int16_t)reg >= (int16_t)ST25R3916_REG_IO_CONF1) && (reg <= (ST25R3916_SPACE_B | ST25R3916_REG_IC_IDENTITY)) )) + { + return false; + } + return true; +} + diff --git a/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_com.h b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_com.h new file mode 100644 index 0000000..d7543ca --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_com.h @@ -0,0 +1,1330 @@ + +/****************************************************************************** + * \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 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 + * @{ + * + */ + + +#ifndef ST25R3916_COM_H +#define ST25R3916_COM_H + +/* +****************************************************************************** +* INCLUDES +****************************************************************************** +*/ +#include "platform.h" +#include "st_errno.h" + +/* +****************************************************************************** +* 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_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 */ +#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 */ + +/* 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 */ + + /* 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 */ +#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 */ + +/* 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 */ +#define ST25R3916_REG_CORR_CONF1 (ST25R3916_SPACE_B|0x0CU) /*!< RW Correlator configuration register 1 */ +#define ST25R3916_REG_CORR_CONF2 (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 */ + +/* 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 */ + +/* 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 */ + +/* 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 */ +#define ST25R3916_REG_TX_DRIVER_TIMING (ST25R3916_SPACE_B|0x29U) /*!< RW TX driver timing Register */ +#define ST25R3916_REG_RES_AM_MOD (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 */ + +/* External Field Detector Threshold Registers */ +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV 0x2AU /*!< RW External Field Detector Activation Threshold Reg */ +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV 0x2BU /*!< RW External Field Detector Deactivation Threshold Reg*/ + +/* 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 */ + +/* 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 */ +#define ST25R3916_REG_OVERSHOOT_CONF1 (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 */ +#define ST25R3916_REG_UNDERSHOOT_CONF1 (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 */ + +/* 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 */ +#define ST25R3916_REG_AMPLITUDE_MEASURE_REF 0x34U /*!< RW Amplitude Measurement Reference Register */ +#define ST25R3916_REG_AMPLITUDE_MEASURE_AA_RESULT 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 */ +#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 */ +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF 0x3BU /*!< RW Capacitance Measurement Configuration Register */ +#define ST25R3916_REG_CAPACITANCE_MEASURE_REF 0x3CU /*!< RW Capacitance Measurement Reference Register */ +#define ST25R3916_REG_CAPACITANCE_MEASURE_AA_RESULT 0x3DU /*!< R Capacitance Measurement Auto Averaging Display Reg*/ +#define ST25R3916_REG_CAPACITANCE_MEASURE_RESULT 0x3EU /*!< R Capacitance Measurement Display Register */ + +/* IC identity */ +#define ST25R3916_REG_IC_IDENTITY 0x3FU /*!< R Chip Id: 0 for old silicon, v2 silicon: 0x09 */ + + +/*! Register bit definitions \cond DOXYGEN_SUPRESS */ + +#define ST25R3916_REG_IO_CONF1_single (1U<<7) +#define ST25R3916_REG_IO_CONF1_rfo2 (1U<<6) +#define ST25R3916_REG_IO_CONF1_i2c_thd1 (1U<<5) +#define ST25R3916_REG_IO_CONF1_i2c_thd0 (1U<<4) +#define ST25R3916_REG_IO_CONF1_i2c_thd_mask (3U<<4) +#define ST25R3916_REG_IO_CONF1_i2c_thd_shift (4U) +#define ST25R3916_REG_IO_CONF1_rfu (1U<<3) +#define ST25R3916_REG_IO_CONF1_out_cl1 (1U<<2) +#define ST25R3916_REG_IO_CONF1_out_cl0 (1U<<1) +#define ST25R3916_REG_IO_CONF1_out_cl_disabled (3U<<1) +#define ST25R3916_REG_IO_CONF1_out_cl_13_56MHZ (2U<<1) +#define ST25R3916_REG_IO_CONF1_out_cl_4_78MHZ (1U<<1) +#define ST25R3916_REG_IO_CONF1_out_cl_3_39MHZ (0U<<1) +#define ST25R3916_REG_IO_CONF1_out_cl_mask (3U<<1) +#define ST25R3916_REG_IO_CONF1_out_cl_shift (1U) +#define ST25R3916_REG_IO_CONF1_lf_clk_off (1U<<0) +#define ST25R3916_REG_IO_CONF1_lf_clk_off_on (1U<<0) +#define ST25R3916_REG_IO_CONF1_lf_clk_off_off (0U<<0) + +#define ST25R3916_REG_IO_CONF2_sup3V (1U<<7) +#define ST25R3916_REG_IO_CONF2_sup3V_3V (1U<<7) +#define ST25R3916_REG_IO_CONF2_sup3V_5V (0U<<7) +#define ST25R3916_REG_IO_CONF2_vspd_off (1U<<6) +#define ST25R3916_REG_IO_CONF2_aat_en (1U<<5) +#define ST25R3916_REG_IO_CONF2_miso_pd2 (1U<<4) +#define ST25R3916_REG_IO_CONF2_miso_pd1 (1U<<3) +#define ST25R3916_REG_IO_CONF2_io_drv_lvl (1U<<2) +#define ST25R3916_REG_IO_CONF2_slow_up (1U<<0) + +#define ST25R3916_REG_OP_CONTROL_en (1U<<7) +#define ST25R3916_REG_OP_CONTROL_rx_en (1U<<6) +#define ST25R3916_REG_OP_CONTROL_rx_chn (1U<<5) +#define ST25R3916_REG_OP_CONTROL_rx_man (1U<<4) +#define ST25R3916_REG_OP_CONTROL_tx_en (1U<<3) +#define ST25R3916_REG_OP_CONTROL_wu (1U<<2) +#define ST25R3916_REG_OP_CONTROL_en_fd_c1 (1U<<1) +#define ST25R3916_REG_OP_CONTROL_en_fd_c0 (1U<<0) +#define ST25R3916_REG_OP_CONTROL_en_fd_efd_off (0U<<0) +#define ST25R3916_REG_OP_CONTROL_en_fd_manual_efd_ca (1U<<0) +#define ST25R3916_REG_OP_CONTROL_en_fd_manual_efd_pdt (2U<<0) +#define ST25R3916_REG_OP_CONTROL_en_fd_auto_efd (3U<<0) +#define ST25R3916_REG_OP_CONTROL_en_fd_shift (0U) +#define ST25R3916_REG_OP_CONTROL_en_fd_mask (3U<<0) + +#define ST25R3916_REG_MODE_targ (1U<<7) +#define ST25R3916_REG_MODE_targ_targ (1U<<7) +#define ST25R3916_REG_MODE_targ_init (0U<<7) +#define ST25R3916_REG_MODE_om3 (1U<<6) +#define ST25R3916_REG_MODE_om2 (1U<<5) +#define ST25R3916_REG_MODE_om1 (1U<<4) +#define ST25R3916_REG_MODE_om0 (1U<<3) +#define ST25R3916_REG_MODE_om_bpsk_stream (0xfU<<3) +#define ST25R3916_REG_MODE_om_subcarrier_stream (0xeU<<3) +#define ST25R3916_REG_MODE_om_topaz (0x4U<<3) +#define ST25R3916_REG_MODE_om_felica (0x3U<<3) +#define ST25R3916_REG_MODE_om_iso14443b (0x2U<<3) +#define ST25R3916_REG_MODE_om_iso14443a (0x1U<<3) +#define ST25R3916_REG_MODE_om_targ_nfca (0x1U<<3) +#define ST25R3916_REG_MODE_om_targ_nfcb (0x2U<<3) +#define ST25R3916_REG_MODE_om_targ_nfcf (0x4U<<3) +#define ST25R3916_REG_MODE_om_targ_nfcip (0x7U<<3) +#define ST25R3916_REG_MODE_om_nfc (0x0U<<3) +#define ST25R3916_REG_MODE_om_mask (0xfU<<3) +#define ST25R3916_REG_MODE_om_shift (3U) +#define ST25R3916_REG_MODE_tr_am (1U<<2) +#define ST25R3916_REG_MODE_tr_am_ook (0U<<2) +#define ST25R3916_REG_MODE_tr_am_am (1U<<2) +#define ST25R3916_REG_MODE_nfc_ar1 (1U<<1) +#define ST25R3916_REG_MODE_nfc_ar0 (1U<<0) +#define ST25R3916_REG_MODE_nfc_ar_off (0U<<0) +#define ST25R3916_REG_MODE_nfc_ar_auto_rx (1U<<0) +#define ST25R3916_REG_MODE_nfc_ar_eof (2U<<0) +#define ST25R3916_REG_MODE_nfc_ar_rfu (3U<<0) +#define ST25R3916_REG_MODE_nfc_ar_mask (3U<<0) +#define ST25R3916_REG_MODE_nfc_ar_shift (0U) + +#define ST25R3916_REG_BIT_RATE_txrate_106 (0x0U<<4) +#define ST25R3916_REG_BIT_RATE_txrate_212 (0x1U<<4) +#define ST25R3916_REG_BIT_RATE_txrate_424 (0x2U<<4) +#define ST25R3916_REG_BIT_RATE_txrate_848 (0x3U<<4) +#define ST25R3916_REG_BIT_RATE_txrate_mask (0x3U<<4) +#define ST25R3916_REG_BIT_RATE_txrate_shift (4U) +#define ST25R3916_REG_BIT_RATE_rxrate_106 (0x0U<<0) +#define ST25R3916_REG_BIT_RATE_rxrate_212 (0x1U<<0) +#define ST25R3916_REG_BIT_RATE_rxrate_424 (0x2U<<0) +#define ST25R3916_REG_BIT_RATE_rxrate_848 (0x3U<<0) +#define ST25R3916_REG_BIT_RATE_rxrate_mask (0x3U<<0) +#define ST25R3916_REG_BIT_RATE_rxrate_shift (0U) + +#define ST25R3916_REG_ISO14443A_NFC_no_tx_par (1U<<7) +#define ST25R3916_REG_ISO14443A_NFC_no_tx_par_off (0U<<7) +#define ST25R3916_REG_ISO14443A_NFC_no_rx_par (1U<<6) +#define ST25R3916_REG_ISO14443A_NFC_no_rx_par_off (0U<<6) +#define ST25R3916_REG_ISO14443A_NFC_nfc_f0 (1U<<5) +#define ST25R3916_REG_ISO14443A_NFC_nfc_f0_off (0U<<5) +#define ST25R3916_REG_ISO14443A_NFC_p_len3 (1U<<4) +#define ST25R3916_REG_ISO14443A_NFC_p_len2 (1U<<3) +#define ST25R3916_REG_ISO14443A_NFC_p_len1 (1U<<2) +#define ST25R3916_REG_ISO14443A_NFC_p_len0 (1U<<1) +#define ST25R3916_REG_ISO14443A_NFC_p_len_mask (0xfU<<1) +#define ST25R3916_REG_ISO14443A_NFC_p_len_shift (1U) +#define ST25R3916_REG_ISO14443A_NFC_antcl (1U<<0) + +#define ST25R3916_REG_EMD_SUP_CONF_emd_emv (1U<<7) +#define ST25R3916_REG_EMD_SUP_CONF_emd_emv_on (1U<<7) +#define ST25R3916_REG_EMD_SUP_CONF_emd_emv_off (0U<<7) +#define ST25R3916_REG_EMD_SUP_CONF_rx_start_emv (1U<<6) +#define ST25R3916_REG_EMD_SUP_CONF_rx_start_emv_on (1U<<6) +#define ST25R3916_REG_EMD_SUP_CONF_rx_start_emv_off (0U<<6) +#define ST25R3916_REG_EMD_SUP_CONF_rfu1 (1U<<5) +#define ST25R3916_REG_EMD_SUP_CONF_rfu0 (1U<<4) +#define ST25R3916_REG_EMD_SUP_CONF_emd_thld3 (1U<<3) +#define ST25R3916_REG_EMD_SUP_CONF_emd_thld2 (1U<<2) +#define ST25R3916_REG_EMD_SUP_CONF_emd_thld1 (1U<<1) +#define ST25R3916_REG_EMD_SUP_CONF_emd_thld0 (1U<<0) +#define ST25R3916_REG_EMD_SUP_CONF_emd_thld_mask (0xfU<<0) +#define ST25R3916_REG_EMD_SUP_CONF_emd_thld_shift (0U) + +#define ST25R3916_REG_SUBC_START_TIME_rfu2 (1U<<7) +#define ST25R3916_REG_SUBC_START_TIME_rfu1 (1U<<6) +#define ST25R3916_REG_SUBC_START_TIME_rfu0 (1U<<5) +#define ST25R3916_REG_SUBC_START_TIME_sst4 (1U<<4) +#define ST25R3916_REG_SUBC_START_TIME_sst3 (1U<<3) +#define ST25R3916_REG_SUBC_START_TIME_sst2 (1U<<2) +#define ST25R3916_REG_SUBC_START_TIME_sst1 (1U<<1) +#define ST25R3916_REG_SUBC_START_TIME_sst0 (1U<<0) +#define ST25R3916_REG_SUBC_START_TIME_sst_mask (0x1fU<<0) +#define ST25R3916_REG_SUBC_START_TIME_sst_shift (0U) + +#define ST25R3916_REG_ISO14443B_1_egt2 (1U<<7) +#define ST25R3916_REG_ISO14443B_1_egt1 (1U<<6) +#define ST25R3916_REG_ISO14443B_1_egt0 (1U<<5) +#define ST25R3916_REG_ISO14443B_1_egt_shift (5U) +#define ST25R3916_REG_ISO14443B_1_egt_mask (7U<<5) +#define ST25R3916_REG_ISO14443B_1_sof_1 (1U<<3) +#define ST25R3916_REG_ISO14443B_1_sof_1_3etu (1U<<3) +#define ST25R3916_REG_ISO14443B_1_sof_1_2etu (0U<<3) +#define ST25R3916_REG_ISO14443B_1_sof_0 (1U<<4) +#define ST25R3916_REG_ISO14443B_1_sof_0_11etu (1U<<4) +#define ST25R3916_REG_ISO14443B_1_sof_0_10etu (0U<<4) +#define ST25R3916_REG_ISO14443B_1_sof_mask (3U<<3) +#define ST25R3916_REG_ISO14443B_1_eof (1U<<2) +#define ST25R3916_REG_ISO14443B_1_eof_11etu (1U<<2) +#define ST25R3916_REG_ISO14443B_1_eof_10etu (0U<<2) +#define ST25R3916_REG_ISO14443B_1_half (1U<<1) +#define ST25R3916_REG_ISO14443B_1_rx_st_om (1U<<0) + +#define ST25R3916_REG_ISO14443B_2_tr1_1 (1U<<7) +#define ST25R3916_REG_ISO14443B_2_tr1_0 (1U<<6) +#define ST25R3916_REG_ISO14443B_2_tr1_64fs32fs (1U<<6) +#define ST25R3916_REG_ISO14443B_2_tr1_80fs80fs (0U<<6) +#define ST25R3916_REG_ISO14443B_2_tr1_mask (3U<<6) +#define ST25R3916_REG_ISO14443B_2_tr1_shift (6U) +#define ST25R3916_REG_ISO14443B_2_no_sof (1U<<5) +#define ST25R3916_REG_ISO14443B_2_no_eof (1U<<4) +#define ST25R3916_REG_ISO14443B_rfu1 (1U<<3) +#define ST25R3916_REG_ISO14443B_rfu0 (1U<<2) +#define ST25R3916_REG_ISO14443B_2_f_p1 (1U<<1) +#define ST25R3916_REG_ISO14443B_2_f_p0 (1U<<0) +#define ST25R3916_REG_ISO14443B_2_f_p_96 (3U<<0) +#define ST25R3916_REG_ISO14443B_2_f_p_80 (2U<<0) +#define ST25R3916_REG_ISO14443B_2_f_p_64 (1U<<0) +#define ST25R3916_REG_ISO14443B_2_f_p_48 (0U<<0) +#define ST25R3916_REG_ISO14443B_2_f_p_mask (3U<<0) +#define ST25R3916_REG_ISO14443B_2_f_p_shift (0U) + +#define ST25R3916_REG_PASSIVE_TARGET_fdel_3 (1U<<7) +#define ST25R3916_REG_PASSIVE_TARGET_fdel_2 (1U<<6) +#define ST25R3916_REG_PASSIVE_TARGET_fdel_1 (1U<<5) +#define ST25R3916_REG_PASSIVE_TARGET_fdel_0 (1U<<4) +#define ST25R3916_REG_PASSIVE_TARGET_fdel_mask (0xfU<<4) +#define ST25R3916_REG_PASSIVE_TARGET_fdel_shift (4U) +#define ST25R3916_REG_PASSIVE_TARGET_d_ac_ap2p (1U<<3) +#define ST25R3916_REG_PASSIVE_TARGET_d_212_424_1r (1U<<2) +#define ST25R3916_REG_PASSIVE_TARGET_rfu (1U<<1) +#define ST25R3916_REG_PASSIVE_TARGET_d_106_ac_a (1U<<0) + +#define ST25R3916_REG_STREAM_MODE_rfu (1U<<7) +#define ST25R3916_REG_STREAM_MODE_scf1 (1U<<6) +#define ST25R3916_REG_STREAM_MODE_scf0 (1U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_sc212 (0U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_sc424 (1U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_sc848 (2U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_sc1695 (3U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_bpsk848 (0U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_bpsk1695 (1U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_bpsk3390 (2U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_bpsk106 (3U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_mask (3U<<5) +#define ST25R3916_REG_STREAM_MODE_scf_shift (5U) +#define ST25R3916_REG_STREAM_MODE_scp1 (1U<<4) +#define ST25R3916_REG_STREAM_MODE_scp0 (1U<<3) +#define ST25R3916_REG_STREAM_MODE_scp_1pulse (0U<<3) +#define ST25R3916_REG_STREAM_MODE_scp_2pulses (1U<<3) +#define ST25R3916_REG_STREAM_MODE_scp_4pulses (2U<<3) +#define ST25R3916_REG_STREAM_MODE_scp_8pulses (3U<<3) +#define ST25R3916_REG_STREAM_MODE_scp_mask (3U<<3) +#define ST25R3916_REG_STREAM_MODE_scp_shift (3U) +#define ST25R3916_REG_STREAM_MODE_stx2 (1U<<2) +#define ST25R3916_REG_STREAM_MODE_stx1 (1U<<1) +#define ST25R3916_REG_STREAM_MODE_stx0 (1U<<0) +#define ST25R3916_REG_STREAM_MODE_stx_106 (0U<<0) +#define ST25R3916_REG_STREAM_MODE_stx_212 (1U<<0) +#define ST25R3916_REG_STREAM_MODE_stx_424 (2U<<0) +#define ST25R3916_REG_STREAM_MODE_stx_848 (3U<<0) +#define ST25R3916_REG_STREAM_MODE_stx_mask (7U<<0) +#define ST25R3916_REG_STREAM_MODE_stx_shift (0U) + +#define ST25R3916_REG_AUX_no_crc_rx (1U<<7) +#define ST25R3916_REG_AUX_rfu (1U<<6) +#define ST25R3916_REG_AUX_nfc_id1 (1U<<5) +#define ST25R3916_REG_AUX_nfc_id0 (1U<<4) +#define ST25R3916_REG_AUX_nfc_id_7bytes (1U<<4) +#define ST25R3916_REG_AUX_nfc_id_4bytes (0U<<4) +#define ST25R3916_REG_AUX_nfc_id_mask (3U<<4) +#define ST25R3916_REG_AUX_nfc_id_shift (4U) +#define ST25R3916_REG_AUX_mfaz_cl90 (1U<<3) +#define ST25R3916_REG_AUX_dis_corr (1U<<2) +#define ST25R3916_REG_AUX_dis_corr_coherent (1U<<2) +#define ST25R3916_REG_AUX_dis_corr_correlator (0U<<2) +#define ST25R3916_REG_AUX_nfc_n1 (1U<<1) +#define ST25R3916_REG_AUX_nfc_n0 (1U<<0) +#define ST25R3916_REG_AUX_nfc_n_mask (3U<<0) +#define ST25R3916_REG_AUX_nfc_n_shift (0U) + +#define ST25R3916_REG_RX_CONF1_ch_sel (1U<<7) +#define ST25R3916_REG_RX_CONF1_ch_sel_PM (1U<<7) +#define ST25R3916_REG_RX_CONF1_ch_sel_AM (0U<<7) +#define ST25R3916_REG_RX_CONF1_lp2 (1U<<6) +#define ST25R3916_REG_RX_CONF1_lp1 (1U<<5) +#define ST25R3916_REG_RX_CONF1_lp0 (1U<<4) +#define ST25R3916_REG_RX_CONF1_lp_1200khz (0U<<4) +#define ST25R3916_REG_RX_CONF1_lp_600khz (1U<<4) +#define ST25R3916_REG_RX_CONF1_lp_300khz (2U<<4) +#define ST25R3916_REG_RX_CONF1_lp_2000khz (4U<<4) +#define ST25R3916_REG_RX_CONF1_lp_7000khz (5U<<4) +#define ST25R3916_REG_RX_CONF1_lp_mask (7U<<4) +#define ST25R3916_REG_RX_CONF1_lp_shift (4U) +#define ST25R3916_REG_RX_CONF1_z600k (1U<<3) +#define ST25R3916_REG_RX_CONF1_h200 (1U<<2) +#define ST25R3916_REG_RX_CONF1_h80 (1U<<1) +#define ST25R3916_REG_RX_CONF1_z12k (1U<<0) +#define ST25R3916_REG_RX_CONF1_hz_60_400khz (0U<<0) +#define ST25R3916_REG_RX_CONF1_hz_60_200khz (4U<<0) +#define ST25R3916_REG_RX_CONF1_hz_40_80khz (2U<<0) +#define ST25R3916_REG_RX_CONF1_hz_12_200khz (1U<<0) +#define ST25R3916_REG_RX_CONF1_hz_12_80khz (3U<<0) +#define ST25R3916_REG_RX_CONF1_hz_12_200khz_alt (5U<<0) +#define ST25R3916_REG_RX_CONF1_hz_600_400khz (8U<<0) +#define ST25R3916_REG_RX_CONF1_hz_600_200khz (12U<<0) +#define ST25R3916_REG_RX_CONF1_hz_mask (0xfU<<0) +#define ST25R3916_REG_RX_CONF1_hz_shift (0U) + +#define ST25R3916_REG_RX_CONF2_demod_mode (1U<<7) +#define ST25R3916_REG_RX_CONF2_amd_sel (1U<<6) +#define ST25R3916_REG_RX_CONF2_amd_sel_mixer (1U<<6) +#define ST25R3916_REG_RX_CONF2_amd_sel_peak (0U<<6) +#define ST25R3916_REG_RX_CONF2_sqm_dyn (1U<<5) +#define ST25R3916_REG_RX_CONF2_pulz_61 (1U<<4) +#define ST25R3916_REG_RX_CONF2_agc_en (1U<<3) +#define ST25R3916_REG_RX_CONF2_agc_m (1U<<2) +#define ST25R3916_REG_RX_CONF2_agc_alg (1U<<1) +#define ST25R3916_REG_RX_CONF2_agc6_3 (1U<<0) + +#define ST25R3916_REG_RX_CONF3_rg1_am2 (1U<<7) +#define ST25R3916_REG_RX_CONF3_rg1_am1 (1U<<6) +#define ST25R3916_REG_RX_CONF3_rg1_am0 (1U<<5) +#define ST25R3916_REG_RX_CONF3_rg1_am_mask (0x7U<<5) +#define ST25R3916_REG_RX_CONF3_rg1_am_shift (5U) +#define ST25R3916_REG_RX_CONF3_rg1_pm2 (1U<<4) +#define ST25R3916_REG_RX_CONF3_rg1_pm1 (1U<<3) +#define ST25R3916_REG_RX_CONF3_rg1_pm0 (1U<<2) +#define ST25R3916_REG_RX_CONF3_rg1_pm_mask (0x7U<<2) +#define ST25R3916_REG_RX_CONF3_rg1_pm_shift (2U) +#define ST25R3916_REG_RX_CONF3_lf_en (1U<<1) +#define ST25R3916_REG_RX_CONF3_lf_op (1U<<0) + +#define ST25R3916_REG_RX_CONF4_rg2_am3 (1U<<7) +#define ST25R3916_REG_RX_CONF4_rg2_am2 (1U<<6) +#define ST25R3916_REG_RX_CONF4_rg2_am1 (1U<<5) +#define ST25R3916_REG_RX_CONF4_rg2_am0 (1U<<4) +#define ST25R3916_REG_RX_CONF4_rg2_am_mask (0xfU<<4) +#define ST25R3916_REG_RX_CONF4_rg2_am_shift (4U) +#define ST25R3916_REG_RX_CONF4_rg2_pm3 (1U<<3) +#define ST25R3916_REG_RX_CONF4_rg2_pm2 (1U<<2) +#define ST25R3916_REG_RX_CONF4_rg2_pm1 (1U<<1) +#define ST25R3916_REG_RX_CONF4_rg2_pm0 (1U<<0) +#define ST25R3916_REG_RX_CONF4_rg2_pm_mask (0xfU<<0) +#define ST25R3916_REG_RX_CONF4_rg2_pm_shift (0U) + +#define ST25R3916_REG_P2P_RX_CONF_ook_fd (1U<<7) +#define ST25R3916_REG_P2P_RX_CONF_ook_rc1 (1U<<6) +#define ST25R3916_REG_P2P_RX_CONF_ook_rc0 (1U<<5) +#define ST25R3916_REG_P2P_RX_CONF_ook_thd1 (1U<<4) +#define ST25R3916_REG_P2P_RX_CONF_ook_thd0 (1U<<3) +#define ST25R3916_REG_P2P_RX_CONF_ask_rc1 (1U<<2) +#define ST25R3916_REG_P2P_RX_CONF_ask_rc0 (1U<<1) +#define ST25R3916_REG_P2P_RX_CONF_ask_thd (1U<<0) + +#define ST25R3916_REG_CORR_CONF1_corr_s7 (1U<<7) +#define ST25R3916_REG_CORR_CONF1_corr_s6 (1U<<6) +#define ST25R3916_REG_CORR_CONF1_corr_s5 (1U<<5) +#define ST25R3916_REG_CORR_CONF1_corr_s4 (1U<<4) +#define ST25R3916_REG_CORR_CONF1_corr_s3 (1U<<3) +#define ST25R3916_REG_CORR_CONF1_corr_s2 (1U<<2) +#define ST25R3916_REG_CORR_CONF1_corr_s1 (1U<<1) +#define ST25R3916_REG_CORR_CONF1_corr_s0 (1U<<0) + +#define ST25R3916_REG_CORR_CONF2_rfu5 (1U<<7) +#define ST25R3916_REG_CORR_CONF2_rfu4 (1U<<6) +#define ST25R3916_REG_CORR_CONF2_rfu3 (1U<<5) +#define ST25R3916_REG_CORR_CONF2_rfu2 (1U<<4) +#define ST25R3916_REG_CORR_CONF2_rfu1 (1U<<3) +#define ST25R3916_REG_CORR_CONF2_rfu0 (1U<<2) +#define ST25R3916_REG_CORR_CONF2_corr_s9 (1U<<1) +#define ST25R3916_REG_CORR_CONF2_corr_s8 (1U<<0) + +#define ST25R3916_REG_TIMER_EMV_CONTROL_gptc2 (1U<<7) +#define ST25R3916_REG_TIMER_EMV_CONTROL_gptc1 (1U<<6) +#define ST25R3916_REG_TIMER_EMV_CONTROL_gptc0 (1U<<5) +#define ST25R3916_REG_TIMER_EMV_CONTROL_gptc_no_trigger (0U<<5) +#define ST25R3916_REG_TIMER_EMV_CONTROL_gptc_erx (1U<<5) +#define ST25R3916_REG_TIMER_EMV_CONTROL_gptc_srx (2U<<5) +#define ST25R3916_REG_TIMER_EMV_CONTROL_gptc_etx_nfc (3U<<5) +#define ST25R3916_REG_TIMER_EMV_CONTROL_gptc_mask (7U<<5) +#define ST25R3916_REG_TIMER_EMV_CONTROL_gptc_shift (5U) +#define ST25R3916_REG_TIMER_EMV_CONTROL_rfu (1U<<4) +#define ST25R3916_REG_TIMER_EMV_CONTROL_mrt_step (1U<<3) +#define ST25R3916_REG_TIMER_EMV_CONTROL_mrt_step_512 (1U<<3) +#define ST25R3916_REG_TIMER_EMV_CONTROL_mrt_step_64 (0U<<3) +#define ST25R3916_REG_TIMER_EMV_CONTROL_nrt_nfc (1U<<2) +#define ST25R3916_REG_TIMER_EMV_CONTROL_nrt_nfc_on (1U<<2) +#define ST25R3916_REG_TIMER_EMV_CONTROL_nrt_nfc_off (0U<<2) +#define ST25R3916_REG_TIMER_EMV_CONTROL_nrt_emv (1U<<1) +#define ST25R3916_REG_TIMER_EMV_CONTROL_nrt_emv_on (1U<<1) +#define ST25R3916_REG_TIMER_EMV_CONTROL_nrt_emv_off (0U<<1) +#define ST25R3916_REG_TIMER_EMV_CONTROL_nrt_step (1U<<0) +#define ST25R3916_REG_TIMER_EMV_CONTROL_nrt_step_64fc (0U<<0) +#define ST25R3916_REG_TIMER_EMV_CONTROL_nrt_step_4096_fc (1U<<0) + +#define ST25R3916_REG_FIFO_STATUS2_fifo_b9 (1U<<7) +#define ST25R3916_REG_FIFO_STATUS2_fifo_b8 (1U<<6) +#define ST25R3916_REG_FIFO_STATUS2_fifo_b_mask (3U<<6) +#define ST25R3916_REG_FIFO_STATUS2_fifo_b_shift (6U) +#define ST25R3916_REG_FIFO_STATUS2_fifo_unf (1U<<5) +#define ST25R3916_REG_FIFO_STATUS2_fifo_ovr (1U<<4) +#define ST25R3916_REG_FIFO_STATUS2_fifo_lb2 (1U<<3) +#define ST25R3916_REG_FIFO_STATUS2_fifo_lb1 (1U<<2) +#define ST25R3916_REG_FIFO_STATUS2_fifo_lb0 (1U<<1) +#define ST25R3916_REG_FIFO_STATUS2_fifo_lb_mask (7U<<1) +#define ST25R3916_REG_FIFO_STATUS2_fifo_lb_shift (1U) +#define ST25R3916_REG_FIFO_STATUS2_np_lb (1U<<0) + +#define ST25R3916_REG_COLLISION_STATUS_c_byte3 (1U<<7) +#define ST25R3916_REG_COLLISION_STATUS_c_byte2 (1U<<6) +#define ST25R3916_REG_COLLISION_STATUS_c_byte1 (1U<<5) +#define ST25R3916_REG_COLLISION_STATUS_c_byte0 (1U<<4) +#define ST25R3916_REG_COLLISION_STATUS_c_byte_mask (0xfU<<4) +#define ST25R3916_REG_COLLISION_STATUS_c_byte_shift (4U) +#define ST25R3916_REG_COLLISION_STATUS_c_bit2 (1U<<3) +#define ST25R3916_REG_COLLISION_STATUS_c_bit1 (1U<<2) +#define ST25R3916_REG_COLLISION_STATUS_c_bit0 (1U<<1) +#define ST25R3916_REG_COLLISION_STATUS_c_pb (1U<<0) +#define ST25R3916_REG_COLLISION_STATUS_c_bit_mask (3U<<1) +#define ST25R3916_REG_COLLISION_STATUS_c_bit_shift (1U) + +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_rfu (1U<<7) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_rfu1 (1U<<6) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_rfu2 (1U<<5) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_rfu3 (1U<<4) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_state3 (1U<<3) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_state2 (1U<<2) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_state1 (1U<<1) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_state0 (1U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_power_off (0x0U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_idle (0x1U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_ready_l1 (0x2U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_ready_l2 (0x3U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_rfu4 (0x4U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_active (0x5U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_rfu6 (0x6U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_rfu7 (0x7U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_rfu8 (0x8U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_halt (0x9U<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_ready_l1_x (0xaU<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_ready_l2_x (0xbU<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_rfu12 (0xcU<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_st_active_x (0xdU<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_state_mask (0xfU<<0) +#define ST25R3916_REG_PASSIVE_TARGET_STATUS_pta_state_shift (0U) + +#define ST25R3916_REG_NUM_TX_BYTES2_ntx4 (1U<<7) +#define ST25R3916_REG_NUM_TX_BYTES2_ntx3 (1U<<6) +#define ST25R3916_REG_NUM_TX_BYTES2_ntx2 (1U<<5) +#define ST25R3916_REG_NUM_TX_BYTES2_ntx1 (1U<<4) +#define ST25R3916_REG_NUM_TX_BYTES2_ntx0 (1U<<3) +#define ST25R3916_REG_NUM_TX_BYTES2_ntx_mask (0x1fU<<3) +#define ST25R3916_REG_NUM_TX_BYTES2_ntx_shift (3U) +#define ST25R3916_REG_NUM_TX_BYTES2_nbtx2 (1U<<2) +#define ST25R3916_REG_NUM_TX_BYTES2_nbtx1 (1U<<1) +#define ST25R3916_REG_NUM_TX_BYTES2_nbtx0 (1U<<0) +#define ST25R3916_REG_NUM_TX_BYTES2_nbtx_mask (7U<<0) +#define ST25R3916_REG_NUM_TX_BYTES2_nbtx_shift (0U) + +#define ST25R3916_REG_NFCIP1_BIT_RATE_nfc_rfu1 (1U<<7) +#define ST25R3916_REG_NFCIP1_BIT_RATE_nfc_rfu0 (1U<<6) +#define ST25R3916_REG_NFCIP1_BIT_RATE_nfc_rate1 (1U<<5) +#define ST25R3916_REG_NFCIP1_BIT_RATE_nfc_rate0 (1U<<4) +#define ST25R3916_REG_NFCIP1_BIT_RATE_nfc_rate_mask (0x3U<<4) +#define ST25R3916_REG_NFCIP1_BIT_RATE_nfc_rate_shift (4U) +#define ST25R3916_REG_NFCIP1_BIT_RATE_ppt2_on (1U<<3) +#define ST25R3916_REG_NFCIP1_BIT_RATE_gpt_on (1U<<2) +#define ST25R3916_REG_NFCIP1_BIT_RATE_nrt_on (1U<<1) +#define ST25R3916_REG_NFCIP1_BIT_RATE_mrt_on (1U<<0) + +#define ST25R3916_REG_TX_DRIVER_am_mod3 (1U<<7) +#define ST25R3916_REG_TX_DRIVER_am_mod2 (1U<<6) +#define ST25R3916_REG_TX_DRIVER_am_mod1 (1U<<5) +#define ST25R3916_REG_TX_DRIVER_am_mod0 (1U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_5percent (0x0U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_6percent (0x1U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_7percent (0x2U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_8percent (0x3U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_9percent (0x4U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_10percent (0x5U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_11percent (0x6U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_12percent (0x7U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_13percent (0x8U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_14percent (0x9U<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_15percent (0xaU<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_17percent (0xbU<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_19percent (0xcU<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_22percent (0xdU<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_26percent (0xeU<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_40percent (0xfU<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_mask (0xfU<<4) +#define ST25R3916_REG_TX_DRIVER_am_mod_shift (4U) +#define ST25R3916_REG_TX_DRIVER_d_res3 (1U<<3) +#define ST25R3916_REG_TX_DRIVER_d_res2 (1U<<2) +#define ST25R3916_REG_TX_DRIVER_d_res1 (1U<<1) +#define ST25R3916_REG_TX_DRIVER_d_res0 (1U<<0) +#define ST25R3916_REG_TX_DRIVER_d_res_mask (0xfU<<0) +#define ST25R3916_REG_TX_DRIVER_d_res_shift (0U) + +#define ST25R3916_REG_PT_MOD_ptm_res3 (1U<<7) +#define ST25R3916_REG_PT_MOD_ptm_res2 (1U<<6) +#define ST25R3916_REG_PT_MOD_ptm_res1 (1U<<5) +#define ST25R3916_REG_PT_MOD_ptm_res0 (1U<<4) +#define ST25R3916_REG_PT_MOD_ptm_res_mask (0xfU<<4) +#define ST25R3916_REG_PT_MOD_ptm_res_shift (4U) +#define ST25R3916_REG_PT_MOD_pt_res3 (1U<<3) +#define ST25R3916_REG_PT_MOD_pt_res2 (1U<<2) +#define ST25R3916_REG_PT_MOD_pt_res1 (1U<<1) +#define ST25R3916_REG_PT_MOD_pt_res0 (1U<<0) +#define ST25R3916_REG_PT_MOD_pt_res_mask (0xfU<<0) +#define ST25R3916_REG_PT_MOD_pt_res_shift (0U) + +#define ST25R3916_REG_AUX_MOD_dis_reg_am (1U<<7) +#define ST25R3916_REG_AUX_MOD_lm_ext_pol (1U<<6) +#define ST25R3916_REG_AUX_MOD_lm_ext (1U<<5) +#define ST25R3916_REG_AUX_MOD_lm_dri (1U<<4) +#define ST25R3916_REG_AUX_MOD_res_am (1U<<3) +#define ST25R3916_REG_AUX_MOD_rfu2 (1U<<2) +#define ST25R3916_REG_AUX_MOD_rfu1 (1U<<1) +#define ST25R3916_REG_AUX_MOD_rfu0 (1U<<0) + +#define ST25R3916_REG_TX_DRIVER_TIMING_d_rat_t3 (1U<<7) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_rat_t2 (1U<<6) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_rat_t1 (1U<<5) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_rat_t0 (1U<<4) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_rat_mask (0xfU<<4) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_rat_shift (4U) +#define ST25R3916_REG_TX_DRIVER_TIMING_rfu (1U<<3) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_tim_m2 (1U<<2) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_tim_m1 (1U<<1) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_tim_m0 (1U<<0) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_tim_m_mask (0x7U<<0) +#define ST25R3916_REG_TX_DRIVER_TIMING_d_tim_m_shift (0U) + +#define ST25R3916_REG_RES_AM_MOD_fa3_f (1U<<7) +#define ST25R3916_REG_RES_AM_MOD_md_res6 (1U<<6) +#define ST25R3916_REG_RES_AM_MOD_md_res5 (1U<<5) +#define ST25R3916_REG_RES_AM_MOD_md_res4 (1U<<4) +#define ST25R3916_REG_RES_AM_MOD_md_res3 (1U<<3) +#define ST25R3916_REG_RES_AM_MOD_md_res2 (1U<<2) +#define ST25R3916_REG_RES_AM_MOD_md_res1 (1U<<1) +#define ST25R3916_REG_RES_AM_MOD_md_res0 (1U<<0) +#define ST25R3916_REG_RES_AM_MOD_md_res_mask (0x7FU<<0) +#define ST25R3916_REG_RES_AM_MOD_md_res_shift (0U) + +#define ST25R3916_REG_TX_DRIVER_STATUS_d_rat_r3 (1U<<7) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_rat_r2 (1U<<6) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_rat_r1 (1U<<5) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_rat_r0 (1U<<4) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_rat_mask (0xfU<<4) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_rat_shift (4U) +#define ST25R3916_REG_TX_DRIVER_STATUS_rfu (1U<<3) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_tim_r2 (1U<<2) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_tim_r1 (1U<<1) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_tim_r0 (1U<<0) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_tim_mask (0x7U<<0) +#define ST25R3916_REG_TX_DRIVER_STATUS_d_tim_shift (0U) + +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_l2a (1U<<6) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_l1a (1U<<5) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_l0a (1U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_75mV (0x0U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_105mV (0x1U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_150mV (0x2U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_205mV (0x3U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_290mV (0x4U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_400mV (0x5U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_560mV (0x6U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_800mV (0x7U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_mask (7U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_trg_shift (4U) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_t3a (1U<<3) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_t2a (1U<<2) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_t1a (1U<<1) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_t0a (1U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_75mV (0x0U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_105mV (0x1U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_150mV (0x2U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_205mV (0x3U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_290mV (0x4U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_400mV (0x5U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_560mV (0x6U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_800mV (0x7U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_25mV (0x8U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_33mV (0x9U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_47mV (0xAU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_64mV (0xBU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_90mV (0xCU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_125mV (0xDU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_175mV (0xEU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_250mV (0xFU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_mask (0xfU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_ACTV_rfe_shift (0U) + +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_l2d (1U<<6) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_l1d (1U<<5) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_l0d (1U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_75mV (0x0U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_105mV (0x1U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_150mV (0x2U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_205mV (0x3U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_290mV (0x4U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_400mV (0x5U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_560mV (0x6U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_800mV (0x7U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_mask (7U<<4) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_trg_shift (4U) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_t3d (1U<<3) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_t2d (1U<<2) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_t1d (1U<<1) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_t0d (1U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_75mV (0x0U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_105mV (0x1U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_150mV (0x2U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_205mV (0x3U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_290mV (0x4U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_400mV (0x5U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_560mV (0x6U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_800mV (0x7U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_25mV (0x8U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_33mV (0x9U<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_47mV (0xAU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_64mV (0xBU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_90mV (0xCU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_125mV (0xDU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_175mV (0xEU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_250mV (0xFU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_mask (0xfU<<0) +#define ST25R3916_REG_FIELD_THRESHOLD_DEACTV_rfe_shift (0U) + +#define ST25R3916_REG_REGULATOR_CONTROL_reg_s (1U<<7) +#define ST25R3916_REG_REGULATOR_CONTROL_rege_3 (1U<<6) +#define ST25R3916_REG_REGULATOR_CONTROL_rege_2 (1U<<5) +#define ST25R3916_REG_REGULATOR_CONTROL_rege_1 (1U<<4) +#define ST25R3916_REG_REGULATOR_CONTROL_rege_0 (1U<<3) +#define ST25R3916_REG_REGULATOR_CONTROL_rege_mask (0xfU<<3) +#define ST25R3916_REG_REGULATOR_CONTROL_rege_shift (3U) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv2 (2U<<2) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv1 (1U<<1) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv0 (1U<<0) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd (0U) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_a (1U) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_d (2U) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_rf (3U) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv_vdd_am (4U) +#define ST25R3916_REG_REGULATOR_CONTROL_rfu (5U) +#define ST25R3916_REG_REGULATOR_CONTROL_rfu1 (6U) +#define ST25R3916_REG_REGULATOR_CONTROL_rfu2 (7U) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv_mask (7U) +#define ST25R3916_REG_REGULATOR_CONTROL_mpsv_shift (0U) + +#define ST25R3916_REG_REGULATOR_RESULT_reg_3 (1U<<7) +#define ST25R3916_REG_REGULATOR_RESULT_reg_2 (1U<<6) +#define ST25R3916_REG_REGULATOR_RESULT_reg_1 (1U<<5) +#define ST25R3916_REG_REGULATOR_RESULT_reg_0 (1U<<4) +#define ST25R3916_REG_REGULATOR_RESULT_reg_mask (0xfU<<4) +#define ST25R3916_REG_REGULATOR_RESULT_reg_shift (4U) +#define ST25R3916_REG_REGULATOR_RESULT_i_lim (1U<<0) + +#define ST25R3916_REG_RSSI_RESULT_rssi_am_3 (1U<<7) +#define ST25R3916_REG_RSSI_RESULT_rssi_am_2 (1U<<6) +#define ST25R3916_REG_RSSI_RESULT_rssi_am_1 (1U<<5) +#define ST25R3916_REG_RSSI_RESULT_rssi_am_0 (1U<<4) +#define ST25R3916_REG_RSSI_RESULT_rssi_am_mask (0xfU<<4) +#define ST25R3916_REG_RSSI_RESULT_rssi_am_shift (4U) +#define ST25R3916_REG_RSSI_RESULT_rssi_pm3 (1U<<3) +#define ST25R3916_REG_RSSI_RESULT_rssi_pm2 (1U<<2) +#define ST25R3916_REG_RSSI_RESULT_rssi_pm1 (1U<<1) +#define ST25R3916_REG_RSSI_RESULT_rssi_pm0 (1U<<0) +#define ST25R3916_REG_RSSI_RESULT_rssi_pm_mask (0xfU<<0) +#define ST25R3916_REG_RSSI_RESULT_rssi_pm_shift (0U) + +#define ST25R3916_REG_GAIN_RED_STATE_gs_am_3 (1U<<7) +#define ST25R3916_REG_GAIN_RED_STATE_gs_am_2 (1U<<6) +#define ST25R3916_REG_GAIN_RED_STATE_gs_am_1 (1U<<5) +#define ST25R3916_REG_GAIN_RED_STATE_gs_am_0 (1U<<4) +#define ST25R3916_REG_GAIN_RED_STATE_gs_am_mask (0xfU<<4) +#define ST25R3916_REG_GAIN_RED_STATE_gs_am_shift (4U) +#define ST25R3916_REG_GAIN_RED_STATE_gs_pm_3 (1U<<3) +#define ST25R3916_REG_GAIN_RED_STATE_gs_pm_2 (1U<<2) +#define ST25R3916_REG_GAIN_RED_STATE_gs_pm_1 (1U<<1) +#define ST25R3916_REG_GAIN_RED_STATE_gs_pm_0 (1U<<0) +#define ST25R3916_REG_GAIN_RED_STATE_gs_pm_mask (0xfU<<0) +#define ST25R3916_REG_GAIN_RED_STATE_gs_pm_shift (0U) + +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_mcal4 (1U<<7) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_mcal3 (1U<<6) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_mcal2 (1U<<5) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_mcal1 (1U<<4) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_mcal0 (1U<<3) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_mcal_mask (0x1fU<<3) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_mcal_shift (3U) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_g2 (1U<<2) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_g1 (1U<<1) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_g0 (1U<<0) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_g_mask (7U<<0) +#define ST25R3916_REG_CAP_SENSOR_CONTROL_cs_g_shift (0U) + +#define ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal4 (1U<<7) +#define ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal3 (1U<<6) +#define ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal2 (1U<<5) +#define ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal1 (1U<<4) +#define ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal0 (1U<<3) +#define ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal_mask (0x1fU<<3) +#define ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal_shift (3U) +#define ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal_end (1U<<2) +#define ST25R3916_REG_CAP_SENSOR_RESULT_cs_cal_err (1U<<1) + +#define ST25R3916_REG_AUX_DISPLAY_a_cha (1U<<7) +#define ST25R3916_REG_AUX_DISPLAY_efd_o (1U<<6) +#define ST25R3916_REG_AUX_DISPLAY_tx_on (1U<<5) +#define ST25R3916_REG_AUX_DISPLAY_osc_ok (1U<<4) +#define ST25R3916_REG_AUX_DISPLAY_rx_on (1U<<3) +#define ST25R3916_REG_AUX_DISPLAY_rx_act (1U<<2) +#define ST25R3916_REG_AUX_DISPLAY_en_peer (1U<<1) +#define ST25R3916_REG_AUX_DISPLAY_en_ac (1U<<0) + +#define ST25R3916_REG_OVERSHOOT_CONF1_ov_tx_mode1 (1U<<7) +#define ST25R3916_REG_OVERSHOOT_CONF1_ov_tx_mode0 (1U<<6) +#define ST25R3916_REG_OVERSHOOT_CONF1_ov_pattern13 (1U<<5) +#define ST25R3916_REG_OVERSHOOT_CONF1_ov_pattern12 (1U<<4) +#define ST25R3916_REG_OVERSHOOT_CONF1_ov_pattern11 (1U<<3) +#define ST25R3916_REG_OVERSHOOT_CONF1_ov_pattern10 (1U<<2) +#define ST25R3916_REG_OVERSHOOT_CONF1_ov_pattern9 (1U<<1) +#define ST25R3916_REG_OVERSHOOT_CONF1_ov_pattern8 (1U<<0) + +#define ST25R3916_REG_OVERSHOOT_CONF2_ov_pattern7 (1U<<7) +#define ST25R3916_REG_OVERSHOOT_CONF2_ov_pattern6 (1U<<6) +#define ST25R3916_REG_OVERSHOOT_CONF2_ov_pattern5 (1U<<5) +#define ST25R3916_REG_OVERSHOOT_CONF2_ov_pattern4 (1U<<4) +#define ST25R3916_REG_OVERSHOOT_CONF2_ov_pattern3 (1U<<3) +#define ST25R3916_REG_OVERSHOOT_CONF2_ov_pattern2 (1U<<2) +#define ST25R3916_REG_OVERSHOOT_CONF2_ov_pattern1 (1U<<1) +#define ST25R3916_REG_OVERSHOOT_CONF2_ov_pattern0 (1U<<0) + +#define ST25R3916_REG_UNDERSHOOT_CONF1_un_tx_mode1 (1U<<7) +#define ST25R3916_REG_UNDERSHOOT_CONF1_un_tx_mode0 (1U<<6) +#define ST25R3916_REG_UNDERSHOOT_CONF1_un_pattern13 (1U<<5) +#define ST25R3916_REG_UNDERSHOOT_CONF1_un_pattern12 (1U<<4) +#define ST25R3916_REG_UNDERSHOOT_CONF1_un_pattern11 (1U<<3) +#define ST25R3916_REG_UNDERSHOOT_CONF1_un_pattern10 (1U<<2) +#define ST25R3916_REG_UNDERSHOOT_CONF1_un_pattern9 (1U<<1) +#define ST25R3916_REG_UNDERSHOOT_CONF1_un_pattern8 (1U<<0) + +#define ST25R3916_REG_UNDERSHOOT_CONF2_un_pattern7 (1U<<7) +#define ST25R3916_REG_UNDERSHOOT_CONF2_un_pattern6 (1U<<6) +#define ST25R3916_REG_UNDERSHOOT_CONF2_un_pattern5 (1U<<5) +#define ST25R3916_REG_UNDERSHOOT_CONF2_un_pattern4 (1U<<4) +#define ST25R3916_REG_UNDERSHOOT_CONF2_un_pattern3 (1U<<3) +#define ST25R3916_REG_UNDERSHOOT_CONF2_un_pattern2 (1U<<2) +#define ST25R3916_REG_UNDERSHOOT_CONF2_un_pattern1 (1U<<1) +#define ST25R3916_REG_UNDERSHOOT_CONF2_un_pattern0 (1U<<0) + +#define ST25R3916_REG_WUP_TIMER_CONTROL_wur (1U<<7) +#define ST25R3916_REG_WUP_TIMER_CONTROL_wut2 (1U<<6) +#define ST25R3916_REG_WUP_TIMER_CONTROL_wut1 (1U<<5) +#define ST25R3916_REG_WUP_TIMER_CONTROL_wut0 (1U<<4) +#define ST25R3916_REG_WUP_TIMER_CONTROL_wut_mask (7U<<4) +#define ST25R3916_REG_WUP_TIMER_CONTROL_wut_shift (4U) +#define ST25R3916_REG_WUP_TIMER_CONTROL_wto (1U<<3) +#define ST25R3916_REG_WUP_TIMER_CONTROL_wam (1U<<2) +#define ST25R3916_REG_WUP_TIMER_CONTROL_wph (1U<<1) +#define ST25R3916_REG_WUP_TIMER_CONTROL_wcap (1U<<0) + +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_d3 (1U<<7) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_d2 (1U<<6) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_d1 (1U<<5) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_d0 (1U<<4) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_d_mask (0xfU<<4) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_d_shift (4U) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_aam (1U<<3) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_aew1 (1U<<2) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_aew0 (1U<<1) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_aew_mask (0x3U<<1) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_aew_shift (1U) +#define ST25R3916_REG_AMPLITUDE_MEASURE_CONF_am_ae (1U<<0) + +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_d3 (1U<<7) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_d2 (1U<<6) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_d1 (1U<<5) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_d0 (1U<<4) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_d_mask (0xfU<<4) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_d_shift (4U) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_aam (1U<<3) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_aew1 (1U<<2) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_aew0 (1U<<1) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_aew_mask (0x3U<<1) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_aew_shift (1U) +#define ST25R3916_REG_PHASE_MEASURE_CONF_pm_ae (1U<<0) + +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_d3 (1U<<7) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_d2 (1U<<6) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_d1 (1U<<5) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_d0 (1U<<4) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_d_mask (0xfU<<4) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_d_shift (4U) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_aam (1U<<3) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_aew1 (1U<<2) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_aew0 (1U<<1) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_aew_mask (0x3U<<1) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_aew_shift (1U) +#define ST25R3916_REG_CAPACITANCE_MEASURE_CONF_cm_ae (1U<<0) + +#define ST25R3916_REG_IC_IDENTITY_ic_type4 (1U<<7) +#define ST25R3916_REG_IC_IDENTITY_ic_type3 (1U<<6) +#define ST25R3916_REG_IC_IDENTITY_ic_type2 (1U<<5) +#define ST25R3916_REG_IC_IDENTITY_ic_type1 (1U<<4) +#define ST25R3916_REG_IC_IDENTITY_ic_type0 (1U<<3) +#define ST25R3916_REG_IC_IDENTITY_ic_type_st25r3916 (5U<<3) +#define ST25R3916_REG_IC_IDENTITY_ic_type_mask (0x1fU<<3) +#define ST25R3916_REG_IC_IDENTITY_ic_type_shift (3U) +#define ST25R3916_REG_IC_IDENTITY_ic_rev2 (1U<<2) +#define ST25R3916_REG_IC_IDENTITY_ic_rev1 (1U<<1) +#define ST25R3916_REG_IC_IDENTITY_ic_rev0 (1U<<0) +#define ST25R3916_REG_IC_IDENTITY_ic_rev_v0 (0U<<0) +#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 + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916ReadRegister( uint8_t reg, uint8_t* val ); + +/*! + ***************************************************************************** + * \brief Reads from multiple ST25R3916 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 frist 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 + ***************************************************************************** + */ +ReturnCode st25r3916ReadMultipleRegisters( uint8_t reg, uint8_t* values, uint8_t length ); + +/*! + ***************************************************************************** + * \brief Writes a given value to a register within the ST25R3916 + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916WriteRegister( uint8_t reg, uint8_t val ); + +/*! + ***************************************************************************** + * \brief Writes multiple values to ST25R3916 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 frist 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 + ***************************************************************************** + */ +ReturnCode st25r3916WriteMultipleRegisters( uint8_t reg, const uint8_t* values, uint8_t length ); + +/*! + ***************************************************************************** + * \brief Writes values to ST25R3916 FIFO + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916WriteFifo( const uint8_t* values, uint16_t length ); + +/*! + ***************************************************************************** + * \brief Read values from ST25R3916 FIFO + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916ReadFifo( uint8_t* buf, uint16_t length ); + +/*! + ***************************************************************************** + * \brief Writes values to ST25R3916 PTM + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916WritePTMem( const uint8_t* values, uint16_t length ); + +/*! + ***************************************************************************** + * \brief Reads the ST25R3916 PTM + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916ReadPTMem( uint8_t* values, uint16_t length ); + +/*! + ***************************************************************************** + * \brief Writes values to ST25R3916 PTM F config + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916WritePTMemF( const uint8_t* values, uint16_t length ); + +/*! + ***************************************************************************** + * \brief Writes values to ST25R3916 PTM TSN Data + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916WritePTMemTSN( const uint8_t* values, uint16_t length ); + +/*! + ***************************************************************************** + * \brief Execute a 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 + ***************************************************************************** + */ +ReturnCode st25r3916ExecuteCommand( 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 + ***************************************************************************** + */ +ReturnCode st25r3916ReadTestRegister( uint8_t reg, uint8_t* val ); + +/*! + ***************************************************************************** + * \brief Writes a given value to a test register within the ST25R3916 + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916WriteTestRegister( uint8_t reg, uint8_t val ); + +/*! + ***************************************************************************** + * \brief Cleart bits on Register + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916ClrRegisterBits( uint8_t reg, uint8_t clr_mask ); + +/*! + ***************************************************************************** + * \brief Set bits on Register + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916SetRegisterBits( uint8_t reg, uint8_t set_mask ); + +/*! + ***************************************************************************** + * \brief Changes the given bits on a ST25R3916 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 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 + ***************************************************************************** + */ +ReturnCode st25r3916ChangeRegisterBits( uint8_t reg, uint8_t valueMask, uint8_t value ); + +/*! + ***************************************************************************** + * \brief Modifies a value within a ST25R3916 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 + ***************************************************************************** + */ +ReturnCode st25r3916ModifyRegister( uint8_t reg, uint8_t clr_mask, uint8_t set_mask ); + +/*! + ***************************************************************************** + * \brief Changes the given bits on a ST25R3916 Test register + * + * 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 + ***************************************************************************** + */ +ReturnCode st25r3916ChangeTestRegisterBits( uint8_t reg, uint8_t valueMask, uint8_t value ); + +/*! + ***************************************************************************** + * \brief Checks if register contains a expected value + * + * This function checks if the given reg contains a value that once masked + * equals the expected 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 + */ +bool st25r3916CheckReg( 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 */ + + +/** + * @} + * + * @} + * + * @} + * + * @} + */ diff --git a/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_irq.c b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_irq.c new file mode 100644 index 0000000..97476a5 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_irq.c @@ -0,0 +1,262 @@ + +/****************************************************************************** + * \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> (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/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_irq.h b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_irq.h new file mode 100644 index 0000000..88332d7 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_irq.h @@ -0,0 +1,264 @@ + +/****************************************************************************** + * \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 occured 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 occured. 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 occured. + * + ***************************************************************************** + */ +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 interupt + ***************************************************************************** + */ +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/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_led.c b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_led.c new file mode 100644 index 0000000..40b8437 --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_led.c @@ -0,0 +1,157 @@ + +/****************************************************************************** + * \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/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_led.h b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_led.h new file mode 100644 index 0000000..f1952fa --- /dev/null +++ b/src/hydranfc_v2/rfal/src/st25r3916/st25r3916_led.h @@ -0,0 +1,153 @@ + +/****************************************************************************** + * \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/src/main.c b/src/main.c index 7c91361..fbf0206 100644 --- a/src/main.c +++ b/src/main.c @@ -1,7 +1,7 @@ /* * HydraBus/HydraNFC * - * Copyright (C) 2014-2015 Benjamin VERNOUX + * Copyright (C) 2014-2020 Benjamin VERNOUX * Copyright (C) 2014 Bert Vermeulen * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -36,6 +36,9 @@ #ifdef HYDRANFC #include "hydranfc.h" #endif +#ifdef HYDRANFC_V2 +#include "hydranfc_v2.h" +#endif #include "hydrabus/hydrabus_bbio.h" #include "hydrabus/hydrabus_sump.h" @@ -124,7 +127,7 @@ int main(void) { int sleep_ms, i; int local_nb_console; -#ifdef HYDRANFC +#if defined(HYDRANFC) || defined(HYDRANFC_V2) bool hydranfc_detected; #endif @@ -185,6 +188,10 @@ int main(void) #ifdef HYDRANFC /* Check HydraNFC */ hydranfc_detected = hydranfc_is_detected(); +#endif +#ifdef HYDRANFC_V2 + /* Check HydraNFC */ + hydranfc_detected = hydranfc_v2_is_detected(); #endif /* * Normal main() thread activity. @@ -236,7 +243,7 @@ int main(void) sleep_ms = BLINK_SLOW; ULED_OFF; -#ifdef HYDRANFC +#if defined(HYDRANFC) if(hydranfc_detected == TRUE) { /* If K3_BUTTON is pressed */ if (K3_BUTTON) { @@ -245,6 +252,16 @@ int main(void) chThdSleepMilliseconds(1000); } } +#endif +#if defined(HYDRANFC_V2) + if(hydranfc_detected == TRUE) { + /* If K1_BUTTON is pressed */ + if (K1_BUTTON) { + hydranfc_cleanup(NULL); + hydranfc_init(NULL); + chThdSleepMilliseconds(1000); + } + } #endif chThdSleepMilliseconds(sleep_ms); }