/******************************************************************************
 �� �� ����UDS_ISO14229_Services.h
 ����������ISO 14229 �淶�涨����Ϸ���������˷���ʵ�ֺ���ͷ�ļ�
 ��    �ߣ�����
 ��    ����V1.0
 ��    �ڣ�2016.11.1
 ******************************************************************************/

/******************************************************************************
 ��Ϸ����OSIģ��ӳ��
 ===============================================================================
 *     NO.     OSI Layer        Diagnostics services
 -------------------------------------------------------------------------------
 *      7      Application      ISO 14229-1 ISO 14229-3
 6      Presentation     -
 *      5      Session          ISO 14229-2
 4      Transport        ISO 15765-2
 3      Network          ISO 15765-2
 2      Data Link        ISO 11898
 1      Physical         ISO 11898
 ===============================================================================
 ******************************************************************************/

#ifndef _UDS_ISO14229_SERVICES_H_
#define _UDS_ISO14229_SERVICES_H_

#include "UDS_ISO14229_Server_Config.h"

/**
 *DFlash
 */
#define NoNeedWait 0x00u
#define NeedWait   0x01u
#define APP_STATUS_ADDR (0x500400ul)

#define Data_Flash_Addr_BootValid_OFFSET   0x00000000
#define Data_Flash_Addr_DiagReceive_OFFSET 0x00002000
#define Data_Flash_Addr_Diag2E_OFFSET      0x00004000
#define Data_Flash_Addr_DiagDTC_OFFSET     0x00006000
#define Data_Flash_Addr_GHdata_OFFSET      0x0000A000    // ��������
#define Jump_To_Boot_Need_Answer           0xA77A3AA3
#define Jump_To_Boot_No_Answer             0xA77A8AA8
#define Flag_App_OTAStatus                 0x3663B88B    // ����Boot��ԭ������ΪOTA

#define EnableInterrupts \
    {                    \
        __asm CLI;       \
    }
#define DisableInterrupts \
    {                     \
        __asm SEI;        \
    }

/*-----------------------------------------------------------------------------
 Response
 -----------------------------------------------------------------------------*/
#define POSITIVE_RSP 0x00
#define NEGATIVE_RSP (! POSITIVE_RSP)
/*-----------------------------------------------------------------------------
 SPRMB
 -----------------------------------------------------------------------------*/
#define AbleResponseType    0x00
#define DisableResponseType (! AbleResponseType)
/*-----------------------------------------------------------------------------
 NRC13 check type
 -----------------------------------------------------------------------------*/
#define MinLengthType 0x00
#define SubLengthType (! MinLengthType)
/*-----------------------------------------------------------------------------
 Session mode
 -----------------------------------------------------------------------------*/
#define DefaultMode            0x01
#define ProgrammingMode        0x02
#define ExtendedDiagnosticMode 0x04
/*----------------------------------------------- ------------------------------
 Security level
 -----------------------------------------------------------------------------*/
#define NoNeed     0x00
#define NeedLevel1 0x01
#define NeedLevel2 0x02
/******************************************************************************
 Function and subFunction
 Diagnostic Session
 *******************************************************************************/
#define DiagnosticSessionControl  0x10
#define DefaultSession            0x01
#define ProgrammingSession        0x02
#define ExtendedDiagnosticSession 0x03

/******************************************************************************
 Function and subFunction
 ECUReset
 ********************************************************************************/
#define ECUReset  0x11
#define HardReset 0x01
#define SoftReset 0x03

/******************************************************************************
 Function and subFunction
 ClearDiagnosticInformation
 ********************************************************************************/
#define ClearDiagnosticInformation 0x14

/******************************************************************************
 Function and subFunction
 ReadDTCInformation
 ********************************************************************************/
#define ReadDTCInformation 0x19
#define Error              0x09
#define NoError            0x08

#define OTA_None  0x00
#define OTA_Reqed 0x01
#define OTA_Quit  0x02

// typedef void (*pfuMsgLost)(void);
// typedef void (*pfuMsgOk)(void);

// typedef struct
// {
//     const uint16_t     Msg_ID;
//     volatile uint16_t *DTC_NodeLostCnt;
//     volatile uint8_t  *DTC_NodeLostFlag;
//     const uint16_t     DTC_LostPeriod;
//     pfuMsgLost         pfuLostHandleCBK;
//     pfuMsgOk           pfuOkHandleCBK;
// } DTC_NodeLostType;
#define _CLRBIT(p, b)     p &= ~(1 << b)
#define _SETBIT(p, b)     p |= (1 << b)
#define _bit_is_set(p, b) p & (1 << b)

#define CLRBIT(p, b)     p &= ~(1 << b)
#define SETBIT(p, b)     p |= (1 << b)
#define bit_is_set(p, b) p & (1 << b)

#define bit_is_clear(p, b) ! (p & (1 << b))

#define bit_2_set(p, b) ((p >> b) & 0x03)
#define bit_3_set(p, b) ((p >> b) & 0x07)
#define bit_4_set(p, b) ((p >> b) & 0x0F)
#define bit_5_set(p, b) ((p >> b) & 0x1F)
#define bit_6_set(p, b) ((p >> b) & 0x3F)
#define bit_7_set(p, b) ((p >> b) & 0x7F)

/******************************************************************************
 Function and subFunction
 ReadDataByIdentifier
 ********************************************************************************/
#define ReadDataByIdentifier 0x22
/******************************************************************************
 Function and subFunction
 SecurityAccess
 ********************************************************************************/
#define SecurityAccess    0x27
#define requestSeed_LV1   0x01
#define sendKey_LV1       0x02
#define requestSeed_LV3   0x03
#define sendKey_LV3       0x04
#define requestSeed_LV5   0x05
#define sendKey_LV5       0x06
#define requestSeed_LV11  0x11
#define sendKey_LV11      0x12
#define NormalKeyUnlock   0x01
#define NormalKeyLock     0x00
#define BootKeyUnlock     0x02
#define BootKeyLock       0x00
#define RequestSeedMaxCnt 0x04
#define AttemptMaxCnt     0x03

#define FLASH_SECTOR_SIZE 0x400
/******************************************************************************
 Function and subFunction and type
 CommunicationControl
 ********************************************************************************/
#define CommunicationControl                                              0x28
#define enableRxAndTx                                                     0x00
#define enableRxAndDisableTx                                              0x01
#define disableRxAndEnableTx                                              0x02
#define disableRxAndTx                                                    0x03
#define normalCommunicationMessages                                       0x01
#define networkManagementCommunicationMessages                            0x02
#define networkManagementCommunicationMessagesnormalCommunicationMessages 0x03

/************************28SerStart*********************/
#define DIAG_COM_NOR_TX 0x01
#define DIAG_COM_NOR_RX 0x02
#define DIAG_COM_NW_TX  0x04
#define DIAG_COM_NW_RX  0x08

#define DIAG_SET_COM_DISABLE(Var, BitField, Type) ((Var) |= ( Type )(BitField))
#define DIAG_SET_COM_ENABLE(Var, BitField, Type)  ((Var) &= (Type) ~( Type )(BitField))
#define DIAG_TST_BIT_SET(Var, BitField, Type)     (0U != ((Var) & ( Type )(BitField)))
#define DIAG_TST_BIT_RESET(Var, BitField, Type)   (0U == ((Var) & ( Type )(BitField)))
/************************28SerEnd***********************/

/******************************************************************************
 Function and subFunction
 WriteDataByIdentifier
 ********************************************************************************/
#define WriteDataByIdentifier 0x2E

/******************************************************************************
 Function and subFunction
 InputOutputControlByIdentifier
 ********************************************************************************/
#define InputOutputControlByIdentifier 0x2F
#define WhiteColor                     0x01
#define BlackColor                     0x02
#define RedColor                       0x03
#define GreenColor                     0x04
#define BlueColor                      0x05
#define GaugeSpeed                     0x01
#define GaugeTacho                     0x02
#define GaugeFuel                      0x03
#define GaugeEngCoolantTemp            0x04
#define ZeroPosition                   0x00
#define HalfPosition                   0x01
#define FullPosition                   0x02

#define Clear  0x08
#define Contrl 0x03
#define Resume 0x00

/******************************************************************************
 Function and subFunction
 RoutineControl
 ********************************************************************************/
#define RoutineControl                 0x31
#define startRoutine                   0x01
#define stopRoutine                    0x02
#define requestRoutineResults          0x03
#define MaintenanceReset               0X62F1
#define CheckMemory                    0x0202
#define UpdateConditionCheck           0x0203
#define ECU_selftest                   0xDFF0
#define EraseMemory                    0xFF00
#define CheckProgrammingDependencies   0xFF01
#define RoutineCompletedSuccessfully   0x00
#define RoutineCompletedUnsuccessfully 0x05

/******************************************************************************
 Function and subFunction
 RequestDownload
 ********************************************************************************/
#define RequestDownload        0X34
#define LengthFormatIdentifier 0x20
#define Download               0x01

/******************************************************************************
 Function and subFunction
 TransferDataf
 ********************************************************************************/
#define TransferData 0x36

/******************************************************************************
 Function and subFunction
 RequestTransferExit
 ********************************************************************************/
#define RequestTransferExit 0x37

/******************************************************************************
 Function and subFunction
 TesterPresent
 ********************************************************************************/
#define TesterPresent 0x3E

/******************************************************************************
 Function and subFunction
 ControlDTCSetting
 ********************************************************************************/
#define ControlDTCSetting 0x85
#define DTCSettingOn      0x01
#define DTCSettingOff     0x02

/******************************************************************************
 Supported negative response codes
 *******************************************************************************/
#define positiveResponse                        0x00
#define serviceNotSupported                     0x11
#define subFunctionNotSupported                 0x12
#define incorrectMessageLength                  0x13
#define responseTooLong                         0x14
#define conditionsNotCorrect                    0x22
#define requestSequenceError                    0x24
#define requestOutOfRange                       0x31
#define securityAccessDenied                    0x33
#define invalidKey                              0x35
#define exceedNumberOfAttempts                  0x36
#define requiredTimeDelayNotExpired             0x37
#define uploadDownloadNotAccepted               0x70
#define transferDataSuspended                   0x71
#define generalProgrammingFailure               0x72
#define wrongBlockSequenceCounter               0x73
#define requestCorrectlyReceivedResponsePending 0x78
#define subfunctionNotSupportinActiveSession    0x7E
#define serviceNotSupportedInActiveSession      0x7F
#define engineIsRunning                         0x83
#define engineIsNotRunning                      0x84
#define engineRunTimeTooLow                     0x85
#define voltageTooHigh                          0x92
#define voltageTooLow                           0x93

#define noErr             0
#define SRecRangeError    1
#define SRecOddError      2    // S-Record Size Must Be Even
#define FlashProgramError 3    // Flash Programming Error
#define FlashEraseError   4    // Flash Erase Error
#define BadHexData        5    // Bad Hex Data
#define SRecTooLong       6    // S-Record Too Long
#define CheckSumErr       7    // Checksum Error
#define UnknownPartID     8    // Unknown Part ID

#define SWV 0x105 // 0x100 = 1.00 software version 软件版本号
#define HWV 0x100 // 0x100 = 1.00 hardware version 硬件版本号
#define BTV 0x100 // 0x100 = 1.00 bootloader version boot程序版本号
#define INTLV 0x102 // 0x100 = 1.00 internal version 内部版本号
#define PROG_Y 0x24 // 0x24 = 2024年, program year
#define PROG_M 0x04 // 0x03 = 3月, program month
#define PROG_D 0x24 // 0x19 = 19日, program day

/******************************************************************************
 Bootloader Variable
 *******************************************************************************/
// typedef struct
// {
//     uint32_t GlobalAddress;
//     uint32_t Datalength;
//     uint8_t  data [ 224 + 10 ];
// } SRecord_t;

typedef struct
{
    uint32_t Flag;
    uint8_t  Attemptcnt;
    uint8_t  RequestSeedCnt;
    uint8_t  AttemptIIcnt;
    uint8_t  RequestSeedIICnt;
} Ser27_FlowCtrlCntUnion;

typedef struct
{
    uint32_t Flag;
    uint8_t DID_F180[6];
    uint8_t DID_F187[6];
    uint8_t DID_F193[6];
    uint8_t DID_F195[6];
    uint8_t Filldata[4];
}DiagDFlashData;
extern DiagDFlashData DiagDataForDFlash;
typedef struct
{
    uint32_t Flag;
    uint32_t APP_STATUS;
}DiagFlag;
extern DiagFlag DiagDataForFlag;

typedef struct
{
    uint8_t Para;
    uint8_t code;
    uint8_t OpCode;
} DiagSendDataNeg;

void UDS_Service_10_Indication(uint16_t A_TA_type, uint16_t A_Length, uint8_t *A_Data);
void UDS_Service_11_Indication(uint16_t A_TA_type, uint16_t A_Length, uint8_t *A_Data);
void UDS_Service_22_Indication(uint16_t A_TA_type, uint16_t A_Length, uint8_t *A_Data);
void UDS_Service_27_Indication(uint16_t A_TA_type, uint16_t A_Length, uint8_t *A_Data);
void UDS_Service_28_Indication(uint16_t A_TA_type, uint16_t A_Length, uint8_t *A_Data);
void UDS_Service_3E_Indication(uint16_t A_TA_type, uint16_t A_Length, uint8_t *A_Data);
void UDS_Service_85_Indication(uint16_t A_TA_type, uint16_t A_Length, uint8_t *A_Data);
void S3_ServerCNTT(void);
void Randomcnt(void);
extern void DIAG_InitParameter(void);

void GetSeed(void);
void CalculateKey(void);
void CalculateKeyLv11(void);

typedef void (*InitFunction)(void);

/***********Local Functin*************/
uint8_t GetCurrentSession(void);
uint8_t SerXXNRC12Filter(uint8_t insub, const uint8_t *supportsub, uint8_t size, uint8_t *index);
uint8_t SerXXNRC13Filter(uint8_t type, uint8_t serlength, const uint8_t *length, uint8_t index);
uint8_t SerXXNRC22Filter(void);
uint8_t SerXXNRC31DIDFilter(uint16_t inDID, const uint16_t *DIDList, uint8_t size, uint8_t *index);
uint8_t SerXXNRC33Filter(const uint8_t *levelList, uint8_t index);
uint8_t SerXXNRC7EFilter(const uint8_t *SubSupportSession, uint8_t index);
uint8_t SerXXNRC7FFilter(uint8_t SupportSession);
extern void Data_Set_DiagPara(void);
void Write_App_InValid(uint32_t m32);
void DFlash_init(void);

#endif
