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

/*-----------------------------------------------------------------------------
正负反馈
-----------------------------------------------------------------------------*/
#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		8	//注:不要超过16

#define        U007388 0xC07388  //BUS OFF    
#define        U300316 0xF00316  //输入电压低 Internal local voltage < 16V  
#define        U300317 0xF00317  //输入电压高 Internal local voltage > 32V   
#define        U014087 0xC14087  //BCM通讯丢失 0x18FE4021或0x18FFDB21报文丢失，T=100ms 丢失5帧报文以上。  
#define        U010087 0xC10087  //EMS通讯丢失 0x0CF00400报文丢失，T=10ms，丢失5帧报文以上   
#define        U012987 0xC12987  //EBS/ESC通讯丢失 0x18FFE033报文丢失，T=500ms，丢失5帧报文以上   
#define        U012887 0xC12887  //EPB 节点丢失 0x18FDA5EC报文丢失，T=100ms，丢失5帧报文以上
#define        U010187 0xC10187  //TCU丢失通信  0x1801D003报文丢失，T=100ms，丢失5帧报文以上 
//#define        U015587 0xC15587  //IC 节点丢失 0X0CFE6C17报文丢失，T=50ms，丢失5帧报文以上    
//#define        U019887 0xC19887  //TBox 节点丢失 0x18FEE69F报文丢失，T=1000ms，丢失5帧报文以上  


#define    cnU007388	0   //BUS OFF    
#define    cnU300316	1   //输入电压低 Internal local voltage < 16V  
#define    cnU300317	2   //输入电压高 Internal local voltage > 32V   
#define    cnU014087	3   //BCM通讯丢失 0x18FE4021或0x18FFDB21报文丢失，T=100ms 丢失5帧报文以上。  
#define    cnU010087	4   //MMI通讯丢失 0x18FEE641报文丢失，T=1000ms，丢失5帧报文以上   
#define    cnU012987	5   //TPMS通讯丢失 0x18FFE033报文丢失，T=500ms，丢失5帧报文以上   
#define    cnU012887	6   //DCM 节点丢失 0x18FDA5EC报文丢失，T=100ms，丢失5帧报文以上
#define    cnU010187	7   //TCU丢失通信  0x1801D003报文丢失，T=100ms，丢失5帧报文以上      
//#define    cnU015587	8   //IC 节点丢失 0X0CFE6C17报文丢失，T=50ms，丢失5帧报文以上    
//#define    cnU019887	9   //TBox 节点丢失 0x18FEE69F报文丢失，T=1000ms，丢失5帧报文以上

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
{
    // uint8_t F112[8];
    uint8_t F190[17];
    uint8_t F197[10];
    uint8_t F10A[9];
    uint8_t F191[8];
    uint8_t F183[10];
    uint8_t F184[7];
    //uint8_t F199[4];
    //uint8_t F19D[4];
    uint8_t attemptcnt;
    uint8_t Sessiontype;
    uint8_t noused;

} DiagReceiveData;


typedef struct
{

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


} Diag27Data;

typedef struct
{
    uint8_t F110[8];
    uint8_t F101[6];
} DiagReceiveData2;

typedef struct
{
    uint8_t DFEC[64];
    uint8_t DFED[64];
    uint8_t DFEE[64];
    uint8_t DFEF[64];

} DiagReceiveData1;


#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_DiagAddress 	    0x100000+512                //本256字节扇区存储诊断协议     2E 写的内容  
#define DFLASH_BackupAddress    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; 

extern DIGKeyValue      DigKeyValue; 

extern INT8U  ContrlorResumeofSOC;
extern INT8U ContrlorResumeofTEMP;
extern INT8U ContrlorResumeofVspeed;
extern INT8U ContrlorResumeofEspeed;
extern uint8_t DTC_STATUS[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 Record_DTCStatus_Wait_No_Busoff_xxms ( void );
void ChangeDTCs_ST_PRG ( INT8U xh, INT8U status );
void SaveDTCsToEEPROM ( void );
void CAN_NORMAL_TIME_PRG ( void );
void HandleOf2FServices ( void );

void Write_2E_DATA_TO_FLASH(void);
void Read_2E_DATA_FROM_FLASH(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 );
void ReadNbyteFrDFalsh ( INT16U *mP, INT16U mLEN );
void Read_BACKUP_DATA_FROM_FLASH ( void );
void WriteNbyteToDFalsh ( INT16U *mP, INT16U mLEN );
INT8U  DFLASH_N_Program ( INT32U  address, INT16U *ptr, INT8U number_of_words );
#endif