#ifndef __UDS_COMMON_H
#define __UDS_COMMON_H


#include "TYW_stdint.h"
#include "RTE_CAN.h"
//#include "CAN_Signal_Tx.h"
#include "RTE_CAN_NM.h"
#include "UDS_DTC.h"

#include "EOL_Para.h"
#include "COM_CAN.h"

#include "Services_Mileage.h"
//#include "Services_ODO.h"
#include "Common_Interface.h"

#include "UDS_ISO14229_Server.h"

#include "DoCAN_ISO15765_Config.h"


#include "CAN_Lib.h"

#include "UDS_ISO14229_Server_Config.h"
#include "Emulated_EEPROM.h"
#include "Watchdog.h"

#include "System_Monitor.h"

#include "RTE_ADC.h"

#include "rh850_macros.h"
#include "Telltales_user.h"


/**
  *正负反馈
  */
#define POSITIVE_RSP                                            (uint8_t) 0x00                          /*正反馈*/
#define NEGATIVE_RSP                                            (uint8_t) (!POSITIVE_RSP)               /*负反馈*/

/**
  *DFlash
  */
#define NoNeedWait                                              0x00u
#define NeedWait                                                0x01u
#define JumpToBoot02                                            0x58856336u
#define JumpToBoot82                                            0x85583663u

/**
  *10服务和子服务
  *诊断会话
  */
#define DiagnosticSessionControl                                0x10u
#define DefaultSession                                          0x01u
#define ProgrammingSession                                      0x02u
#define ExtendedDiagnosticSession                               0x03u

/**
  *11服务和子服务
  *ECU复位
  */
#define ECUReset                                                0x11u
#define HardReset                                               0x01u
#define SoftReset                                               0x03u

/**
  *14服务和子服务
  *清除故障信息
  */
#define ClearDiagnosticInformation                              0x14u

/**
  *19服务和子服务
  *读取故障信息
  */
#define ReadDTCInformation                                      0x19u
#define ReportNumberOfDTCByStatusMask                           0x01u
#define ReportDTCByStatusMask                                   0x02u
#define ReportDTCSnapshotRecordByDTCNumber                      0x04u
#define ReportSupportedDTC                                      0x0Au

#define NoSupport                                               0x00u
#define NeedSupport                                             0x01u
#define NormalVottage                                           0x00u
#define LowVottage                                              0x01u
#define HightVottage                                            0x02u
#define AgeingCount                                             40u
#define OfflineLoopMultiple                                     30u
#define MaxDTCPendingCount                                      1u
#define MinimumVoltage                                          16000u
#define RestoreMinimumVoltage                                   16500u
#define MaximumVoltage                                          32000u
#define RestoreMaximumVoltage                                   31500u
#define LowVoltageTimer                                         5000u
#define HightVoltageTimer                                       5000u

#define DTCError                                                0x01u
#define DTCErrorThisCycle                                       0x02u
#define DTCPending                                              0x04u
#define DTCConfirmed                                            0x08u
#define DTCNoTestLastClear                                      0x10u
#define DTCErrorLastClear                                       0x20u
#define DTCNoError                                              0xFEu
#define DTCNoTestThisCycle                                      0x40u

#define DTCMask                                                 0x09u

#define KL15DTCEnableTimer                                      3500u
#define H_LVoltageDTCEnableTimer                                500u
#define BusOffDTCEnableTimer                                    1000u

/**
  *22服务和子服务
  *通过DID来读数据
  */
#define ReadDataByIdentifier                                    0x22u

/**
  *27服务和子服务
  *安全访问
  */
#define SecurityAccess                                          0x27u
#define requestSeed_LV1                                         0x01u
#define sendKey_LV1                                             0x02u
#define requestSeed_LV3                                         0x03u
#define sendKey_LV3                                             0x04u
#define requestSeed_LV7                                         0x07u
#define sendKey_LV7                                             0x08u
#define NormalKeyUnlock                                         0x01u
#define NormalKeyLock                                           0x00u
#define BootKeyUnlock                                           0x02u
#define BootKeyLock                                             0x00u
#define SER27_MAX_REQ_SEED_NUM                                  0x03u
#define SER27_MAX_INVAILD_KEY_NUM                               0x03u
#define SER27_CLEAR_REQ_SEEDED                                  0x00u
#define SER27_REQ_SEEDED                                        0x01u
#define SER27_ERR_DELAY_TIMER_EN                                0x01u
#define SER27_ERR_DELAY_SER_PERIOD                              100u
#define SER27_ERR_DELAY_TIMEOUT                                 10000u

/**
  *28服务和子服务
  *通讯控制
  */
#define CommunicationControl                                    0x28u
#define enableRxAndTx                                           0x00u
#define enableRxAndDisableTx                                    0x01u
#define disableRxAndEnableTx                                    0x02u
#define disableRxAndTx                                          0x03u
#define normalMsg                                               0x01u
#define networkManagementMsg                                    0x02u
#define networkManagementMsgAndnormalMsg                        0x03u

/**
  *2E服务和子服务
  *通过DID来写数据
  */
#define WriteDataByIdentifier                                   0x2Eu
#define WriteBootData                                           0x00u
#define Write2EData                                             0x01u
#define WriteEOLData                                            0x02u

/**
  *2F服务和子服务
  *通过DID来控制ECU
  */
#define InputOutputControlByIdentifier                          0x2Fu
#define WhiteColor                                              0x01u
#define BlackColor                                              0x02u
#define RedColor                                                0x03u
#define GreenColor                                              0x04u
#define BlueColor                                               0x05u
#define GaugeSpeed                                              0x01u
#define GaugeTacho                                              0x02u
#define GaugeFuel                                               0x03u
#define GaugeEngCoolantTemp                                     0x04u
#define ZeroPosition                                            0x00u
#define HalfPosition                                            0x01u
#define FullPosition                                            0x02u
#define Contrl                                                  0x03u
#define Resume                                                  0x00u

/**
  *31服务和子服务
  *历程控制
  */
#define RoutineControl                                          0x31u
#define startRoutine                                            0x01u
#define stopRoutine                                             0x02u
#define requestRoutineResults                                   0x03u
#define MaintenanceReset                                        0X62F1u
#define CheckMemory                                             0x0202u
#define UpdateConditionCheck                                    0x0203u
#define ECU_selftest                                            0xDFF0u
#define EraseMemory                                             0xFF00u
#define CheckProgrammingDependencies                            0xFF01u
#define RoutineCompletedSuccessfully                            0x04u
#define RoutineCompletedUnsuccessfully                          0x05u

/**
  *3E服务和子服务
  *维持当前会话
  */
#define TesterPresent                                           0x3Eu
#define ZeroSubFunction                                         0x00u

/**
  *85服务和子服务
  *故障检测控制
  */
#define  ControlDTCSetting                                      0x85u
#define  DTCSettingOn                                           0x01u
#define  DTCSettingOff                                          0x02u

/**
  *诊断支持的否定响应代码
  */
#define positiveResponse                                        0x00u
#define	serviceNotSupported                                     0x11u
#define	subFunctionNotSupported                                 0x12u
#define	incorrectMessageLength                                  0x13u
#define	responseTooLong                                         0x14u
#define	conditionsNotCorrect                                    0x22u
#define	requestSequenceError                                    0x24u
#define	requestOutOfRange                                       0x31u
#define	securityAccessDenied                                    0x33u
#define	invalidKey                                              0x35u
#define	exceedNumberOfAttempts                                  0x36u
#define	requiredTimeDelayNotExpired                             0x37u
#define	uploadDownloadNotAccepted                               0x70u
#define	transferDataSuspended                                   0x71u
#define	generalProgrammingFailure                               0x72u
#define	wrongBlockSequenceCounter                               0x73u
#define	requestCorrectlyReceivedResponsePending                 0x78u
#define	subfunctionNotSupportinActiveSession                    0x7Eu
#define	serviceNotSupportedInActiveSession                      0x7Fu
#define	engineIsRunning                                         0x83u
#define	engineIsNotRunning                                      0x84u
#define	engineRunTimeTooLow                                     0x85u
#define	voltageTooHigh                                          0x92u
#define	voltageTooLow                                           0x93u

#define getDID(DID_H, DID_L)                                    ((uint16_t)(((uint16_t)(DID_H)) << 8u) | (uint16_t)(DID_L))
#define toUint16_t(data0, data1)                                ((uint16_t)(((uint16_t)(data0)) << 8u) | (uint16_t)(data1))
#define toUint32_t(data0, data1, data2, data3)                  ((uint32_t)(((uint32_t)(data0)) << 24u) | (uint32_t)(((uint32_t)(data1)) << 16u) | (uint32_t)(((uint32_t)(data2)) << 8u) | (uint32_t)(data3))
#define isBCD(data)                                             ((((uint8_t)((data) & 0x0Fu)) < 0x0Au) && (((uint8_t)(((uint8_t)((data) & 0xF0u)) >> 4u )) < 0x0Au))
#define isBoolean(data)                                         (((uint8_t)(data) == 0u) || ((uint8_t)(data) == 1u))
#define DIM( X )                                                (sizeof(X) / sizeof((X)[0]))
/**
  * TYPEDEFS
  */



typedef union 
{
    uint8_t Data[500];
    struct
    {
        uint8_t SubID                                           :7;
        uint8_t PositiveSuppression                             :1;
        uint8_t Data[499];
    } SidDetail;
    struct
    {
        uint8_t DID_H;
        uint8_t DID_L;
        uint8_t Data[498];
    } DidDetail;
    struct
    {
        uint32_t Parameter                                      :24;
        uint8_t Data[497];
    } S14Detail;
    struct
    {
        uint8_t SubID;
        uint8_t DID_H;
        uint8_t DID_L;
        uint8_t Data[497];
    } S31Detail;
    struct
    {
      uint8_t SubID                                            :7;
      uint8_t PositiveSuppression                              :1; 
      uint8_t ContrlType;
      uint8_t Data[498];  
    }S28Detail;
    
} msgDataUnion;

typedef struct
{
    uint32_t msgID;
    uint16_t msgDLC;
    msgDataUnion msgData;
} DiagMSGUnion;

typedef struct
{
    uint8_t LV1Ctrl;
    uint8_t LV1DelayCtrl;
    uint16_t LV1DelayTimer;
    uint8_t LV1SafetyStatus;
    uint8_t LV1Seed[2];
    uint8_t LV1Key[2];
    uint8_t LV3Ctrl;
    uint8_t LV3DelayCtrl;
    uint16_t LV3DelayTimer;
    uint8_t LV3SafetyStatus;
    uint8_t LV3Seed[2];
    uint8_t LV3Key[2];
    uint16_t Counter_1000ms;
    uint8_t AllowRequestSeedFlag;

} Ser27_FlowCtrlUnion;

typedef struct
{
    uint32_t Flag;
    uint32_t JumpToBootFlag;
    uint32_t AppValidFlag;
    uint32_t S11Flag;
} DiagFlagUnion;

typedef struct
{
    uint32_t Flag;
    uint32_t RandNum;
    uint16_t fill;
    uint8_t  LV1ReqSeedCnt;
    uint8_t  LV1InvaidKyeCnt;
    uint8_t  LV3ReqSeedCnt;
    uint8_t  LV3InvaidKyeCnt;
    uint8_t  LV7_ReqSeedCnt;
    uint8_t  LV7_InvaidKyeCnt; 
} Ser27_FlowCtrlCntUnion;

typedef struct
{
    uint32_t Flag;
    uint8_t DID_F180[7];
    uint8_t DID_F181[7];
    uint8_t DID_F182[7];  
    uint8_t DID_6000;
    uint8_t DID_6001;
    uint8_t DID_6078;
    uint8_t DID_6079;
    uint8_t DID_607A;
    uint8_t DID_607B;
    uint8_t DID_607C;
    uint8_t DID_607D;
    uint8_t DID_60C8;
    uint8_t DID_6005;
    uint8_t DID_600B;
    uint8_t DID_607E;
    uint8_t DID_607F;
    uint8_t DID_6080;
    uint8_t DID_6002;
    uint8_t DID_600F;
    uint8_t DID_6011;
    uint8_t DID_600E;
    uint8_t DID_6081;
    uint8_t DID_6009;
    uint8_t DID_6010;
    uint8_t DID_6082;
    uint8_t DID_6083;
    uint8_t DID_6084;
    uint8_t DID_600A;
    uint8_t DID_6085;
    uint8_t DID_6086;
    uint8_t DID_6087[2];
    uint8_t DID_6088;
    uint8_t DID_6089;
    uint8_t DID_608A;
    uint8_t DID_608B;
    uint8_t DID_608C;
    uint8_t DID_608D;
    uint8_t DID_608E;
    uint8_t DID_6029;
    uint8_t DID_6090;
    uint8_t DID_6013;
    uint8_t DID_602A;
    uint8_t DID_6023;
    uint8_t DID_602C;
    uint8_t DID_60A2;
    uint8_t DID_60AB;
    uint8_t DID_60AC;
    uint8_t DID_6065;
    uint8_t DID_6066;
    uint8_t DID_6069;
    uint8_t DID_6077; 
} BootToDFlashInfoUnion;

typedef struct
{
    uint32_t Flag;
    uint8_t  DID_F183[42];
    uint8_t  DID_F184[42];
    uint8_t  DID_F185[42];
    uint8_t  DID_F190[17];
    uint8_t  DID_F1F0[6];
    uint8_t  DID_F1F1[6];
    uint8_t  DID_F187[13];
    uint8_t  DID_F18A[8];
    uint8_t  DID_F18B[4];
    uint8_t  DID_F18C[20];
    uint8_t  DID_F193[6];
    uint8_t  DID_F195[6];
} Ser2EToDFlashInfoUnion;

/*typedef struct
{
    uint8_t  ECUPowerVoltage;
    uint16_t VehicleSpeed;
    uint8_t  OccurrenceCounter;
    uint32_t FirstMalfunction;
    uint32_t LastMalfunction;
} SnapshotUnion;*/

typedef struct
{
    uint8_t  DTCStatus;
    uint8_t  DTCAgeing;
    uint8_t  DTCCount;
    uint8_t  DTCPendingCount;
    //SnapshotUnion Snapshot;
} DTCUnion;

typedef struct
{
    uint32_t Flag;
    DTCUnion DTC[18u];
} DTCToDFlashInfoUnion;



typedef void (*InitFunction)(void);

extern uint8_t S31DID62F3RequestStatus;
extern DiagMSGUnion DiagMSG;
extern DiagFlagUnion DiagFlag;
extern Ser27_FlowCtrlUnion Ser27_FlowCtrl;
extern Ser27_FlowCtrlCntUnion Ser27_FlowCtrlCnt;
extern BootToDFlashInfoUnion BootToDFlashInfo;
extern Ser2EToDFlashInfoUnion Ser2EToDFlashInfo;
extern DTCToDFlashInfoUnion DTCToDFlashInfo;
extern uint8_t  S31DIDC004RequestStatus ;
extern uint8_t  S31DIDC005RequestStatus ;
extern uint8_t  S31DIDC014RequestStatus ;



void setSessionType(uint8_t status);
uint8_t getSessionType(void);
void setDiagMSG(uint32_t Identifier, uint16_t dlc, uint8_t Data[]);
DiagMSGUnion getDiagMSG(void);
void clearDiagMSG(void);
uint16_t getSpeed(void);
uint16_t getESpeed(void);
uint32_t getKL30Voltage(void);
uint8_t getKL15Status(void);
uint8_t getSecurityLevel(uint8_t SecurityLevel);
void Ser27_ChangeSessionHandle(void);
void UDS_RESET(void);
void UDS_Delay(uint16_t count);
void UDS_S11_Sand(uint8_t subid);
void UDS_S11_Confirm(void);
void UDS_NRC78_Sand(uint8_t sid);
void UDS_SendNRCRsp(uint8_t sid,uint8_t status);
void UDS_14_SendRsp(uint8_t sid);
void UDS_50us_Service(void);
void UDS_10ms_Service(void);
void UDS_KL15_init(void);
void UDS_Slepp(void);
void MsgLostTimer(uint16_t timer);
void ReceivedMsg(uint32_t MsgID, uint8_t DLC);
void S3_Service(uint16_t timer);
void S3_ServiceClear(void);
void S3_ServiceWait(void);
void S3_ServiceTimeOut(void);
void Ser27_ErrDelayTimerService(uint16_t timer);
void Ser27_IgOnDelayTimerService(uint16_t timer);
uint8_t GetRequestSeedFlag(void);
void ControlMessageCommunication(uint8_t Type, uint8_t Status);
void enableDTCTimer(uint16_t Timer);
uint8_t isDTCEnable(void);
void setDTCEnableTimer(uint16_t Timer);
void OpenDTCTest(void);
void CloseDTCTest(void);
uint8_t DTCTestIsOpen(void);
void DTCAgeing(void);
void ReadAllDFlashData(void);
uint8_t ReadDFlashData(uint8_t u8BlockNum, uint32_t u32Data[], uint16_t u16Len, InitFunction initFunction);
uint8_t WriteDFlashData(uint8_t u8BlockNum, uint32_t u32Data[], uint16_t u16Len, uint8_t isWait);
void AllFlagInit(void);
void Ser27ToDFlashInfoInit(void);
void BootToDFlashInfoInit(void);
void Ser2EToDFlashInfoInit(void);
void DTCToDFlashInfoInit(void);
void DTCConfigurationInit(void);
void BootReadFlahInit(void);
#endif
