/******************************************************************************
文 件 名：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"

typedef void (*InitFunction)(void);

/*-----------------------------------------------------------------------------
正负反馈
-----------------------------------------------------------------------------*/
#define POSITIVE_RSP                    0x00
#define NEGATIVE_RSP                    (!POSITIVE_RSP)
/******************************************************************************
Function and subFunction
Diagnostic Session
*******************************************************************************/
#define DiagnosticSessionContro         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   cnDTCslen		7	//

#define U007488 0xC07488  //BUS OFF    
#define U300316 0xF00316  //Internal local voltage < 16V  
#define U300317 0xF00317  //Internal local voltage > 32V   
#define U111087 0xD11087  //NM Limphome failure
#define U014087 0xC14087  //Lost communication with BCM 0x10FF7521 
#define U012187 0xC12187  //Lost communication with ABS 0x18FEBF0B 
#define U010087 0xC10087  //Lost communication with EMS 0x0CF00400  

#define cnU007488 0
#define cnU300316 1
#define cnU300317 2
#define cnU111087 3
#define cnU014087 4
#define cnU012187 5
#define cnU010087 6

#define cnMSG521      0
#define cnMSGF0B      1
#define cnMSG400      2

#define     NormalVottage         0x00
#define     LowVottage            0x01
#define     HightVottage          0x02

#define     LowVoltageTimer           1000
#define     HightVoltageTimer         1000
#define     RecoverRecordDTCTimer     1000

#define     KL15DTCEnableTimer       3200
#define     H_LVoltageDTCEnableTimer 700
#define     BusOffDTCEnableTimer     200

typedef struct
{
    uint16_t Timer;
    uint8_t  Flag;
    uint8_t  Status;
    uint8_t  LastStatus;
} RecDTC_WaitBusoff_STRUCT;

#define		 _CLRBIT(p,b)		p&=~(1<<b)	//清0 p对应的第b BIT位 (p只能为8BIT数)  
#define		_SETBIT(p,b)		p|=(1<<b)	//置1 p对应的第b BIT位 (p只能为8BIT数)      
#define		_bit_is_set(p,b)		p&(1<<b)

#define		CLRBIT(p,b)			p&=~(1<<b)	//清0 p对应的第b BIT位 (p只能为8BIT数)  
#define		SETBIT(p,b)			p|=(1<<b)	//置1 p对应的第b BIT位 (p只能为8BIT数)      
#define		bit_is_set(p,b)		p&(1<<b)

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

//--------------20160425--------add start 001

#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_LV12                    0x12

//#define Level4UnLock                    0x05
#define Level2UnLock                    0x04
#define Level1UnLock                    0x03
#define NormalKeyUnlock                 0x02
#define NormalKeyLock                   0x00
#define BootKeyUnlock                   0x01
#define BootKeyLock                     0x00



#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  //正常报文+网络管理报文

/******************************************************************************
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 Contrl                          0x01
#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 CheckProgrammingPreconditions   0x0203
#define ECU_selftest                    0xDF01
#define EraseMemory                     0xFF00
#define CheckProgrammingDependencies    0xFF01

#define RoutineCompletedSuccessfully    0x01
#define RoutineCompletedUnsuccessfully  0x00
/******************************************************************************
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	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



/******************************************************************************
Bootloader Variable
*******************************************************************************/
typedef struct
{
    uint32_t  GlobalAddress;   //ȫ�ֵ�ַ��ʼ��ַ
    uint32_t  Datalength;      //MemorySize  ������¼�����ݳ���(�����ֽ�)
    uint8_t   data[224 + 10];     //Data
} SRecord_t;


typedef struct
{
    INT32U Flag;
    INT8U  D_F190[17];
    INT8U  D_F1A8[20];
    INT8U  D_3200[16];
    INT8U  D_F1FA[6];
    INT8U  FillData;
} DIAG_2E_DATA;

typedef struct
{
    INT32U Flag;
    INT8U  D_F184[7];
    INT8U  D_F183[10];
    INT8U  Fill[3];   
} DIAG_Boot_DATA;

extern DIAG_2E_DATA   Diag2eData;
extern DIAG_Boot_DATA DiagBootData;


typedef struct
{

    uint8_t attemptcnt;       //level 1 尝试次数
    uint8_t RequestSeedCnt;   //level 1 请求种子次数
    uint8_t attemptcnt11;     //level 11尝试次数
    uint8_t RequestSeedCnt11; //level 11请求种子次数


} Diag27Data;


#define S9S12XHY256 1
#define Bootloader   1
#define OK          			    0x00
#define ERASED      			    0x01
#define NON_ERASED  			    0x02
#define MISALIGNED_ADDRESS  	0x03
#define ACCESS_ERROR        	0x04
#define VERIFICATION_FAILED 	0x05
#define LENGTH_OUT_OF_RANGE 	0x06

#define DFLASH_FirstAddress 	  0x100000                    //0x004400 (HY64)
#define DFLASH_APPvAddress 	    0x100000+256                //=0xA77A表示应用程序无效    
#define DFLASH_Ser2EAddress 	    0x100000+512                //本256字节扇区存储诊断协议     2E 写的内容  
#define DFLASH_SerBOOTAddress    0x100000+768                //本256字节扇区存储备份数据协议  2E 写的内容
#define DFLASH_MOTORAddress     0x100000+1024               //本256字节扇区存储调表数据
#define DFLASH_USERAddress      0X100000+1280               //本256字节扇区存F110 F101
#define DFLASH_TripAddress      0X100000+1536               //储里程清零值,清零次数,保养里程值
#define DFLASH_LockAddress      0X100000+1792               //27服务解锁信息

#define EnableInterrupts   {__asm CLI;}
#define DisableInterrupts  {__asm SEI;}
/*-----------------------------------------------------------------------------
应用层反馈传输结果枚举
-----------------------------------------------------------------------------*/
typedef enum
{
    A_OK = 0,
    A_ERR,
} A_Result_Enum;

typedef struct
{
    uint8_t Para;
    uint8_t P2;
    uint8_t P2Ast;
} DiagSendDataRes;

typedef struct
{
    uint8_t Para;
    uint8_t code;
    uint8_t OpCode;
} DiagSendDataNeg;
typedef struct
{
    uint8_t DiagDataLength;
    uint8_t msg[64];
} ConvertData;

typedef union 
{ 
    uint8_t Msg[4]; 
    uint32_t Value;
} DIGKeyValue; 
//DTC
#define     DTCError           0x01
#define     DTCErrorThisCycle  0x02
#define     DTCPending         0x04
#define     DTCConfirmed       0x08
#define     DTCNoTestLastClear 0x10
#define     DTCErrorLastClear  0x20
#define     DTCNoTestThisCycle 0x40
#define     DTCNoError         0xFE

#define     AgeingCount        39

typedef union
{
    struct
    {
        uint8_t   TestFailed           : 1;
        uint8_t   TestFailedThisOprCyc : 1;
        uint8_t   PendingDTC           : 1;
        uint8_t   ConfirmedDTC         : 1;
        uint8_t   TestNotCompLastClr   : 1;
        uint8_t   TestFailedLastClr    : 1;
        uint8_t   TestNotCompThisCyc   : 1;
        uint8_t   WarnIndicatorReq     : 1;
    } Bits;
    uint8_t Flag;
} _DTC_STATUS;

typedef struct 
{
    _DTC_STATUS     Status;
    uint8_t         FaultPendCount;
    uint8_t         DTCAgingCount; 

}_DTC;


extern DIGKeyValue      DigKeyValue; 

extern INT8U  ContrlorResumeofSOC;
extern INT8U ContrlorResumeofTEMP;
extern INT8U ContrlorResumeofVspeed;
extern INT8U ContrlorResumeofEspeed;
extern _DTC DiagDtc[cnDTCslen];
extern uint16_t ESpeedValNUM;         //ת��
extern uint16_t VspeedValNUM;         //����
extern uint16_t ESpeedVal;            //ת��
extern uint16_t VspeedVal;            //����
extern uint8_t  TempSeg;              //ˮ��
extern uint8_t  SocSeg;               //ȼ��
extern uint8_t  S3_ServerEN;          //��չ�Ự5s��ʱ��ʹ�ܿ���
extern uint8_t DiagnosticReceived;    //��ϲ��ֹ�����ȫ�ֱ���?
extern uint8_t  ContrlorResumeofLamp;    //���б����Ʋ���
extern uint8_t LampWarningStatus;        //�ƹ�״̬

/******************************************************************************
函数声明
******************************************************************************/

/*** 10# - Diagnostic Session Control ***/
void UDS_Service_19_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_10_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_27_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_28_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_85_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_31_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_34_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_36_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_37_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_11_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_3E_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_2E_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_2F_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_22_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void UDS_Service_14_Indication ( uint32_t A_TA_type, uint16_t A_Length, uint8_t *A_Data );
void S3_ServerCNT ( void );
/*** 11# - Ecu Reset ***/
void Randomcnt ( void );
void CanLoseDetected ( void );
void INIT_DTC_STATUS_IGN_ON ( void );
void ChangeDTCs_ST_PRG ( INT8U pos, INT8U status );
void SaveDTCsToEEPROM ( void );
void CAN_NORMAL_TIME_PRG ( void );
void HandleOf2FServices ( void );

void Write_27_DATA_TO_FLASH(void);
void Read_27_DATA_FROM_FLASH(void);

extern INT16U MYeturnCode;
extern uint32_t DFLASHeep_adr;
INT8U  DFLASH_Erase_Sector ( INT32U  address ) ;
INT8U  DFLASH_Program ( INT32U  address, INT16U *ptr, INT8U number_of_words );

INT8U  DFLASH_Erase_Sector ( INT32U  address );
uint32_t DFLASH_Read_Word ( INT32U  address );
uint8_t DFLASH_Read_Word1(INT32U Adrr, uint32_t *Data,uint8_t len);
void ReadNbyteFrDFalsh ( INT16U *mP, INT16U mLEN );
void WriteNbyteToDFalsh ( INT16U *mP, INT16U mLEN );
INT8U  DFLASH_N_Program ( INT32U  address, INT16U *ptr, INT8U number_of_words );
uint8_t getKL15Status(void);
uint8_t GetBusOffState_NotNM(void);
uint8_t getBusoffStatus(void);
void enableDTCTimer(uint16_t Timer);
void setDTCEnableTimer(uint16_t Timer);
uint8_t getPowerStatus(void);
void ReceivedMsg(uint32_t MsgID, uint8_t DLC);
void MsgLostTimer(uint16_t timer);
uint8_t getMSGStatus(uint8_t cnMsgID);
uint8_t write2EData(void);
uint8_t WriteDFlashData(uint32_t u8BlockNum, uint32_t u32Data[], uint16_t u16Len);
uint8_t Write_Base_DATA_FROM_FLASH(uint32_t Adrr, uint8_t *Data,uint8_t len);
uint8_t ReadDFlashData(uint32_t u8BlockNum, uint32_t u32Data[], uint16_t u16Len, InitFunction initFunction);
void Ser2EToDFlashInfoInit(void);
void ReadAllDflashData(void);
#endif