/******************************************************************************
文 件 名：DoCAN_ISO15765.c
功能描述：ISO 15765 规范规定的诊断服务函数库文件
作    者：张暄
版    本：V1.0
日    期：2016.7.18
******************************************************************************/

#include "DoCAN_ISO15765.h"
#include "Application.h"
#include "can.h"

LinkRxFIFOStruct LinkRxFIFO;
LinkTxCtrlStruct LinkTxCtrl;

volatile TransportDataUnion TransportRxData;
volatile TransportDataUnion TransportTxData;

N_USDataRxStruct N_USDataRxBuffer;
N_USDataTxStruct N_USDataTxBuffer;

TransportControlStruct       TpCtrl;
TransportTimingControlStruct TpTimingCtrl;

uint8_t DiagnosticReceived;

extern void UDS_N_USData_Confirm(uint16_t N_TAtype, uint8_t N_Result);
extern void UDS_N_USData_FF_Indication(uint16_t N_TAtype, uint16_t Length);
extern void UDS_N_USData_Indication(uint16_t N_TAtype, uint8_t *MessageData, uint16_t Length, uint8_t N_Result);

/******************************************************************************
后台服务
******************************************************************************/
/******************************************************************************
函数名：DoCAN_Communication_Service
功  能：基于CAN总线的诊断通信服务后台控制函数
参  数：无
返回值：无
*******************************************************************************
注  意：该服务函数必须被实时调用
******************************************************************************/
void DoCAN_Communication_Service(void)
{
    DoCAN_Update_Timer( );
    DoCAN_Handle_Time_Out( );
    UDS_Server_Application_Service( );
    DoCAN_Receive_And_Assemble_N_USData( );
    DoCAN_Disassemble_And_Transmit_N_USData( );
}

/******************************************************************************
函数名：DoCAN_Timer_Update
功  能：更新定时器数值,用于时序控制以及STmin计时
参  数：Interval：定时器两次更新的时间间隔,单位us
返回值：无
*******************************************************************************
注  意：该服务函数必须被嵌入到定时中断中
******************************************************************************/
void DoCAN_Timer_Update(uint16_t Interval)
{
    TpTimingCtrl.Cnt += Interval;
}

/******************************************************************************
Services provided by network layer to higher layers
******************************************************************************/
/******************************************************************************
函数名：DoCAN_N_USData_Request
功  能：该服务函数用于请求传输数据
        This service is used to request the transfer of data. If necessary, the
        network layer segments the data.
参  数：N_TAtype    ：目标地址类型,发送数据请使用 DIAG_ID_Tx
        MessageData ：请求传输的数据
        Length      ：数据长度
返回值：无
******************************************************************************/
void DoCAN_N_USData_Request(uint16_t N_TAtype, uint8_t *MessageData, uint16_t Length)
{
    uint8_t i;

    // 非空闲状态下不允许发送
    if ( TpCtrl.Process != TP_IDLE )
    {
        DoCAN_N_USData_Confirm(N_TAtype, N_ERROR);
        return;
    }

    if ( (Length == 0) || (Length > N_USDATA_TX_BUFFER_SIZE) )    // 非法的长度
    {
        DoCAN_N_USData_Confirm(N_TAtype, N_ERROR);
        return;
    }

    // 将数据缓存到发送Buffer中
    N_USDataTxBuffer.N_TAtype = N_TAtype;
    N_USDataTxBuffer.Length   = Length;

    for ( i = 0; i < Length; i++ )
    {
        N_USDataTxBuffer.MsgData [ i ] = *MessageData;
        MessageData++;
    }

    // 更新传输层状态
    TpCtrl.NonStopMode = 0;
    TpCtrl.TotalLen    = Length;    // 记录字节总数
    TpCtrl.BSMax       = 0xFF;      // 初始化BSMax数值
    TpCtrl.STmin       = 0x7F;

    // 拆分为N_PDU
    if ( TpCtrl.TotalLen < 8 )    // 数据总长度小于8,采用单帧发送
    {
        TpCtrl.BlockSize = 1;                  // 单帧,Block总数为1
        TpCtrl.Len       = TpCtrl.TotalLen;    // 单帧发出全部的数据
        TpCtrl.BlockCnt  = 1;                  // 记录已发送Block数

        TransportTxData.N_PDU_SF.N_TAtype    = N_USDataTxBuffer.N_TAtype;
        TransportTxData.N_PDU_SF.N_PCI.Type  = SINGLE_FRAME;
        TransportTxData.N_PDU_SF.N_PCI.SF_DL = ( uint8_t )(TpCtrl.TotalLen);
        TransportTxData.N_PDU_SF.DLC         = ( uint8_t )(TpCtrl.TotalLen) + 1;

        for ( i = 0; i < TpCtrl.TotalLen; i++ )
            TransportTxData.N_PDU_SF.N_Data [ i ] = N_USDataTxBuffer.MsgData [ i ];
    }
    else    // 数据总长度大于等于8,采用多帧发送,首先发送首帧
    {
        if ( (Length + 1) % 7 )                     // 计算BlockSize
            TpCtrl.BlockSize = (Length + 8) / 7;    // 等效于(Length + 1) / 7 + 1
        else
            TpCtrl.BlockSize = (Length + 1) / 7;
        TpCtrl.Len      = 6;    // 首帧发出数据长度为6
        TpCtrl.BlockCnt = 1;    // 记录已发送Block数

        TransportTxData.N_PDU_FF.N_TAtype      = N_USDataTxBuffer.N_TAtype;
        TransportTxData.N_PDU_FF.N_PCI.Type    = FIRST_FRAME;
        TransportTxData.N_PDU_FF.N_PCI.FF_DL_H = ( uint8_t )((TpCtrl.TotalLen >> 8) & 0x000F);
        TransportTxData.N_PDU_FF.N_PCI.FF_DL_L = ( uint8_t )(TpCtrl.TotalLen & 0x00FF);
        TransportTxData.N_PDU_FF.DLC           = 8;

        for ( i = 0; i < 6; i++ )
            TransportTxData.N_PDU_FF.N_Data [ i ] = N_USDataTxBuffer.MsgData [ i ];
    }

    DoCAN_Start_Timer(TIMING_PARA_N_As);    // 启动N_As计时

    DoCAN_L_Data_Request(TransportTxData.Frame.Identifier, TransportTxData.Frame.DLC, ( uint8_t * )TransportTxData.Frame.Data);
    TpCtrl.Process = TP_TX_INIT;    // 数据帧已发出,等待发送完成
    DoCAN_L_Data_Confirm(TransportTxData.Frame.Identifier, COMPLETE);
}

/******************************************************************************
函数名：DoCAN_N_USData_Confirm
功  能：该服务函数由网络层发起,用于确认前一次使用N_USData.request服务向
        N_TAtype地址发送的数据是否发送完成
        The N_USData.confirm service is issued by the network layer. The service
        primitive confirms the completion of an N_USData.request service
        identified by the address information in N_TAtype.
参  数：N_TAtype ：N_USData.confirm服务请求的发送地址
        N_Result ：N_USData.request服务的传输状态
返回值：无
******************************************************************************/
void DoCAN_N_USData_Confirm(uint16_t N_TAtype, N_ResultEnum N_Result)
{
    UDS_N_USData_Confirm(N_TAtype, N_Result);
}

/******************************************************************************
函数名：DoCAN_N_USData_FF_Indication
功  能：该服务函数由网络层发起,用于向上层指示地址为N_TAtype的一组多帧数据的首帧
        的到来
        The N_USData_FF.indication service is issued by the network layer. The
        service primitive indicates to the adjacent upper layer the arrival of
        a FirstFrame (FF) of a segmented message received from a peer protocol
        entity, identified by the address information N_TAtype.
参  数：N_TAtype ：新到的多帧数据首帧的地址信息
        Length   ：新到的多帧数据的总长度
返回值：无
******************************************************************************/
void DoCAN_N_USData_FF_Indication(uint16_t N_TAtype, uint16_t Length)
{
    UDS_N_USData_FF_Indication(N_TAtype, Length);
}

/******************************************************************************
函数名：DoCAN_N_USData_Indication
功  能：该服务函数由网络层发起,用于向上层指出由N_TAtype地址发送来的长度为Length
        的MessageData数据的传送结果N_Result,并同时传递这一数据
        The N_USData.indication service is issued by the network layer. The
        service primitive indicates <N_Result> events and delivers
        <MessageData> with <Length> bytes received from a peer protocol entity
        identified by the address information in N_TAtype to the adjacent upper
        layer.
参  数：N_TAtype    ：接收到的数据地址信息
        MessageData ：接收到的数据      (仅在N_Result为N_OK时有效)
        Length      ：接收到的数据长度  (仅在N_Result为N_OK时有效)
        N_Result    ：数据的接收结果
返回值：无
******************************************************************************/
void DoCAN_N_USData_Indication(uint16_t N_TAtype, uint8_t *MessageData, uint16_t Length, N_ResultEnum N_Result)
{
    UDS_N_USData_Indication(N_TAtype, MessageData, Length, N_Result);
}

/******************************************************************************
下层接口函数
******************************************************************************/

/******************************************************************************
函数名：DoCAN_L_Data_Request
功  能：该服务原语请求向<Identifier>传输特定格式的<Data>数据
        The service primitive requests transmission of <Data> that shall be
        mapped within specific attributes of the data link protocol data unit
        selected by means of <Identifier>.
参  数：Identifier ：报文ID
        dlc        ：数据长度
        Data       ：数据<Data>于数据链路层的存放地址
返回值：无
******************************************************************************/


void DoCAN_L_Data_Request(uint16_t Identifier, uint8_t dlc, uint8_t *Data)
{
    uint8_t i;
    CanTxRxMsg msg_diag_tx;
    LinkTxCtrl.Identifier = Identifier;

    for ( i = 0; i < dlc; i++ )
    {
        LinkTxCtrl.Data[i] = *Data;
        Data++;
    }
 
    for ( i = dlc; i < 8; i++ )
        LinkTxCtrl.Data[i] = FILLER_BYTE;

        msg_diag_tx.Id = LinkTxCtrl.Identifier;
        msg_diag_tx.DLC = 8;
        msg_diag_tx.RTR = 0;
        msg_diag_tx.IDE = 0;
        msg_diag_tx.CacheType = CAN_CacheType_Tx;
        for(i =0;i<8;i++)
        {
          msg_diag_tx.Data[i] =  LinkTxCtrl.Data[i] ;
        }

        CAN_Transmit(CAN0MSG09, &msg_diag_tx);
        // Can_Write(&msg);
    //CANFD_Ch1_L_Data_Request(LinkTxCtrl.Identifier,8,LinkTxCtrl.Data);
    LinkTxCtrl.Busy  = 1;
}

/******************************************************************************
函数名：DoCAN_L_Data_Confirm
功  能：该服务原语用于确认具有特定<Identifier>的报文是否发送完成。
        <TransferStatus>参数用于传递发送完成与否的状态。
        The service primitive confirms the completion of an L_Data.request
        service for a specific <Identifier>.The parameter <TransferStatus>
        provides the status of the service request.
参  数：Identifier     ：报文ID
        TransferStatus ：Not_Complete - 未完成
                         Complete     - 已发送完成
返回值：无
******************************************************************************/
void DoCAN_L_Data_Confirm(uint16_t Identifier, uint8_t TransferStatus)
{
    // 如果数据发送成功,收发状态相应改变
    if ( (LinkTxCtrl.Identifier == Identifier) && (TransferStatus == COMPLETE) )
    {
        switch ( TpCtrl.Process )
        {
            case TP_TX_INIT:
                if ( TpCtrl.BlockSize == 1 )    // BlockSize为1,单帧发送成功
                {
                    TpCtrl.Process = TP_IDLE;    // 所有数据发送完毕,回到空闲状态
                    DoCAN_Stop_Timer( );         // 停止计时
                    DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_OK);
                }
                else    // BlockSize不为1,首帧发送成功
                {
                    DoCAN_Start_Timer(TIMING_PARA_N_Bs);    // 启动N_Bs计时
                    TpCtrl.Process = TP_TX_RTS;             // 等待接收机许可多帧发送
                }
                break;

            case TP_TX_CTS:
                if ( TpCtrl.BlockCnt == TpCtrl.BlockSize )    // 最后一帧发送完成
                {
                    TpCtrl.Process = TP_IDLE;    // 所有数据发送完毕,回到空闲状态
                    DoCAN_Stop_Timer( );         // 停止计时
                    // DoCAN_Start_Timer(TIMING_PARA_N_Bs);
                    DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_OK);
                }
                else
                {
                    // DoCAN_Start_Timer ( TIMING_PARA_N_Bs ); //启动/重启N_Bs计时
                    if ( TpCtrl.BSMax )    // 还可以继续发送数据帧,则启动STmin计时
                    {
                        DoCAN_Stop_Timer( );
                        DoCAN_Start_STmin_Timer(TpCtrl.STmin);
                    }
                    else
                    {
                        DoCAN_Start_Timer(TIMING_PARA_N_Bs);
                    }
                }
                break;

            case TP_RX_RTS:
                DoCAN_Start_Timer(TIMING_PARA_N_Cr);    // 启动N_Cr计时
                TpCtrl.Process = TP_RX_CTS;
                break;

            case TP_RX_WAIT:
                DoCAN_Start_Timer(TIMING_PARA_N_Cr);    // 启动N_Cr计时
                TpCtrl.Process = TP_RX_CTS;
                break;

            case TP_RX_OVFL:
                TpCtrl.Process = TP_IDLE;    // 停止接收过程
                DoCAN_Stop_Timer( );         // 停止计时
                DoCAN_N_USData_Indication(N_USDataRxBuffer.N_TAtype, N_USDataRxBuffer.MsgData,
                                          N_USDataRxBuffer.Length, N_ERROR);
                break;

            default:
                break;
        }
    }
}

/******************************************************************************
函数名：DoCAN_L_Data_Indication
功  能：该服务原语标示一个数据链路层事件到相邻上层并根据<Identifier>传送<Data>
        The service primitive indicates a data link layer event to the adjacent
        upper layer and delivers <Data> identified by <Identifier>
参  数：Identifier ：报文ID
        dlc        ：数据长度
        pData      ：数据<Data>于数据链路层的存放地址
返回值：无
******************************************************************************/
void DoCAN_L_Data_Indication(uint16_t Identifier, uint32_t dlc, uint8_t *pData)
{
    uint8_t i;

    if ( LinkRxFIFO.Depth >= LINK_RX_FIFO_MAX_DEPTH )    // FIFO未满时装入报文,否则抛弃报文
    {
#if DOCAN_DEBUG_EN
        LINK_RX_FIFO_OVERFLOW_INDICATOR( );
#endif
        return;
    }

    LinkRxFIFO.LinkData [ LinkRxFIFO.IPtr ].Identifier = Identifier;    // 装入报文ID
    for ( i = 0; i < dlc; i++ )                                         // 拷贝报文
        LinkRxFIFO.LinkData [ LinkRxFIFO.IPtr ].Data [ i ] = *(pData + i);
    LinkRxFIFO.LinkData [ LinkRxFIFO.IPtr ].DLC = dlc;    // 保存报文长度

    LinkRxFIFO.Depth++;    // 新报文装入,深度+1
    LinkRxFIFO.IPtr++;     // 输入指针+1
    if ( LinkRxFIFO.IPtr >= LINK_RX_FIFO_MAX_DEPTH )
        LinkRxFIFO.IPtr = 0;
}

/******************************************************************************
传输层协议解析
******************************************************************************/

/******************************************************************************
函数名：DoCAN_Receive_And_Assemble_N_USData();
功  能：接收N_PDU并重组数据
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Receive_And_Assemble_N_USData(void)
{
    DoCAN_Get_N_PDU( );

    if ( TransportRxData.N_PDU.New )
    {
        switch ( TransportRxData.N_PDU.N_PCI.Type )
        {
            case SINGLE_FRAME:
                DoCAN_Receive_Single_Frame_N_Data( );
                break;

            case FIRST_FRAME:
                DoCAN_Receive_First_Frame_N_Data( );
                DoCAN_Transmit_Flow_Control( );    // 首帧发送完毕后必须发送流控帧
                break;

            case CONSECUTIVE_FRAME:
                DoCAN_Receive_Consecutive_Frame_N_Data( );
                DoCAN_Transmit_Flow_Control( );    // 当接收满一个BlockSize时,需要发送流控帧
                break;

            case FLOW_CONTROL:
                DoCAN_Receive_Flow_Control( );
                break;

            default:
                DoCAN_Handle_Unknown_N_PDU( );
                break;
        }
        TransportRxData.N_PDU_FC.New = 0;
    }
}

/******************************************************************************
函数名：DoCAN_Get_N_PDU
功  能：从数据链路层获取N_PDU(network protocol data unit)
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Get_N_PDU(void)
{
    uint8_t i;

    if ( LinkRxFIFO.Depth )    // FIFO中有数据
    {
        TransportRxData.Frame.Identifier = LinkRxFIFO.LinkData [ LinkRxFIFO.OPtr ].Identifier;    // 取出ID
        for ( i = 0; i < 8; i++ )                                                                 // 拷贝报文
            TransportRxData.Frame.Data [ i ] = LinkRxFIFO.LinkData [ LinkRxFIFO.OPtr ].Data [ i ];
        TransportRxData.Frame.DLC = LinkRxFIFO.LinkData [ LinkRxFIFO.OPtr ].DLC;    // 取出报文长度
        TransportRxData.Frame.New = 1;

        LinkRxFIFO.Depth--;    // 报文已取出,深度-1
        LinkRxFIFO.OPtr++;     // 输出指针+1
        if ( LinkRxFIFO.OPtr >= LINK_RX_FIFO_MAX_DEPTH )
            LinkRxFIFO.OPtr = 0;
    }
}

/******************************************************************************
函数名：DoCAN_Receive_Single_Frame_N_Data
功  能：单帧数据接收
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Receive_Single_Frame_N_Data(void)
{
    uint8_t i;

    if ( (TpCtrl.Process & TP_DIR_MASK) == TP_TX )    // 发送中不接收
        return;

    /*---------------------------------------------------------------------------
    Whether the interleaving Tester Present messages would lead to a loss of CF
    or termination of the reception of an ongoing multiple frame request
    2018.11.29
    ---------------------------------------------------------------------------*/
    if ( (TpCtrl.Process != TP_IDLE) && (TransportRxData.N_PDU_SF.N_TAtype != DIAG_ID_Rx_PHY) )
        return;

    /*---------------------------------------------------------------------------
    Tester sends a Single frame with a CAN-DLC shorter and equal to the transport
    protocol data length field. ECU must not send a response.
    2018.11.28添加长度还要等于8
    ---------------------------------------------------------------------------*/
    if ( (TransportRxData.N_PDU_SF.DLC <= TransportRxData.N_PDU_SF.N_PCI.SF_DL) || (TransportRxData.N_PDU_SF.DLC != 8) )
        return;

    /*---------------------------------------------------------------------------
    Tester sends a Single frame with a data length that is not allowed by the
    protocol. ECU must not send a response.
    ---------------------------------------------------------------------------*/
    if ( (TransportRxData.N_PDU_SF.N_PCI.SF_DL == 0) || (TransportRxData.N_PDU_SF.N_PCI.SF_DL > 7) )
        return;

    N_USDataRxBuffer.N_TAtype = TransportRxData.N_PDU_SF.N_TAtype;
    N_USDataRxBuffer.Length   = TransportRxData.N_PDU_SF.N_PCI.SF_DL;
    for ( i = 0; i < N_USDataRxBuffer.Length; i++ )
        N_USDataRxBuffer.MsgData [ i ] = TransportRxData.N_PDU_SF.N_Data [ i ];

    TpCtrl.Process = TP_IDLE;    // 接收完成,回到IDLE状态
    DoCAN_Stop_Timer( );
    DoCAN_N_USData_Indication(N_USDataRxBuffer.N_TAtype, N_USDataRxBuffer.MsgData,
                              N_USDataRxBuffer.Length, N_OK);
}

/******************************************************************************
函数名：DoCAN_Receive_First_Frame_N_Data
功  能：接收首帧数据并初始化多帧数据接收
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Receive_First_Frame_N_Data(void)
{
    uint8_t  i;
    uint16_t Len;

    if ( (TpCtrl.Process & TP_DIR_MASK) == TP_TX )    // 发送中不接收
        return;

    /*-----------------------------------------------------------------------------
    Tester sends a functional addressed First frame. ECU must not send a response.
    -----------------------------------------------------------------------------*/
    if ( TransportRxData.N_PDU_FF.N_TAtype != DIAG_ID_Rx_PHY )
        return;

    /*---------------------------------------------------------------------------
    (8.3) A FirstFrame protocol data unit (FF N_PDU), containing the first six
    data bytes
    ---------------------------------------------------------------------------*/
    if ( TransportRxData.N_PDU_FF.DLC != 8 )    // 首帧总长(N_PCI + N_Data)应为8
        return;

    /*---------------------------------------------------------------------------
    Tester sends a First frame with Data length set to 0. ECU must not send a
    response.
    -----------------------------------------------------------------------------
    (8.5.3.3) If the network layer receives an FF with an FF_DL that is less than
    eight when using normal addressing, then the network layer shall ignore the
    received FF N_PDU and not transmit an FC N_PDU.
    ---------------------------------------------------------------------------*/
    Len = ( uint16_t )(TransportRxData.N_PDU_FF.N_PCI.FF_DL_H);
    Len <<= 8;
    Len |= ( uint16_t )(TransportRxData.N_PDU_FF.N_PCI.FF_DL_L);

    if ( Len < 8 )
        return;

        /*---------------------------------------------------------------------------
        Tester sends a First frame of a segmented request. After the receipt of the
        ECU Flow Control the Tester sends another segmented request. The ECU must
        send a response for the second request.
        ---------------------------------------------------------------------------*/
#if ( N_MAX_BS )
    TpCtrl.NonStopMode = 0;
#else
    TpCtrl.NonStopMode = 1;
#endif

    TpCtrl.Len      = 6;           // 首帧接收6字节
    TpCtrl.TotalLen = Len;         // 记录字节总数
    TpCtrl.BlockCnt = 1;           // 首帧接收1个block
    TpCtrl.BSMax    = N_MAX_BS;    // 装入最大的BS数
    TpCtrl.WFTCnt   = N_WFTmax;    // 装入最大等待次数

    // 首帧含6字节数据,连续帧含7字节数据,根据字节数计算Block总数
    if ( (TpCtrl.TotalLen + 1) % 7 )
        TpCtrl.BlockSize = (TpCtrl.TotalLen + 8) / 7;    // 等效于(TpCtrl.TotalLen + 1) / 7 + 1
    else
        TpCtrl.BlockSize = (TpCtrl.TotalLen + 1) / 7;

    // 开始接收首帧数据
    N_USDataRxBuffer.N_TAtype = TransportRxData.N_PDU_FF.N_TAtype;
    N_USDataRxBuffer.Length   = Len;
    for ( i = 0; i < 6; i++ )
        N_USDataRxBuffer.MsgData [ i ] = TransportRxData.N_PDU_FF.N_Data [ i ];

    DoCAN_Start_Timer(TIMING_PARA_N_Br);    // 启动N_Br计时
    TpCtrl.Process = TP_RX_INIT;
    DoCAN_N_USData_FF_Indication(N_USDataRxBuffer.N_TAtype, N_USDataRxBuffer.Length);
}

/******************************************************************************
函数名：DoCAN_Receive_Consecutive_Frame_N_Data
功  能：接收连接帧数据
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Receive_Consecutive_Frame_N_Data(void)
{
    uint8_t i;

    /*---------------------------------------------------------------------------
    Tester sends a request with a response that is longer than one frame. After
    the Flow control the Tester sends a Consecutive frame. ECU must send a
    diagnostic response for the first request. ECU must not send a response
    for the Consecutive frame.
    -----------------------------------------------------------------------------
    Tester sends a single Consecutive frame. The ECU must not send a response.
    ---------------------------------------------------------------------------*/
    if ( TpCtrl.Process != TP_RX_CTS )
        return;

    if ( TransportRxData.N_PDU_CF.N_TAtype != DIAG_ID_Rx_PHY )
        return;

    /*---------------------------------------------------------------------------
    Send a request which requires more than 4 frames. Drop the third consecutive
    frame (CF). The ECU should not respond.
    -----------------------------------------------------------------------------
    Send a multi frame message to the ECU. Send the first consecutive frame (CF)
    twice. No response is expected.
    ---------------------------------------------------------------------------*/
    if ( TransportRxData.N_PDU_CF.N_PCI.SN != ( uint8_t )(TpCtrl.BlockCnt & 0x000F) )
    {
        TpCtrl.Process = TP_IDLE;    // 停止接收过程
        DoCAN_Stop_Timer( );         // 停止计时
        DoCAN_N_USData_Indication(N_USDataRxBuffer.N_TAtype, N_USDataRxBuffer.MsgData,
                                  N_USDataRxBuffer.Length, N_WRONG_SN);
        return;
    }

    TpCtrl.BlockCnt++;    // 接收到1个Block
    TpCtrl.BSMax--;

    if ( TpCtrl.BlockCnt < TpCtrl.BlockSize )    // 此次接收不是最后一帧
    {
        if ( TransportRxData.N_PDU_CF.DLC != 8 )    // 此时连续帧总长(N_PCI + N_Data)应为8
            return;

        for ( i = 0; i < 7; i++ )
        {
            N_USDataRxBuffer.MsgData [ TpCtrl.Len ] = TransportRxData.N_PDU_CF.N_Data [ i ];
            TpCtrl.Len++;
        }

        DoCAN_Start_Timer(TIMING_PARA_N_Cr);    // 重启N_Cr计时
    }
    else    // 此次接收是最后一帧
    {
        /*-------------------------------------------------------------------------
        In a segmented request the Tester sends a Consecutive frame with a CAN-DLC
        shorter or equal to transport protocol data length field. ECU must not send
        a response.
        -------------------------------------------------------------------------*/
        if ( (TransportRxData.N_PDU_CF.DLC <= TpCtrl.TotalLen - TpCtrl.Len) || (TransportRxData.N_PDU_CF.DLC != 8) )    // 此时连续帧总长应不小于剩余数据长度
            return;

        i = 0;
        while ( TpCtrl.Len < TpCtrl.TotalLen )
        {
            N_USDataRxBuffer.MsgData [ TpCtrl.Len ] = TransportRxData.N_PDU_CF.N_Data [ i ];
            i++;
            TpCtrl.Len++;
        }

        TpCtrl.Process = TP_IDLE;    // 接收完成,回到IDLE状态
        DoCAN_Stop_Timer( );
        DoCAN_N_USData_Indication(N_USDataRxBuffer.N_TAtype, N_USDataRxBuffer.MsgData,
                                  N_USDataRxBuffer.Length, N_OK);
    }
}

/******************************************************************************
函数名：DoCAN_Receive_Flow_Control
功  能：接收流控帧数据
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Receive_Flow_Control(void)
{
    /*--------------------------------------------------------------------------
    Tester sends a segmented request interrupted by a Flow control after the ECU
    Flow control. After that the Tester sends the remaining consecutive frames.
    ECU should send a diagnostic response for the request.
    -----------------------------------------------------------------------------
    Tester sends a single Flow Control. The ECU must not send a response.
    ---------------------------------------------------------------------------*/
    if ( (TpCtrl.Process != TP_TX_RTS) && (TpCtrl.Process != TP_TX_CTS) && (TpCtrl.Process != TP_TX_WAIT) )
        return;

    /*---------------------------------------------------------------------------
    Tester sends a request with a response that is longer than one frame. After
    the First frame is received the Tester sends a functional addressed Flow
    control. ECU must abort sending of the response.
    ---------------------------------------------------------------------------*/
    if ( TransportRxData.N_PDU_FC.N_TAtype != DIAG_ID_Rx_PHY )
    {
        DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_ERROR);
        DoCAN_Stop_Timer( );         // 停止计时
        TpCtrl.Process = TP_IDLE;    // 中止数据发送,回到空闲状态
        return;
    }

    /*---------------------------------------------------------------------------
    Tester sends a Flow control with a too short CAN-DLC for a response that is
    longer than one frame. ECU must not send Consecutive frames. After that the
    tester sends a new request. ECU must send a response for the last request.
    ---------------------------------------------------------------------------*/
    if ( TransportRxData.N_PDU_FC.DLC != 8 )
    {
        DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_ERROR);
        DoCAN_Stop_Timer( );         // 停止计时
        TpCtrl.Process = TP_IDLE;    // 中止数据发送,回到空闲状态
        return;
    }

    switch ( TransportRxData.N_PDU_FC.N_PCI.FS )
    {
        case FC_FS_CTS:
            if ( TpCtrl.NonStopMode )
                break;

            /*-------------------------------------------------------
            Tester sends a Flow control with Blocksize 0 for a
            response that is longer than one frame. ECU must send the
            complete response.
            ---------------------------------------------------------
            Tester sends a Flow control with Blocksize 0 for a
            response that is longer than one frame. ECU must send the
            complete response without waiting for another Flow
            control. Tester verifies that every Consecutive frame is
            received within TimeoutCr.
            -------------------------------------------------------*/
            if ( TransportRxData.N_PDU_FC.N_PCI.BS == 0 )
                TpCtrl.NonStopMode = 1;

            /*-------------------------------------------------------
            Tester sends a Flow control with a special Blocksize for
            a response that is longer than one frame. ECU must send
            the number of Consecutive frames that matches the
            blocksize. Blocksize 1, 8 and 20 is checked if the
            response is long enough.
            -------------------------------------------------------*/
            else
                TpCtrl.BSMax = TransportRxData.N_PDU_FC.N_PCI.BS;

            /*-------------------------------------------------------
            Tester sends a Flow control for a response that is longer
            than one frame. ECU must send the complete response.
            Tester verifies that the time between the Consecutive
            Frames is not below STMin time. This is tested for STMin
            values 1,10,20,30,40,50 and 60.
            -------------------------------------------------------*/
            if ( TpCtrl.Process != TP_TX_CTS )
            {
                if(TransportRxData.N_PDU_FC.N_PCI.STmin == 0)
                {
                    TpCtrl.STmin = 1;
                }
                else
                {
                    TpCtrl.STmin = TransportRxData.N_PDU_FC.N_PCI.STmin;
                }
            }

            /*-------------------------------------------------------
            Request a service where the response requires more than
            one response frame. Tester sends two Flow Controls (FC)
            instead of one. A response from the ECU is expected.
            -------------------------------------------------------*/
            TpCtrl.Process = TP_TX_CTS;    // 发送机被许可发送
            DoCAN_Stop_Timer( );
            DoCAN_Start_STmin_Timer(TpCtrl.STmin);    // 启动STmin计时
            break;

        case FC_FS_WAIT:
            if ( TpCtrl.NonStopMode )
                break;

            /*-------------------------------------------------------
            Tester sends a Flow control with Status value wait (WT)
            for a response that is longer than one frame. ECU must
            not send Consecutive frames. After the N_Bs Timeout the
            Tester sends another Flow control with status continue to
            send (CTS). Then the tester sends a new request. ECU must
            send a response for the last request.
            -------------------------------------------------------*/
            TpCtrl.Process = TP_TX_WAIT;            // 接收机请求发送机等待
            DoCAN_Start_Timer(TIMING_PARA_N_Bs);    // 启动/重启N_Bs计时
            break;

        case FC_FS_OVFL:
            if ( TpCtrl.NonStopMode )
                break;

            /*-------------------------------------------------------
            Tester sends a Flow control with status overflow for a
            response that is longer than one frame. ECU must not send
            Consecutive frame(s).
            ---------------------------------------------------------
            Tester sends a request with a response that is longer
            than one frame. After sending the Flow control the Tester
            receives the first Consecutive frame and sends another
            Flow control with status overflow (OVFLW). ECU must send
            a diagnostic response for the first request. ECU must not
            send a response for the Flow control.
            -------------------------------------------------------*/
            if ( TpCtrl.Process == TP_TX_RTS )
            {
                DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_BUFFER_OVFLW);
                DoCAN_Stop_Timer( );         // 停止计时
                TpCtrl.Process = TP_IDLE;    // 中止数据发送,回到空闲状态
            }
            break;

        default: /*-------------------------------------------------------
             Tester sends a Flow control with an invalid Status value
             (3-15) for a response that is longer than one frame. ECU
             must not send a response.
             -------------------------------------------------------*/
            DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_INVALID_FS);
            DoCAN_Stop_Timer( );         // 停止计时
            TpCtrl.Process = TP_IDLE;    // 中止数据发送,回到空闲状态
            break;
    }
}

/******************************************************************************
函数名：DoCAN_Transmit_Flow_Control
功  能：根据当前的接收机状态发送流控帧
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Transmit_Flow_Control(void)
{
    if ( TpCtrl.Process == TP_RX_INIT )
    {
        /*-------------------------------------------------------------------------
        (8.5.3.3) If the network layer receives an FF with an FF_DL that is greater
        than the available receiver buffer size, then this shall be considered as
        an error condition. The network layer shall abort the message reception and
        send an FC N_PDU with the parameter FlowStatus = Overflow.
        -------------------------------------------------------------------------*/
        if ( N_USDataRxBuffer.Length > N_USDATA_RX_BUFFER_SIZE )
        {
            TransportTxData.N_PDU_FC.N_PCI.FS = FC_FS_OVFL;
            TpCtrl.Process                    = TP_RX_OVFL;
        }
        else
        {
            TransportTxData.N_PDU_FC.N_PCI.FS = FC_FS_CTS;
            TpCtrl.Process                    = TP_RX_RTS;
        }
    }
    else if ( TpCtrl.Process == TP_RX_CTS )
    {
        if ( TpCtrl.BSMax )    // 仍然没有接收满一个BS的N_PDU
            return;

        if ( TpCtrl.NonStopMode )    // 如果是连续接收模式(BS本来就是0)
            return;

        /*
        if (0)                        //如果满足等待条件,则发送等待FC帧
        {
          if(TpCtrl.WFTCnt == 0)
          {
            TpCtrl.Process = TP_IDLE;
            DoCAN_Stop_Timer();
            DoCAN_N_USData_Indication(N_USDataRxBuffer.N_TAtype, N_USDataRxBuffer.MsgData, \
                                      N_USDataRxBuffer.Length, N_WFT_OVRN);
            return;
          }

          TpCtrl.WFTCnt--;
          TransportTxData.N_PDU_FC.N_PCI.FS = FC_FS_WAIT;
        }*/

        TpCtrl.BSMax                      = N_MAX_BS;    // 重新装入最大的BS数
        TransportTxData.N_PDU_FC.N_PCI.FS = FC_FS_CTS;
        TpCtrl.Process                    = TP_RX_RTS;    // 等待RTS发送完成
    }
    else
        return;

    TransportTxData.N_PDU_FC.N_TAtype   = DIAG_ID_Tx;
    TransportTxData.N_PDU_FC.N_PCI.Type = FLOW_CONTROL;
    TransportTxData.N_PDU_FC.N_PCI.BS   = 0;
    /*---------------------------------------------------------------------------
    Tester sends a segmented request to check for a valid STMin time in the ECU
    Flow control. The STMin time value must be within 0x01-0x7F or 0xF1-0xF9.
    ---------------------------------------------------------------------------*/
    TransportTxData.N_PDU_FC.N_PCI.STmin = N_STmin;
    TransportTxData.N_PDU_FC.DLC         = 3;

    DoCAN_Start_Timer(TIMING_PARA_N_Ar);    // 启动N_Ar计时
    DoCAN_L_Data_Request(TransportTxData.Frame.Identifier, TransportTxData.Frame.DLC, ( uint8_t * )TransportTxData.Frame.Data);
    DoCAN_L_Data_Confirm(TransportTxData.Frame.Identifier, COMPLETE);
}

/******************************************************************************
函数名：DoCAN_Handle_Unknown_N_PDU
功  能：处理接收到的未知类型的N_PDU
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Handle_Unknown_N_PDU(void)
{
}

/******************************************************************************
函数名：DoCAN_Disassemble_And_Transmit_N_USData
功  能：将数据拆分为连续帧(CF)并发送出去
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Disassemble_And_Transmit_N_USData(void)
{
    uint8_t i;
    uint8_t Len;

    if ( TpCtrl.Process != TP_TX_CTS )    // 未被许可时不可以发送连续帧
        return;

    // 仅在STmin计时时间到后发送一次
    if ( DoCAN_Get_STmin_Timer_Status( ) == STmin_TIME_UP )
    {
        TransportTxData.N_PDU_CF.N_TAtype   = N_USDataTxBuffer.N_TAtype;
        TransportTxData.N_PDU_CF.N_PCI.Type = CONSECUTIVE_FRAME;
        TransportTxData.N_PDU_CF.N_PCI.SN   = ( uint8_t )(TpCtrl.BlockCnt & 0x000F);

        // 当BSMax减小到0时,链路层数据发送完毕后,将不会再启动STmin计数器(详情见DoCAN_L_Data_Confirm函数）
        // 因此STmin_TIME_UP状态将不会再出现,从而停止了连续帧的发送
        // 直到有新的CF帧到来给BSMax赋予新值,或N_Bs计时超时
        TpCtrl.BSMax--;
        TpCtrl.BlockCnt++;

        if ( TpCtrl.BlockCnt < TpCtrl.BlockSize )    // 将要发送的不是最后一帧
        {
            TransportTxData.N_PDU_CF.DLC = 8;
            for ( i = 0; i < 7; i++ )
            {
                TransportTxData.N_PDU_CF.N_Data [ i ] = N_USDataTxBuffer.MsgData [ TpCtrl.Len ];
                TpCtrl.Len++;
            }
        }
        else if ( TpCtrl.BlockCnt == TpCtrl.BlockSize )    // 将要发送最后一帧
        {
            Len = ( uint8_t )(TpCtrl.TotalLen - TpCtrl.Len);

            TransportTxData.N_PDU_CF.DLC = Len + 1;
            for ( i = 0; i < Len; i++ )
            {
                TransportTxData.N_PDU_CF.N_Data [ i ] = N_USDataTxBuffer.MsgData [ TpCtrl.Len ];
                TpCtrl.Len++;
            }
        }
        else    // 已发送帧数不可能大于帧总数,除非有错误发生
        {
            DoCAN_Stop_Timer( );         // 停止计时
            TpCtrl.Process = TP_IDLE;    // 中止数据发送,回到空闲状态
            DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_ERROR);
            return;
        }

        DoCAN_Start_Timer(TIMING_PARA_N_As);    // 启动N_As计时
        DoCAN_L_Data_Request(TransportTxData.Frame.Identifier, TransportTxData.Frame.DLC, ( uint8_t * )TransportTxData.Frame.Data);
        DoCAN_L_Data_Confirm(TransportTxData.Frame.Identifier, COMPLETE);
    }
}

/******************************************************************************
传输层时序管理
******************************************************************************/
/******************************************************************************
函数名：DoCAN_Update_Timer
功  能：定时器更新函数
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Update_Timer(void)
{
    uint16_t CurrentCnt;
    uint16_t Dec;

    CurrentCnt = TpTimingCtrl.Cnt;
    if ( CurrentCnt != TpTimingCtrl.LastCnt )    // 定时器计数值有更新
    {
        if ( CurrentCnt > TpTimingCtrl.LastCnt )
            Dec = CurrentCnt - TpTimingCtrl.LastCnt;
        else
            Dec = 65535 - TpTimingCtrl.LastCnt + 1 + CurrentCnt;

        TpTimingCtrl.LastCnt = CurrentCnt;

        if ( TpTimingCtrl.Type != TIMING_PARA_NONE )
        {
            if ( TpTimingCtrl.NTimer )
            {
                if ( TpTimingCtrl.NTimer > ( uint32_t )Dec )
                    TpTimingCtrl.NTimer -= Dec;
                else
                    TpTimingCtrl.NTimer = 0;
            }
        }

        if ( TpTimingCtrl.STminStatus == STmin_TIMING )
        {
            if ( TpTimingCtrl.STimer )
            {
                if ( TpTimingCtrl.STimer > ( uint32_t )Dec )
                    TpTimingCtrl.STimer -= Dec;
                else
                    TpTimingCtrl.STimer = 0;
            }

            if ( TpTimingCtrl.STimer == 0 )
                TpTimingCtrl.STminStatus = STmin_TIME_UP;
        }
    }
}

/******************************************************************************
函数名：DoCAN_Handle_Time_Out
功  能：超时处理
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Handle_Time_Out(void)
{
    if ( TpTimingCtrl.NTimer == 0 )    // 计时超时
    {
        switch ( TpTimingCtrl.Type )
        {
            case TIMING_PARA_N_As:
                if ( TpCtrl.Process != TP_IDLE )
                {
                    TpCtrl.Process = TP_IDLE;    // 中止数据收发,回到空闲状态
                    DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_TIMEOUT_A);
                }
                break;

            case TIMING_PARA_N_Ar:
                if ( TpCtrl.Process != TP_IDLE )
                {
                    TpCtrl.Process = TP_IDLE;    // 中止数据收发,回到空闲状态
                    DoCAN_N_USData_Indication(N_USDataRxBuffer.N_TAtype, N_USDataRxBuffer.MsgData,
                                              N_USDataRxBuffer.Length, N_TIMEOUT_A);
                }
                break;

            case TIMING_PARA_N_Bs:
                if ( TpCtrl.Process != TP_IDLE )
                {
                    TpCtrl.Process = TP_IDLE;    // 中止数据发送,回到空闲状态
                    DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_TIMEOUT_Bs);
                }
                break;

            case TIMING_PARA_N_Br:
                if ( TpCtrl.Process != TP_IDLE )
                {
                    TpCtrl.Process = TP_IDLE;    // 中止数据收发,回到空闲状态
                    DoCAN_N_USData_Indication(N_USDataRxBuffer.N_TAtype, N_USDataRxBuffer.MsgData,
                                              N_USDataRxBuffer.Length, N_ERROR);
                }
                break;

            case TIMING_PARA_N_Cs:
                if ( TpCtrl.Process != TP_IDLE )
                {
                    TpCtrl.Process = TP_IDLE;    // 中止数据收发,回到空闲状态
                    DoCAN_N_USData_Confirm(N_USDataTxBuffer.N_TAtype, N_ERROR);
                }
                break;

            case TIMING_PARA_N_Cr:
                if ( TpCtrl.Process != TP_IDLE )
                {
                    TpCtrl.Process = TP_IDLE;    // 中止数据接收,回到空闲状态
                    DoCAN_N_USData_Indication(N_USDataRxBuffer.N_TAtype, N_USDataRxBuffer.MsgData,
                                              N_USDataRxBuffer.Length, N_TIMEOUT_Cr);
                }
                break;

            default:
                break;
        }

        DoCAN_Stop_Timer( );    // 停止计时
    }
}

/******************************************************************************
函数名：DoCAN_Start_Timer
功  能：启动时序定时器
参  数：TimingParameter ：时序参数,可以是下列参数中的一种
                          TIMING_PARA_N_As
                          TIMING_PARA_N_Ar
                          TIMING_PARA_N_Bs
                          TIMING_PARA_N_Br
                          TIMING_PARA_N_Cs
                          TIMING_PARA_N_Cr
返回值：无
******************************************************************************/
void DoCAN_Start_Timer(uint8_t TimingParameter)
{
    switch ( TimingParameter )
    {
        case TIMING_PARA_N_As:
            TpTimingCtrl.Type   = TIMING_PARA_N_As;
            TpTimingCtrl.NTimer = N_As * 1000;
            break;

        case TIMING_PARA_N_Ar:
            TpTimingCtrl.Type   = TIMING_PARA_N_Ar;
            TpTimingCtrl.NTimer = N_Ar * 1000;
            break;

        case TIMING_PARA_N_Bs:
            TpTimingCtrl.Type   = TIMING_PARA_N_Bs;
            TpTimingCtrl.NTimer = N_Bs * 1000;
            break;

        case TIMING_PARA_N_Br:
            TpTimingCtrl.Type   = TIMING_PARA_N_Br;
            TpTimingCtrl.NTimer = N_Br * 1000;
            break;

        case TIMING_PARA_N_Cs:
            TpTimingCtrl.Type   = TIMING_PARA_N_Cs;
            TpTimingCtrl.NTimer = N_Cs * 1000;
            break;

        case TIMING_PARA_N_Cr:
            TpTimingCtrl.Type   = TIMING_PARA_N_Cr;
            TpTimingCtrl.NTimer = N_Cr * 1000;
            break;

        default:
            TpTimingCtrl.Type   = TIMING_PARA_NONE;
            TpTimingCtrl.NTimer = 0;
            break;
    }
}

/******************************************************************************
函数名：DoCAN_Stop_Timer
功  能：停止时序定时器
参  数：无
返回值：无
******************************************************************************/
void DoCAN_Stop_Timer(void)
{
    TpTimingCtrl.Type = TIMING_PARA_NONE;
}

/******************************************************************************
函数名：DoCAN_Start_STmin_Timer
功  能：启动STmin定时器
参  数：STminTime：STmin时间
返回值：无
******************************************************************************/
void DoCAN_Start_STmin_Timer(uint8_t STminTime)
{
    if ( STminTime <= 0x7F )    // 0x00 - 0x7F：0ms - 127ms
        TpTimingCtrl.STimer = ( uint32_t )STminTime * 1000;
    else if ( (STminTime >= 0xF1) && (STminTime <= 0xF9) )    // 0xF1 - 0xF9：100us - 900us
        TpTimingCtrl.STimer = ( uint32_t )(STminTime & 0x0F) * 100;
    else    // Reserved   ：127ms
        TpTimingCtrl.STimer = 127000;

    TpTimingCtrl.STminStatus = STmin_TIMING;    // STmin开始计时
}

/******************************************************************************
函数名：DoCAN_Get_STmin_Timer_Status
功  能：获取当前STmin定时器的状态
参  数：无
返回值：STmin_TIMER_IDLE：STmin定时器空闲
        STmin_TIME_UP   ：STmin定时时间到
        STmin_TIMING    ：STmin定时器计时中
******************************************************************************/
uint8_t DoCAN_Get_STmin_Timer_Status(void)
{
    uint8_t Status;

    Status = TpTimingCtrl.STminStatus;

    if ( Status == STmin_TIME_UP )
        TpTimingCtrl.STminStatus = STmin_TIMER_IDLE;

    return Status;
}
