/***************  COPYRIGHT (c) 2002-2007 FICOSA INTERNATIONAL   **************
| Language:       |  MISRA C
| Controller:     |  Generic
| Spec. Document: |  ISO15765-2-E.pdf
|-----------------|------------------------------------------------------------
| Project:        |  ISO15765-2
| Reference:      |  
|------------------------------------------------------------------------------
|    Date  - Cod. - Rev. - App. -             Description
| 12/09/02   AM                 Implementation of the kwp2000 for PSA.
| 19/08/04   DT                 Split ISO15765_2 protocol from the KWP2000
|                               because they are different modules.
| 24/04/09   DC                 Modification to guarantee the requirements SR1431, 
|                               SR1438, SR1681.
| 15/12/10   AC                 Converted ISO15765_2 protocol to multi-instance.
| 13/11/11   AC                 Converted ISO15765_2 to full-duplex
| 09/01/12   AC                 Changed file, routines and variable naming to 
|                               make it a standard component improving his
|                               comprehension and having a similar naming style 
|                               with MPDT.
|------------------------------------------------------------------------------
| DESCRIPTION:
|   User interface for the transport protocol ISO15765_2 on CAN.
|   ISO15765_2 protocol is a transport protocol that permits the sending and
|   reception of frames until 4096 bytes on a network protocol with frames of
|   lower size. The original frame is segemented and sent with flow control
|   data that allows to the reception node to mount again the original frame.
| GENERAL CONSIDERATIONS
|   - This implementation allows full duplex communications.
|   - This implementation allows for each instance a communication channel
|     with physical address in which both transmission and receptions could
|     be done and a funcional address for only receptions.
|   - The functional address channel only supports frames with less than
|     8 bytes of data.
|   - This header must be included by the application as it contains the
|     definitions of the ISO15765_2 shared structures that allow the ISO15765_2
|     and the application to communicate and interact.
******************************************************************************/
#ifndef __TP_H
#define __TP_H

/*----------------------------- INCLUDES ---------------------------------*/
#include "DiagnosticL/UDS/Iso15765_layer2/TP_CFG.h"
#include "DiagnosticL/FicOsek/FicOsekCom.h"
#include "OsekCom/OsekCom.h"
//#include "Global.h"
#include "Std_Types.h"

/*----------------------------- DEFINES ----------------------------------*/

/* Macro to calculate the size of the buffer that must allocate the */
/* transport protocol frame */
#define SIZE_ALLOC_BUFFER(val)                                            \
    (((val) <= 7) ? (7) :                                                 \
    ((val) + (((((val) - 6) % 7) > 0) ? (7 - (((val) - 6) % 7)) : (0))))

/*-------------------------- DATA TYPES ----------------------------------*/

/* List of the possible types of flow controls */
typedef enum {
    TP_FLOW_STS_CTS = 0,   /* Clear to Send    */
    TP_FLOW_STS_WT  = 1,   /* Wait             */
    TP_FLOW_STS_OVFLW = 2  /* Buffer Overflow  */
} t_tp_flow_sts;

/* List of the possible status for transmiting */
typedef enum {
    TP_TX_REQUESTED = 0,   /* Transmission requested */
    TP_TX_ON_GOING = 1,    /* Transmission ongoing */
    TP_TX_CONFIRMED = 2,   /* Transmission confirmed */
    TP_TX_ERROR = 3        /* Transmission error */
} t_tp_tx_sts;

/* List of the possible types of transport protocol received frames */
typedef enum {
    TP_RX_SF = 0,         /* Received Single Frame        (SF) */
    TP_RX_FF = 1,         /* Received First Frame         (FF) */
    TP_RX_CF = 2,         /* Received Consecutive  Frame  (CF) */
    TP_RX_NO_FRM = 3      /* No recognized frame received */
} t_tp_rx_frm;

/* List of the possible status of flow control */
typedef enum {
    TP_FC = 0,          /* Received Flow Control Frame  (FC) */
    TP_NO_FC_FRM = 1    /* No recognized FC received */
} t_tp_fc_frm;

/* List of the possible status of reception */
typedef enum {
    TP_FRM_RX_IDLE        = 0,  /* Idle status of RX, nothing new */
    TP_FRM_RX_IN_PRG      = 1,  /* Reception in progress */
    TP_FRM_RX_NOTIF       = 2,  /* Notification to higher layer of a full reception */
    TP_FRM_RX_ERR_NOTIF   = 3,  /* Notification to higher layer of error during a reception */
    TP_FRM_RX_FINISHED    = 4,  /* CF reception finished and pending to be notified to higher layer */
    TP_FRM_RX_ERR_FINISHED = 5  /* Error reception finished and pending to be notified to higher layer */
} t_tp_frm_sts_rx;

/* List of the possible status of transmission */
typedef enum {
    TP_FRM_TX_IDLE        = 0,  /* No TX in progress and last TX OK           */
    TP_FRM_TX_REQ         = 1,  /* Transmission requested and pending         */
    TP_FRM_TX_ERR_NOTIF   = 2,  /* Error occurred during last transmission    */
    TP_FRM_TX_PENDING     = 3   /* Transmission needed pending to be given    */
} t_tp_frm_sts_tx;

/* Types of frame that TP have pending to send */
typedef enum {  
    TP_TX_TYPE_NONE       = 0,  /* TP do not have any frame to be sent */
    TP_TX_TYPE_FC         = 1,  /* TP is going to send a FC */
    TP_TX_TYPE_SF_FF_CF   = 2   /* TP is going to send a SF, FF or CF */
} t_tp_tx_type;

/* Structure that contains all the information for the physical reception and transmission */
typedef struct {
    UI_8* data_tx;              /* Pointer to the buffer that will be transmitted when requested */
    UI_8* data_rx;              /* Pointer to the physical reception buffer */
    UI_16 size_tx;              /* Size of the transmission requested */
    UI_16 size_rx;              /* Size of the last reception */
    t_tp_frm_sts_tx sts_tx;     /* Status of the transmission */
    t_tp_frm_sts_rx sts_rx;     /* Status of the phyisical reception */
    BOOL unblock_after_tx;      /* Flag to unblock the ISO15765_2 reception at the end of the current transmission */
    BOOL iso15765_2_block_rx;   /* Flag to block the reception of new frames. To be used for example in diagnostics where a */
                                /* request must always be answered before receiving another request */
    BOOL iso15765_2_block_tx;   /* Flag that blocks the transmission of diagnostics on the ISO15765_2. To be used for example */
                                /* when the TCU is acting as a UDS client and is doing autodiagnostics */
} t_tp_frm;

/* Structure that contains the functional reception frame information */
typedef struct {
    UI_8 *data_rx;              /* Pointer to the physical reception buffer */
    UI_8 size;                  /* Size of the received functional data */
    t_tp_frm_sts_rx sts_rx;     /* Status of the functional reception */
} t_tp_fun_frm;

/* Structure that must be used to initialize an instance of the ISO15765_2 module. This structure must   */
/* be defined in the stack in a ISO15765_2 callback routine inside the application space that must be    */
/* named Iso15765_2_DynamicParametersInitCallback and will be directly called by the                     */
/* InicialitzaIso15765_2Task routine that must be the only one called from the initializations in main.  */
typedef struct {
    UI_16 max_frm_size;         /* Maximum size allowed for the TP RX buffer. The protocol allows        */
                                /* frames until 4096 bytes. The buffer must be reserved having into      */
                                /* account the MACRO "SIZE_ALLOC_BUFFER" to avoid overflows.             */
    BOOL frm_size_fixed;        /* Flag to configure fixed or variable length in the CAN frames TX       */
                                /* Allowed values:                                                       */
                                /*   TRUE -> all the TP frames are sent with 8 bytes and the non useful  */
                                /*           ones are padded with the value tx_padding_value             */
                                /*   FALSE -> all the TP frames are sent only with the length needed to  */
                                /*            send all the valid data                                    */
	BOOL rx_padding_sensitive;	/* Flag to be taken into account if frm_size_fixed is defined as TRUE.   */
                                /* Allowed values:                                                       */
                                /*   TRUE -> RX TP frames with less than 8 bytes are ignored  			 */
                                /*   FALSE -> RX TP frames with less than 8 bytes are processed          */
								/*            correctly if the frame has a correct TP format             */
    UI_8 tx_padding_value;      /* Padding value for the non valid bytes in case that                    */
                                /* np_can_frm_size_fixed is configured to TRUE                           */
    UI_16 cr_timer;             /* Maximum timeout measured in ms between Consecutive frames before      */
                                /* aborting the reception due to time out                                */
    UI_16 bs_timer;             /* Time in ms between the first frame and the firs flow control or       */
                                /* between the last consecutive frame of a block and the flow control    */
                                /* before aborting the transmission due to timeout                       */
    UI_16 stmin_timer;          /* Time in ms between consecutive frames of the transmitter to allow     */
                                /* ourself to process the received frames without losing anyone          */
                                /* If the block size if different from 1, this time must be minimum the  */
                                /* cycle frequency, otherwise if this is 1 the stmin could be 0          */
    UI_8 block_size;            /* Number of consecutive frames that the ECU will send without waiting   */
                                /* for a flow control before continuing. If the block size is set to 0   */
                                /* means that only one flow control is needed after receiving the first  */
                                /* frame                                                                 */
	UI_8 max_fc_wait;			/* Maximum FC wait that TP can handle in a row							 */
    UI_8 * tx_phy_buffer;       /* Pointer to the TX physical buffer. Must be declared with the size to  */
                                /* hold the maximum trasmission length                                   */
    UI_8 * rx_phy_buffer;       /* Pointer to the RX physical buffer. Must be declared with the size to  */
                                /* hold the maximum reception length                                     */
    UI_8 * rx_fun_buffer;       /* Pointer to the RX functional buffer. The size of the buffer must be 7 */
    t_can_handler can_handler;                 //ACF must be called OsekCom_Handler
    t_symbolic_name sig_np_rx_phy;              /* OSEKCOM signal to get the RX physical frame           */
    t_symbolic_name sig_np_tx_phy;              /* OSEKCOM signal to request the transmission of the TX  */
                                                /* physical frame                                        */
    t_symbolic_name sig_np_rx_fun;              /* OSEKCOM signal to get the RX functional frame         */
} t_tp_init;
    
/*--------------------------- GLOBAL VARIABLES --------------------------*/

/* Declaration of the tp_frm phisical structures. This structure is declared extern because will be the  */
/* input and output structure between the application and the ISO15765_2 transport protocol              */
extern t_tp_frm tp_frm[TP_NUM_INSTANCES];

/* Declaration of the tp_frm functional structures. This structure is declared extern because will be    */
/* the input and output structure between the application and the ISO15765_2 transport protocol          */
extern t_tp_fun_frm tp_fun_frm[TP_NUM_INSTANCES];

/*---------------------------- ROUTINE PROTOTYPES --------------------------*/

/*****************************************************************************
| Portability:  Generic
|----------------------------------------------------------------------------
| Functionalities Contract Description:
|  Routine to initialize one ISO15765_2 transport protocol instance. This
|  routine should be called once in the main initializations and will call
|  to the Iso15765_2_DynamicParametersInitCallback callback routine to 
|  configure dynamically the transport protocol instance with the parameters
|  needed by the application.
|  This routine should be called once for each ISO15765_2 instance defined.
|---------------------------------------------------------------------------
| Parameters Explanation:
|     tp_hdl: ISO15765_2 handler of the instance that will be initialized.
|---------------------------------------------------------------------------
| Timing:
| Tmax Int Dis:   ? CPU cycles | O(n): CTE 
| Tmax Int En :   ? CPU cycles | O(n): CTE 
| Tmax Total  :   ? CPU cycles | O(n): CTE 
/---------------------------------------------------------------------------*/
void InicialitzaTPTask(UI_8 tp_hdl);

/*****************************************************************************
| Portability:  Generic
|----------------------------------------------------------------------------
| Functionalities Contract Description:
|  Task that must be executed once in each main cycle and that will trigger
|  all the tasks needed to assure the transport protocol correct functionality.
|  This routine should be called once for each ISO15765_2 instance defined.
|---------------------------------------------------------------------------
| Parameters Explanation:
|     tp_hdl: ISO15765_2 handler to be used
|---------------------------------------------------------------------------
| Timing:
| Tmax Int Dis:   ? CPU cycles | O(n): CTE 
| Tmax Int En :   ? CPU cycles | O(n): CTE 
| Tmax Total  :   ? CPU cycles | O(n): CTE 
/---------------------------------------------------------------------------*/
void TPTask(UI_8 tp_hdl);

/*****************************************************************************
| Portability:  Generic
|----------------------------------------------------------------------------
| Functionalities Contract Description:
|  Routine to initialize an ISO15765_2 instance with the configuration 
|  parameters needed by the application.
|  This routine must be called from the callback routine in which the user
|  must configure the dynamic parameters that must be called 
|  TPDynamicParametersInitCallback
|---------------------------------------------------------------------------
| Parameters Explanation:
|     tp_hdl: ISO15765_2 handler to be used
|     init_data: ISO15765_2 configuration parameters to be taken by the 
|                given handler
|---------------------------------------------------------------------------
| Timing:
| Tmax Int Dis:   ? CPU cycles | O(n): CTE 
| Tmax Int En :   ? CPU cycles | O(n): CTE 
| Tmax Total  :   ? CPU cycles | O(n): CTE 
/---------------------------------------------------------------------------*/
void TPInitData(UI_8 tp_hdl, t_tp_init * init_data);

#ifdef ENABLE_INCREMENT_EXTERNAL_TIMERS
/*****************************************************************************
| Portability:  Generica
|----------------------------------------------------------------------------
| Functionalities Contract Description:
|  Routine to increment the timers used in the RX task. This routine should be called
|  in case of a known desviation of the main program cycle which the user know that
|  all the timers should be incremented additionally with a certain value.
|---------------------------------------------------------------------------
| Parameters Explanation:
|---------------------------------------------------------------------------
| Timing:
| Tmax Int Dis:   ? CPU cycles | O(n): CTE 
| Tmax Int En :   ? CPU cycles | O(n): CTE 
| Tmax Total  :   ? CPU cycles | O(n): CTE 
/---------------------------------------------------------------------------*/
void TPRxIncrTimers(UI_8 tp_hdl, UI_16 ticks);

/*****************************************************************************
| Portability:  Generica
|----------------------------------------------------------------------------
| Functionalities Contract Description:
|  Routine to increment the timers used in the TX task. This routine should be called
|  in case of a known desviation of the main program cycle which the user know that
|  all the timers should be incremented additionally with a certain value.
|---------------------------------------------------------------------------
| Parameters Explanation:
|---------------------------------------------------------------------------
| Timing:
| Tmax Int Dis:   ? CPU cycles | O(n): CTE 
| Tmax Int En :   ? CPU cycles | O(n): CTE 
| Tmax Total  :   ? CPU cycles | O(n): CTE 
/---------------------------------------------------------------------------*/
void TPTxIncrTimers(UI_8 tp_hdl, UI_16 ticks);
#endif /* #ifdef ENABLE_INCREMENT_EXTERNAL_TIMERS */

#endif
