#include <stdio.h>      /*標準輸入輸出定義*/
#include <stdlib.h>     /*標準函數庫定義*/
#include <string.h>
#include <stdint.h>
#include <time.h>
#include <unistd.h>

#include <sys/time.h>
#include <sys/timeb.h>

#include "../ShareMemory/shmMem.h"
#include "../Config.h"
#include "../Log/log.h"
#include "Module_InternalComm.h"
#include "internalComm.h"

//------------------------------------------------------------------------------
static struct SysConfigData *pSysConfig = NULL;
static struct SysInfoData *pSysInfo = NULL;
static struct AlarmCodeData *pAlarmCode = NULL;
static struct RelayModuleData *ShmRelayModuleData = NULL;
static struct PsuData *ShmPsuData = NULL;
static struct PrimaryMcuData *ShmPrimaryMcuData = NULL;
static DcCommonInfo *ShmDcCommonData = NULL;

static Relay outputRelay = {0};
static Relay regRelay = {0};
static int Uart5Fd = 0;

//static bool _isRelayWelding[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
//static struct timeval _checkRelayWeldingTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];

//static bool _isOutputNoneMatch[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
//static struct timeval _checkOutputNoneMatchTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];

static bool _isOvpChkTimeFlag[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add
static struct timeval _checkOutputVolProtectTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY]; //DS60-120 add

static struct timeval _close_ac_contactor;

//------------------------------------------------------------------------------
static void RunForceStopProcess(void)
{
    static bool isCriticalStop = NO;
    static struct timeval  _psuCriticalStop;
    uint32_t _timebuf;

    if (isCriticalStop == NO) {
        isCriticalStop = YES;
        gettimeofday(&_psuCriticalStop, NULL);
    } else {
        _timebuf = GetTimeoutValue(_psuCriticalStop);

        if (_timebuf < 0) {
            gettimeofday(&_psuCriticalStop, NULL);
        } else {
            if (_timebuf / 1000 >= (FORCE_STOP_TIME * 1000)) {
                isCriticalStop = NO;
                pAlarmCode->AlarmEvents.bits.PsuFailureAlarm = NORMAL;
            }
        }
    }
}

static void StopCheckRelayInfo(uint8_t _chkIndex)
{
    if (ShmDcCommonData->CheckRelayStatus[_chkIndex] != STOP) {
        ShmDcCommonData->CheckRelayStatus[_chkIndex] = STOP;
    }
}

static void StartCheckRelayInfo(uint8_t _chkIndex, uint8_t toState)
{
    // SMR1 *2 + SMR2 * 2 + Parallel * 2
    static time_t lastCheckRelayStateTimer[6] = {0};
    time_t nowTime = {0};
    //uint8_t *pCheckRelayState = (uint8_t *)ShmDcCommonData->CheckRelayStatus[_chkIndex];

    if (ShmDcCommonData->CheckRelayStatus[_chkIndex] == STOP) {
        time(&lastCheckRelayStateTimer[_chkIndex]);
        ShmDcCommonData->CheckRelayStatus[_chkIndex] = START;
    } else {
        time(&nowTime);

        if (nowTime - lastCheckRelayStateTimer[_chkIndex] >= 1) {
            //log_info("relay welding or driving fault = %d \n", _chkIndex);
            if (toState == 1) {
                ShmDcCommonData->CheckRelayStatus[_chkIndex] = RELAY_STATUS_ERROR_DRIVING;
            } else {
                ShmDcCommonData->CheckRelayStatus[_chkIndex] = RELAY_STATUS_ERROR_WELDING;
            }
            lastCheckRelayStateTimer[_chkIndex] = nowTime;
        }
    }
}

static uint8_t getCommTargetID(uint8_t index)
{
    uint8_t targetID = 0;
    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);

    if (pSysConfig->TotalConnectorCount == 1) {
        if (strncmp((char *)&pSysConfig->ModelName[7], "0", 1) != 0) {
            targetID = 0x01;
        } else if (strncmp((char *)&pSysConfig->ModelName[9], "0", 1) != 0) {
            targetID = 0x02;
        }
    } else {
        targetID = pDcChargingInfo->Evboard_id;
    }

    return targetID;
}

/*static void MatchRelayStatus(void)
{
    // 因為 AC Contactor 沒有 Feedback,所以暫時先這樣處理
    //regRelay.relay_event.bits.AC_Contactor = outputRelay.relay_event.bits.AC_Contactor;
    //pSysInfo->AcContactorStatus =
    //    regRelay.relay_event.bits.AC_Contactor =
    //        outputRelay.relay_event.bits.AC_Contactor;
    regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
    regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
    regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
    regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
    regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
    regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
    regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;
}
*/

static bool IsNoneMatchRelayStatus(void)
{
    bool result = false;

    if (
#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
        (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) ||
        (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) ||
#endif //!defined DD360 && !defined DD360Audi
        (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) ||
        (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) ||
        (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) ||
        (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N)
#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
        ||
        (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) ||
        (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N)
#endif //!defined DD360 && !defined DD360Audi
    ) {
        result = true;
    }

#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
    if (regRelay.relay_event.bits.AC_Contactor != outputRelay.relay_event.bits.AC_Contactor) {
        log_info("AC Contact Relay none match. \n");
    }

    if (regRelay.relay_event.bits.CCS_Precharge != outputRelay.relay_event.bits.CCS_Precharge) {
        log_info("CCS Precharge Relay none match. \n");
    }
#endif //

    if (regRelay.relay_event.bits.Gun1_P != outputRelay.relay_event.bits.Gun1_P) {
        //log_info("SMR1:D+ Relay none match. \n");
        StartCheckRelayInfo(RELAY_SMR1_P_STATUS, outputRelay.relay_event.bits.Gun1_P);
    } else {
        StopCheckRelayInfo(RELAY_SMR1_P_STATUS);
    }

    if (regRelay.relay_event.bits.Gun1_N != outputRelay.relay_event.bits.Gun1_N) {
        //log_info("SMR1:D- Relay none match. \n");
        StartCheckRelayInfo(RELAY_SMR1_N_STATUS, outputRelay.relay_event.bits.Gun1_N);
    } else {
        StopCheckRelayInfo(RELAY_SMR1_N_STATUS);
    }

    if (regRelay.relay_event.bits.Gun2_P != outputRelay.relay_event.bits.Gun2_P) {
        //log_info("SMR2:D+ Relay none match. \n");
        StartCheckRelayInfo(RELAY_SMR2_P_STATUS, outputRelay.relay_event.bits.Gun2_P);
    } else {
        StopCheckRelayInfo(RELAY_SMR2_P_STATUS);
    }

    if (regRelay.relay_event.bits.Gun2_N != outputRelay.relay_event.bits.Gun2_N) {
        //log_info("SMR2:D- Relay none match. \n");
        StartCheckRelayInfo(RELAY_SMR2_N_STATUS, outputRelay.relay_event.bits.Gun2_N);
    } else {
        StopCheckRelayInfo(RELAY_SMR2_N_STATUS);
    }

#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
    if (regRelay.relay_event.bits.Gun1_Parallel_P != outputRelay.relay_event.bits.Gun1_Parallel_P) {
        //log_info("Parallel:D+ Relay none match. \n");
        StartCheckRelayInfo(RELAY_PARA_P_STATUS, outputRelay.relay_event.bits.Gun1_Parallel_P);
    } else {
        StopCheckRelayInfo(RELAY_PARA_P_STATUS);
    }

    if (regRelay.relay_event.bits.Gun1_Parallel_N != outputRelay.relay_event.bits.Gun1_Parallel_N) {
        //log_info("Parallel:D- Relay none match. \n");
        StartCheckRelayInfo(RELAY_PARA_N_STATUS, outputRelay.relay_event.bits.Gun1_Parallel_N);
    } else {
        StopCheckRelayInfo(RELAY_PARA_N_STATUS);
    }
#endif //

    return result;
}

static void SetParalleRelayStatus(void)
{
#if defined DD360 || defined DD360Audi || defined DD360ComBox
    return;
#endif //!defined  DD360 || !defined DD360Audi || !defined DD360ComBox

    struct ChargingInfoData *pDcChargingInfo0 = (struct ChargingInfoData *)GetDcChargingInfoData(0);
    struct ChargingInfoData *pDcChargingInfo1 = (struct ChargingInfoData *)GetDcChargingInfoData(1);

    // 之後雙槍單模機種,橋接都會上
    if (pSysConfig->TotalConnectorCount >= 2) {
        if (pDcChargingInfo0->SystemStatus == S_BOOTING || pDcChargingInfo1->SystemStatus == S_BOOTING ||
                (pDcChargingInfo0->SystemStatus == S_IDLE && pDcChargingInfo1->SystemStatus == S_IDLE)) {
            // 初始化~ 不搭橋接
            if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
                outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
            } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
                outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
            }
        } else {
            if (pDcChargingInfo0->IsReadyToCharging == YES ||
                    pDcChargingInfo1->IsReadyToCharging == YES) {
                // ************需考慮在切換中 - 切開 relay 與搭回 relay 的時機點************
                if (pSysInfo->MainChargingMode == _MAIN_CHARGING_MODE_MAX) {
                    if (pSysInfo->ReAssignedFlag < _REASSIGNED_RELAY_M_TO_A) {
                        // 最大充 - 搭上橋接
                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
                        }
                    } else {
                        // 平均充 - 不搭
                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
                        }
                    }
                } else if (pSysInfo->MainChargingMode == _MAIN_CHARGING_MODE_AVER) {
                    if (pSysInfo->ReAssignedFlag < _REASSIGNED_RELAY_A_TO_M) {
                        // 平均充 - 不搭
                        if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
                            outputRelay.relay_event.bits.Gun1_Parallel_P = NO;
                        } else if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
                            outputRelay.relay_event.bits.Gun1_Parallel_N = NO;
                        }
                    } else {
                        // 最大充 - 搭上橋接
                        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO) {
                            outputRelay.relay_event.bits.Gun1_Parallel_N = YES;
                        } else if (regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
                            outputRelay.relay_event.bits.Gun1_Parallel_P = YES;
                        }
                    }
                }
            }
        }
    }
}

static void GetGfdAdc(void)
{
    int gunIndex = 0;
    uint8_t targetID = 0;
    struct ChargingInfoData *pDcChargingInfo = NULL;
    Gfd gfd_adc = {0};

    // define : 每 0.2 ~ 1 秒一次
    // occur : <= 75k 歐姆 @ 150 - 750 Vdc
    // warning : >= 100 歐姆 && <= 500 歐姆 @ 150-750 Vdc
    if (Query_Gfd_Adc(Uart5Fd, ADDR_RELAY, &gfd_adc) == PASS) {
        for (gunIndex = 0; gunIndex < pSysConfig->TotalConnectorCount; gunIndex++) {
            pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gunIndex);

            if (pDcChargingInfo->Type == 0x09 &&
                    !pSysConfig->AlwaysGfdFlag
               ) {
                if ((pDcChargingInfo->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE) {
                    pDcChargingInfo->GroundFaultStatus = GFD_PASS;
                }
                continue;
            }

            targetID = getCommTargetID(gunIndex);

            if (targetID == 0x01) {
                //if (gfd_adc.result_conn1 == GFD_WARNING) {
                //    gfd_adc.result_conn1 = GFD_PASS;
                //}

                pDcChargingInfo->GroundFaultStatus = gfd_adc.result_conn1;
                //log_info("GFD ******** Result = %d, Step = %d, R = %d, Vol = %d \n",
                //            pDcChargingInfo->GroundFaultStatus,
                //            gfd_adc.rb_step_1,
                //            gfd_adc.Resister_conn1,
                //            gfd_adc.voltage_conn1);
                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d \n",
                             gunIndex,
                             gfd_adc.rb_step_1,
                             gfd_adc.Resister_conn1,
                             gfd_adc.voltage_conn1);

                } else if (pDcChargingInfo->GroundFaultStatus == GFD_PASS ||
                           pDcChargingInfo->GroundFaultStatus == GFD_WARNING
                          ) {
                    if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING) {
                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d \n",
                                 gunIndex,
                                 pDcChargingInfo->GroundFaultStatus,
                                 gfd_adc.Resister_conn1,
                                 gfd_adc.voltage_conn1);
                    }
                }
            } else if (targetID == 0x02) {
                //if (gfd_adc.result_conn2 == GFD_WARNING) {
                //    gfd_adc.result_conn2 = GFD_PASS;
                //}
                pDcChargingInfo->GroundFaultStatus = gfd_adc.result_conn2;
                if (pDcChargingInfo->GroundFaultStatus == GFD_FAIL) {
                    log_info("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d \n",
                             gunIndex,
                             gfd_adc.rb_step_2,
                             gfd_adc.Resister_conn2,
                             gfd_adc.voltage_conn2);
                } else if (pDcChargingInfo->GroundFaultStatus == GFD_PASS ||
                           pDcChargingInfo->GroundFaultStatus == GFD_WARNING
                          ) {
                    if (pDcChargingInfo->GroundFaultStatus == GFD_WARNING) {
                        log_info("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d \n",
                                 gunIndex,
                                 pDcChargingInfo->GroundFaultStatus,
                                 gfd_adc.Resister_conn1,
                                 gfd_adc.voltage_conn1);
                    }
                }
            }
        }
    }
}

void CheckOutputPowerOverCarReq(uint8_t index)
{
    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);

    float fireV = pDcChargingInfo->FireChargingVoltage;
    float carV = pDcChargingInfo->EvBatteryMaxVoltage * 10;

    if ((pDcChargingInfo->EvBatterytargetVoltage * 10) > 1500 &&
            (pDcChargingInfo->Type == _Type_Chademo ||
             pDcChargingInfo->Type == _Type_CCS_2 ||
             pDcChargingInfo->Type == _Type_GB)) {
        if (fireV >= (carV + (carV * 0.02))) {
            if (!_isOvpChkTimeFlag[index]) {
                if ((pDcChargingInfo->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE * 10) {
                    gettimeofday(&_checkOutputVolProtectTimer[index], NULL);
                    _isOvpChkTimeFlag[index] = YES;
                }
            } else {
                log_info("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f \n",
                         pDcChargingInfo->FireChargingVoltage,
                         (pDcChargingInfo->EvBatterytargetVoltage * 10));

                log_error("[Module_InternalComm]CheckOutputPowerOverCarReq NG : fire = %f, battery = %f \n",
                          pDcChargingInfo->FireChargingVoltage,
                          (pDcChargingInfo->EvBatterytargetVoltage * 10));
                if ((GetTimeoutValue(_checkOutputVolProtectTimer[index]) / 1000) >= OUTPUT_VOL_CHK_TIME) {
                    if (pDcChargingInfo->Type == _Type_Chademo) {
                        pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = YES;
                    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
                        pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = YES;
                    } else if (pDcChargingInfo->Type == _Type_GB) {
                        pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = YES;
                    }
                    pDcChargingInfo->StopChargeFlag = YES;
                }
            }
        } else {
            if (_isOvpChkTimeFlag[index] == YES) {
                _isOvpChkTimeFlag[index] = NO;
            }
        }
    }
}

void ResetDetAlarmStatus(uint8_t gun)
{
    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(gun);

    if (pDcChargingInfo->Type == _Type_Chademo) {
        if (pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP == YES) {
            pAlarmCode->AlarmEvents.bits.SystemChademoOutputOVP = NO;
        }
    } else if (pDcChargingInfo->Type == _Type_GB) {
        if (pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP == YES) {
            pAlarmCode->AlarmEvents.bits.SystemGbOutputOVP = NO;
        }
    } else if (pDcChargingInfo->Type == _Type_CCS_2) {
        if (pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP == YES) {
            pAlarmCode->AlarmEvents.bits.SystemCcsOutputOVP = NO;
        }
    }
}

void CheckAcInputOvpStatus(uint8_t index)
{
    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);

    if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == YES ||
            pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == YES ||
            pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == YES) {
//      if ((pDcChargingInfo->SystemStatus >= S_PREPARNING && pDcChargingInfo->SystemStatus <= S_CHARGING) ||
//              (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 && pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1))
//      {
//          if (pSysInfo->ChargerType == _CHARGER_TYPE_IEC)
//          {
//              if (_psuInputVolR > VIN_MAX_VOLTAGE_IEC ||
//                      _psuInputVolS > VIN_MAX_VOLTAGE_IEC ||
//                      _psuInputVolT > VIN_MAX_VOLTAGE_IEC)
//              {
//                  log_info("IEC _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f \n",
//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
//                  pDcChargingInfo->StopChargeFlag = YES;
//              }
//
//          }
//          else if (pSysInfo->ChargerType == _CHARGER_TYPE_UL)
//          {
//              if (_psuInputVolR > VIN_MAX_VOLTAGE_UL ||
//                      _psuInputVolS > VIN_MAX_VOLTAGE_UL ||
//                      _psuInputVolT > VIN_MAX_VOLTAGE_UL)
//              {
//                  log_info("UL _psuInputVolR = %f, _psuInputVolS = %f, _psuInputVolT = %f \n",
//                          _psuInputVolR, _psuInputVolS, _psuInputVolT);
//                  pDcChargingInfo->StopChargeFlag = YES;
//              }
//          }
//      }
//      else
        //log_info("CheckAcInputOvpStatus\r\n");
        pDcChargingInfo->StopChargeFlag = YES;
    }
}

//void CheckOutputVolNoneMatchFire(uint8_t index)
//{
//    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
//
//    if ((pDcChargingInfo->EvBatterytargetVoltage * 10) > 1500 &&
//            (pDcChargingInfo->Type == _Type_Chademo ||
//             pDcChargingInfo->Type == _Type_CCS_2 ||
//             pDcChargingInfo->Type == _Type_GB)) {
//        if (((pDcChargingInfo->PresentChargingVoltage * 10) < pDcChargingInfo->FireChargingVoltage - 300) ||
//                ((pDcChargingInfo->PresentChargingVoltage * 10) > pDcChargingInfo->FireChargingVoltage + 300)) {
//            if (!_isOutputNoneMatch[index]) {
//                _isOutputNoneMatch[index] = YES;
//                gettimeofday(&_checkOutputNoneMatchTimer[index], NULL);
//            } else {
//                if ((GetTimeoutValue(_checkOutputNoneMatchTimer[index]) / 1000) >= 5000) {
//                    /*log_info("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d) : pre = %f, fire = %f \n",
//                            index, (pDcChargingInfo->PresentChargingVoltage * 10), pDcChargingInfo->FireChargingVoltage);
//                    log_error("[Module_InternalComm]CheckOutputVolNoneMatchFire NG (%d): pre = %f, fire = %f \n",
//                            index, (pDcChargingInfo->PresentChargingVoltage * 10), pDcChargingInfo->FireChargingVoltage);
//                    pDcChargingInfo->StopChargeFlag = YES;*/
//                }
//            }
//        } else {
//            _isOutputNoneMatch[index] = NO;
//        }
//    }
//}

void CheckPhaseLossStatus(uint8_t index)
{
    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);

    if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == YES ||
            pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == YES ||
            pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == YES) {
        //log_info("CheckPhaseLossStatus\r\n");
        pDcChargingInfo->StopChargeFlag = YES;
    }
}

void SetK1K2RelayStatus(uint8_t index)
{
    uint8_t targetID = 0;
    PreChargingState *pRegPreChargingState = NULL;
    PreChargingState *pOutputPreChargingState = NULL;
    GunPNState *pRegGunPNState = NULL;
    GunPNState *pOutputGunPNState = NULL;
    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);

    if (ShmPsuData->Work_Step >= _TEST_MODE &&
            ShmPsuData->Work_Step <= _TEST_MODE) {
        if (regRelay.relay_event.bits.Gun1_N == NO) {
            outputRelay.relay_event.bits.Gun1_N = YES;
        } else if (regRelay.relay_event.bits.Gun1_P == NO) {
            outputRelay.relay_event.bits.Gun1_P = YES;
        }
        return;
    }

    targetID = getCommTargetID(index);

    pRegPreChargingState = (PreChargingState *)&regRelay.relay_event.relay_status[0];
    pOutputPreChargingState = (PreChargingState *)&outputRelay.relay_event.relay_status[0];
    if (targetID == 0x01) {
        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[1];
        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[1];
    } else if (targetID == 0x02) {
        pRegGunPNState = (GunPNState *)&regRelay.relay_event.relay_status[2];
        pOutputGunPNState = (GunPNState *)&outputRelay.relay_event.relay_status[2];
    }

    switch (pDcChargingInfo->SystemStatus) {
    case S_BOOTING:
    case S_IDLE:
    case S_AUTHORIZING:
    case S_REASSIGN_CHECK:
    case S_REASSIGN:
    case S_PREPARNING:
    case S_PREPARING_FOR_EV:
        if (pRegGunPNState->GunP == YES) {
            pOutputGunPNState->GunP = NO;
        } else if (pRegGunPNState->GunN == YES) {
            pOutputGunPNState->GunN = NO;
        }

        if (targetID == 0x02 && pDcChargingInfo->Type == _Type_CCS_2) {
            if (pRegPreChargingState->CcsPrecharge == YES) {
                pOutputPreChargingState->CcsPrecharge = NO;
            }
        }
        break;

    case S_PREPARING_FOR_EVSE:
    case S_CHARGING:
        //if (pDcChargingInfo->RelayWeldingCheck != YES) {
        //    break;
        //}

        if (pRegGunPNState->GunN == NO) {
            pOutputGunPNState->GunN = YES;
        } else if (pRegGunPNState->GunP == NO) {
            pOutputGunPNState->GunP = YES;
        }
        break;

    case S_TERMINATING:
    case S_COMPLETE:
    case S_ALARM:
        if ((pDcChargingInfo->PresentChargingCurrent * 10) <= SEFETY_SWITCH_RELAY_CUR) {
            if (pRegGunPNState->GunP == YES) {
                pOutputGunPNState->GunP = NO;
            } else if (pRegGunPNState->GunN == YES) {
                pOutputGunPNState->GunN = NO;
            }
        }
        break;

    case S_CCS_PRECHARGE_ST0:
#if defined DD360 || defined DD360Audi || defined DD360ComBox
        break;
#endif //defined DD360 || defined DD360Audi || defined DD360ComBox

        //if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
        //    if (pRegPreChargingState->CcsPrecharge == NO) {
        //        pOutputPreChargingState->CcsPrecharge = YES;
        //    } else if (pRegPreChargingState->CcsPrecharge == YES) {
        //        pRegGunPNState->GunP = NO;
        //    }
        //}
        break;

    case S_CCS_PRECHARGE_ST1:
#if defined DD360 || defined DD360Audi || defined DD360ComBox
        break;
#endif //defined DD360 || defined DD360Audi || defined DD360ComBox

        //if (pDcChargingInfo->Type == _Type_CCS_2 && targetID == 0x02) {
        //    if (pRegGunPNState->GunP == NO) {
        //        pOutputGunPNState->GunP = YES;
        //    } else if (pRegGunPNState->GunP == YES) {
        //        pOutputPreChargingState->CcsPrecharge = NO;
        //    }
        //}
        break;
    }
}

// 確認 K1 K2 relay 的狀態
void CheckK1K2RelayOutput(uint8_t index)
{
    uint8_t targetID = 0;
    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);

    targetID = getCommTargetID(index);

    switch (targetID) {
    case 0x01:
        if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.Gun1_P == YES) {
            pDcChargingInfo->RelayK1K2Status = YES;
        } else {
            pDcChargingInfo->RelayK1K2Status = NO;
        }

        if (pDcChargingInfo->Type == _Type_CCS_2) {
#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
            if (regRelay.relay_event.bits.Gun1_N == YES && regRelay.relay_event.bits.CCS_Precharge == YES) {
                pDcChargingInfo->RelayKPK2Status = YES;
            } else {
                pDcChargingInfo->RelayKPK2Status = NO;
            }
#else
            if (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0) {
                pDcChargingInfo->RelayKPK2Status = YES;
            } else {
                pDcChargingInfo->RelayKPK2Status = NO;
            }
#endif //!defined DD360 && !defined DD360Audi
        }
        break;

    case 0x02:
        if (regRelay.relay_event.bits.Gun2_N == YES &&
                regRelay.relay_event.bits.Gun2_P == YES) {
            pDcChargingInfo->RelayK1K2Status = YES;
        } else {
            pDcChargingInfo->RelayK1K2Status = NO;
        }

        if (pDcChargingInfo->Type == _Type_CCS_2) {
#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
            if (regRelay.relay_event.bits.Gun2_N == YES &&
                    regRelay.relay_event.bits.CCS_Precharge == YES) {
                pDcChargingInfo->RelayKPK2Status = YES;
            } else {
                pDcChargingInfo->RelayKPK2Status = NO;
            }
#else
            if (pDcChargingInfo->SystemStatus == S_CCS_PRECHARGE_ST0) {
                pDcChargingInfo->RelayKPK2Status = YES;
            } else {
                pDcChargingInfo->RelayKPK2Status = NO;
            }
#endif //!defined DD360 && !defined DD360Audi
        }
        break;
    }

#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
    //DS60-120 add
    if (pSysInfo->BridgeRelayStatus == YES) {
        if (regRelay.relay_event.bits.Gun1_Parallel_N == NO &&
                regRelay.relay_event.bits.Gun1_Parallel_P == NO) {
            pSysInfo->BridgeRelayStatus = NO;
        }
    } else if (pSysInfo->BridgeRelayStatus == NO) {
        if (regRelay.relay_event.bits.Gun1_Parallel_N == YES &&
                regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
            pSysInfo->BridgeRelayStatus = YES;
        }
    }
#else
    pSysInfo->BridgeRelayStatus = YES;
#endif //!defined DD360 && !defined DD360Audi
}

void SetGfdConfig(uint8_t index, uint8_t resister)
{
    Gfd_config gfd_config = {
        .index = index,
        .state = resister,
    };

    //log_info("************************GFD Vol = %d, GFD Res = %d \n", gfd_config.reqVol, gfd_config.resister);
    if (Config_Gfd_Value(Uart5Fd, ADDR_RELAY, &gfd_config) == PASS) {
//      log_info("Set reqVol = %f, resister = %d \n",
//              gfd_config.reqVol,
//              gfd_config.resister);
    }
}

void CableCheckDetected(uint8_t index)
{
    uint8_t targetID = 0;
    struct ChargingInfoData *pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
    // Cable Check
    // 當火線上的電壓 = 車端要求的電壓電流
    // _chargingData[targetGun]->EvBatterytargetVoltage
    // 才可以開始偵測 1s
    // Warning : Rgfd <= 150 歐/V 假設電壓為 500V 則~ Rgfd <= 75000 歐
    // Pre-Warning : 150 歐/V < Rgfd <= 500 歐/V 假設電壓為 500V 則 75000 歐 < Rgfd <= 250000
    // SO Normal : Rgfd > 500 歐/V 假設電壓為 500 V 則 Rgfd > 250000 歐

    if (pSysConfig->TotalConnectorCount == 1) {
        if (strncmp((char *)&pSysConfig->ModelName[7], "0", 1) != 0) {
            targetID = 0;
        } else if (strncmp((char *)&pSysConfig->ModelName[9], "0", 1) != 0) {
            targetID = 1;
        }
    } else {
        targetID = index;
    }

    if ((pDcChargingInfo->Type >= _Type_Chademo &&
            pDcChargingInfo->Type <= _Type_GB) ||
            (pDcChargingInfo->Type == 0x09 &&
             pSysConfig->AlwaysGfdFlag)
       ) {
        if ((pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
                pDcChargingInfo->SystemStatus <= S_TERMINATING) ||
                (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
                 pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
           ) {
            //if ((pDcChargingInfo->SystemStatus == S_PREPARING_FOR_EVSE) &&
            //        (pDcChargingInfo->RelayWeldingCheck == YES)
            //   ) {
            if (pDcChargingInfo->SystemStatus == S_PREPARING_FOR_EVSE) {
                SetGfdConfig(targetID, GFD_CABLECHK);
            } else if ((pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0) &&
                       (pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1)
                      ) {
                SetGfdConfig(targetID, GFD_PRECHARGE);
            } else if ((pDcChargingInfo->SystemStatus >= S_CHARGING) &&
                       (pDcChargingInfo->SystemStatus <= S_TERMINATING)
                      ) {
                if ((pDcChargingInfo->Type == _Type_GB) ||
                        (pDcChargingInfo->Type == _Type_Chademo)
                   ) {
                    SetGfdConfig(targetID, GFD_IDLE);
                } else {
                    SetGfdConfig(targetID, GFD_CHARGING);
                }
            }
        } else if (pDcChargingInfo->SystemStatus == S_COMPLETE ||
                   pDcChargingInfo->SystemStatus == S_PREPARNING ||
                   pDcChargingInfo->SystemStatus == S_IDLE) {
            SetGfdConfig(targetID, GFD_IDLE);
        }
    }
}

// 讀取 Relay 狀態
void GetRelayOutputStatus(void)
{
    if (Query_Relay_Output(Uart5Fd, ADDR_RELAY, &regRelay) == PASS) {
#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
        regRelay.relay_event.bits.AC_Contactor = pSysInfo->AcContactorStatus;
#endif //!defined DD360 && !defined DD360Audi
    }
}

// AC 三相輸入電壓
void GetPresentInputVol(void)
{
    static uint8_t _threePhaseOvp[3] = {0, 0, 0}; //DS60-120 add
    static uint8_t _threePhaseUvp[3] = {0, 0, 0}; //DS60-120 add
    PresentInputVoltage inputVoltage = {0};

    if (Query_Present_InputVoltage(Uart5Fd, ADDR_RELAY, &inputVoltage) == PASS) {
        // resolution : 0.1
        pSysInfo->InputVoltageR = ShmRelayModuleData->InputL1Volt = inputVoltage.L1N_L12;
        pSysInfo->InputVoltageS = ShmRelayModuleData->InputL2Volt = inputVoltage.L2N_L23;
        pSysInfo->InputVoltageT = ShmRelayModuleData->InputL3Volt = inputVoltage.L3N_L31;

        //********************************************************************************************************//
        // Vin (UVP)
        if (pSysInfo->ChargerType == _CHARGER_TYPE_IEC) {
            if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == NO) {
                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_IEC) {
                    log_info("In Uvp L1N_L12 = %f \n", inputVoltage.L1N_L12);
                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = YES;
                    } else {
                        _threePhaseUvp[0] += 1;
                    }
                }
            } else {
                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_IEC) {
                    pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = NO;
                    _threePhaseUvp[0] = 0;
                }
            }

            if (pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == NO) {
                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_IEC) {
                    log_info("In Uvp L2N_L23 = %f \n", inputVoltage.L2N_L23);
                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = YES;
                    } else {
                        _threePhaseUvp[1] += 1;
                    }
                }
            } else {
                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_IEC) {
                    pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = NO;
                    _threePhaseUvp[1] = 0;
                }
            }

            if (pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == NO) {
                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_IEC) {
                    log_info("In Uvp L3N_L31 = %f \n", inputVoltage.L3N_L31);
                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = YES;
                    } else {
                        _threePhaseUvp[2] += 1;
                    }
                }
            } else {
                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_IEC) {
                    pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = NO;
                    _threePhaseUvp[2] = 0;
                }
            }
        } else if (pSysInfo->ChargerType == _CHARGER_TYPE_UL) {
            if (pAlarmCode->AlarmEvents.bits.SystemL1InputUVP == NO) {
                if (inputVoltage.L1N_L12 < VIN_MIN_VOLTAGE_UL) {
                    log_info("In Uvp L1N_L12 = %f \n", inputVoltage.L1N_L12);
                    if (_threePhaseUvp[0] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = YES;
                    } else {
                        _threePhaseUvp[0] += 1;
                    }
                }
            } else {
                if (inputVoltage.L1N_L12 > VIN_MIN_REV_VOLTAGE_UL) {
                    pAlarmCode->AlarmEvents.bits.SystemL1InputUVP = NO;
                    _threePhaseUvp[0] = 0;
                }
            }

            if (pAlarmCode->AlarmEvents.bits.SystemL2InputUVP == NO) {
                if (inputVoltage.L2N_L23 < VIN_MIN_VOLTAGE_UL) {
                    log_info("In Uvp L2N_L23 = %f \n", inputVoltage.L2N_L23);
                    if (_threePhaseUvp[1] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = YES;
                    } else {
                        _threePhaseUvp[1] += 1;
                    }
                }
            } else {
                if (inputVoltage.L2N_L23 > VIN_MIN_REV_VOLTAGE_UL) {
                    pAlarmCode->AlarmEvents.bits.SystemL2InputUVP = NO;
                    _threePhaseUvp[1] = 0;
                }
            }

            if (pAlarmCode->AlarmEvents.bits.SystemL3InputUVP == NO) {
                if (inputVoltage.L3N_L31 < VIN_MIN_VOLTAGE_UL) {
                    log_info("In Uvp L3N_L31 = %f \n", inputVoltage.L3N_L31);
                    if (_threePhaseUvp[2] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = YES;
                    } else {
                        _threePhaseUvp[2] += 1;
                    }
                }
            } else {
                if (inputVoltage.L3N_L31 > VIN_MIN_REV_VOLTAGE_UL) {
                    pAlarmCode->AlarmEvents.bits.SystemL3InputUVP = NO;
                    _threePhaseUvp[2] = 0;
                }
            }
        }

        //********************************************************************************************************//
        // Vin (OVP)
        if (pSysInfo->ChargerType == _CHARGER_TYPE_IEC) {
            if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == NO) {
                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_IEC) {
                    log_info("In Ovp L1N_L12 = %f \n", inputVoltage.L1N_L12);
                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = YES;
                    } else {
                        _threePhaseOvp[0] += 1;
                    }
                }
            } else {
                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_IEC) {
                    pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = NO;
                    _threePhaseOvp[0] = 0;
                }
            }

            if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == NO) {
                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_IEC) {
                    log_info("In Ovp L2N_L23 = %f \n", inputVoltage.L2N_L23);
                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = YES;
                    } else {
                        _threePhaseOvp[1] += 1;
                    }
                }
            } else {
                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_IEC) {
                    pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = NO;
                    _threePhaseOvp[1] = 0;
                }
            }

            if (pAlarmCode->AlarmEvents.bits.SystemL3InputOVP == NO) {
                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_IEC) {
                    log_info("In Ovp L3N_L31 = %f \n", inputVoltage.L3N_L31);
                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = YES;
                    } else {
                        _threePhaseOvp[2] += 1;
                    }
                }
            } else {
                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_IEC) {
                    pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = NO;
                    _threePhaseOvp[2] = 0;
                }
            }
        } else if (pSysInfo->ChargerType == _CHARGER_TYPE_UL) {
            if (pAlarmCode->AlarmEvents.bits.SystemL1InputOVP == NO) {
                if (inputVoltage.L1N_L12 > VIN_MAX_VOLTAGE_UL) {
                    log_info("In Ovp L1N_L12 = %f \n", inputVoltage.L1N_L12);
                    if (_threePhaseOvp[0] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = YES;
                    } else {
                        _threePhaseOvp[0] += 0;
                    }
                }
            } else {
                if (inputVoltage.L1N_L12 < VIN_MAX_REV_VOLTAGE_UL) {
                    pAlarmCode->AlarmEvents.bits.SystemL1InputOVP = NO;
                    _threePhaseOvp[0] = 0;
                }
            }

            if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == NO) {
                if (inputVoltage.L2N_L23 > VIN_MAX_VOLTAGE_UL) {
                    log_info("In Ovp L2N_L23 = %f \n", inputVoltage.L2N_L23);
                    if (_threePhaseOvp[1] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = YES;
                    } else {
                        _threePhaseOvp[1] += 0;
                    }
                }
            } else {
                if (inputVoltage.L2N_L23 < VIN_MAX_REV_VOLTAGE_UL) {
                    pAlarmCode->AlarmEvents.bits.SystemL2InputOVP = NO;
                    _threePhaseOvp[1] = 0;
                }
            }

            if (pAlarmCode->AlarmEvents.bits.SystemL2InputOVP == NO) {
                if (inputVoltage.L3N_L31 > VIN_MAX_VOLTAGE_UL) {
                    log_info("In Ovp L3N_L31 = %f \n", inputVoltage.L3N_L31);
                    if (_threePhaseOvp[2] >= OVP_UVP_CHK_COUNT) {
                        pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = YES;
                    } else {
                        _threePhaseOvp[2] += 1;
                    }
                }
            } else {
                if (inputVoltage.L3N_L31 < VIN_MAX_REV_VOLTAGE_UL) {
                    pAlarmCode->AlarmEvents.bits.SystemL3InputOVP = NO;
                    _threePhaseOvp[2] = 0;
                }
            }
        }
    }
}

// 左右槍的 Relay 前後的輸出電壓
void GetPersentOutputVol(void)
{
    uint8_t index = 0;
    uint8_t targetID = 0;
    struct ChargingInfoData *pDcChargingInfo = NULL;
    PresentOutputVoltage outputVoltage = {0};

    if (Query_Present_OutputVoltage(Uart5Fd, ADDR_RELAY, &outputVoltage) != PASS) {
        return;
    }

    //log_info("Conn1 fuse 1 = %f \n", outputVoltage.behindFuse_Voltage_C1);
    //log_info("Conn1 relay 1 = %f \n", outputVoltage.behindRelay_Voltage_C1);
    //log_info("Conn2 fuse 2 = %f \n", outputVoltage.behindFuse_Voltage_C2);
    //log_info("Conn2 relay 2 = %f \n", outputVoltage.behindRelay_Voltage_C2);

    //log_info("outputVoltage.behindFuse_Voltage_C1 = %f \n", outputVoltage.behindFuse_Voltage_C1);
    //log_info("outputVoltage.behindFuse_Voltage_C2 = %f \n", outputVoltage.behindFuse_Voltage_C2);

    ShmRelayModuleData->Gun1FuseOutputVolt = outputVoltage.behindFuse_Voltage_C1;
    ShmRelayModuleData->Gun1RelayOutputVolt = outputVoltage.behindRelay_Voltage_C1;
    ShmRelayModuleData->Gun2FuseOutputVolt = outputVoltage.behindFuse_Voltage_C2;
    ShmRelayModuleData->Gun2RelayOutputVolt = outputVoltage.behindRelay_Voltage_C2;

    for (index = 0; index < pSysConfig->TotalConnectorCount; index++) {
        pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(index);
        targetID = getCommTargetID(index);

        switch (targetID) {
        case 0x01:
#if defined DD360 || defined DD360Audi || defined DD360ComBox
            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
            pDcChargingInfo->PresentChargingCurrent = ShmRelayModuleData->Gun1FuseOutputVolt / 10;
            pDcChargingInfo->PresentChargingVoltage = pDcChargingInfo->FireChargingVoltage / 10;
            pDcChargingInfo->FuseChargingVoltage = pDcChargingInfo->FireChargingVoltage;
            break;
#endif //defined DD360 || defined DD360Audi || defined DD360ComBox

            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun1RelayOutputVolt;
            pDcChargingInfo->FuseChargingVoltage = ShmRelayModuleData->Gun1FuseOutputVolt;
            break;

        case 0x02:
#if defined DD360 || defined DD360Audi || defined DD360ComBox
            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
            pDcChargingInfo->PresentChargingCurrent = ShmRelayModuleData->Gun2FuseOutputVolt / 10;
            pDcChargingInfo->PresentChargingVoltage = pDcChargingInfo->FireChargingVoltage / 10;
            pDcChargingInfo->FuseChargingVoltage = pDcChargingInfo->FireChargingVoltage;
            break;
#endif //defined DD360 || defined DD360Audi || defined DD360ComBox

            pDcChargingInfo->FireChargingVoltage = ShmRelayModuleData->Gun2RelayOutputVolt;
            pDcChargingInfo->FuseChargingVoltage = ShmRelayModuleData->Gun2FuseOutputVolt;
            break;
        }

        //unsigned short Ovp = 0;
        //unsigned short Ocp = 0;
        //Ovp = MIN [VOUT_MAX_VOLTAGE, EV_BATTERY_VOLTAGE]  // 最大輸出電壓與電池電壓最大值
        //Ocp = MIN [IOUT_MAX_CURRENT, EV_CURRENT_REQ]      // 最大輸出電流與需求電流最小值
        //if (pDcChargingInfo->Type == _Type_Chademo) {
        //    //Ovp = MaxValue(pDcChargingInfo->MaximumChargingVoltage, pDcChargingInfo->EvBatteryMaxVoltage);
        //    //Ocp = MaxValue(pDcChargingInfo->PresentChargingCurrent, ShmCHAdeMOData->ev[pDcChargingInfo->type_index].ChargingCurrentRequest);
        //} else if (pDcChargingInfo->Type == _Type_CCS_2) {
        //}
    }
}

void SetRtcData_Relay(void)
{
    struct timeb csuTime;
    struct tm *tmCSU;
    Rtc rtc = {0};

    ftime(&csuTime);
    tmCSU = localtime(&csuTime.time);
    //  log_info("Time : %04d-%02d-%02d %02d:%02d:%02d \n", tmCSU->tm_year + 1900,
    //          tmCSU->tm_mon + 1, tmCSU->tm_mday, tmCSU->tm_hour, tmCSU->tm_min,
    //          tmCSU->tm_sec);

    rtc.RtcData[0] = '0' + (tmCSU->tm_year + 1900) / 1000 % 10;
    rtc.RtcData[1] = '0' + (tmCSU->tm_year + 1900) / 100 % 10;
    rtc.RtcData[2] = '0' + (tmCSU->tm_year + 1900) / 10 % 10;
    rtc.RtcData[3] = '0' + (tmCSU->tm_year + 1900) / 1 % 10;

    rtc.RtcData[4] = '0' + (tmCSU->tm_mon + 1) / 10 % 10;
    rtc.RtcData[5] = '0' + (tmCSU->tm_mon + 1) / 1 % 10;

    rtc.RtcData[6] = '0' + (tmCSU->tm_mday) / 10 % 10;
    rtc.RtcData[7] = '0' + (tmCSU->tm_mday) / 1 % 10;

    rtc.RtcData[8] = '0' + (tmCSU->tm_hour) / 10 % 10;
    rtc.RtcData[9] = '0' + (tmCSU->tm_hour) / 1 % 10;

    rtc.RtcData[10] = '0' + (tmCSU->tm_min) / 10 % 10;
    rtc.RtcData[11] = '0' + (tmCSU->tm_min) / 1 % 10;

    rtc.RtcData[12] = '0' + (tmCSU->tm_sec) / 10 % 10;
    rtc.RtcData[13] = '0' + (tmCSU->tm_sec) / 1 % 10;

    if (Config_Rtc_Data(Uart5Fd, ADDR_RELAY, &rtc) == PASS) {
        //log_info("SetRtc (RB) sucessfully. \n");
    }
}

void SetModelName_Relay(void)
{
    if (Config_Model_Name(Uart5Fd, ADDR_RELAY, pSysConfig->ModelName) == PASS) {
        //log_info("Set Model name (RB) PASS = %s \n", pSysConfig->ModelName);
    }
}

void GetFwAndHwVersion_Relay(void)
{
    Ver ver = {0};

    if (Query_FW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
        // RelayModuleData
        strcpy((char *)ShmRelayModuleData->version, ver.Version_FW);
        // SystemInfo
        strcpy((char *)pSysInfo->RelayModuleFwRev, ver.Version_FW);
        //log_info("GetFwAndHwVersion_Relay s1 = %s \n", ver.Version_FW);
    }

    if (Query_HW_Ver(Uart5Fd, ADDR_RELAY, &ver) == PASS) {
        // SystemInfo
        strcpy((char *)pSysInfo->RelayModuleHwRev, ver.Version_FW);
        //log_info("GetFwAndHwVersion_Relay s2 = %s \n", ver.Version_HW);
    }
}

static void outputRelayInit(int fd)
{
    memset((uint8_t *)&outputRelay, 0, sizeof(Relay));

    if (Config_Relay_Output(fd, ADDR_RELAY, &outputRelay) != PASS) {
        log_info("Config_Relay_Output fail \n");
    }
}

void RelayBoardTask(int uartFD)
{
    pid_t pid = fork();

    if (pid == 0) {
        bool isCharging = false;
        bool isStopChargingCount = false;
        uint8_t i = 0;
        int isContinue = 1;
        struct ChargingInfoData *pDcChargingInfo = NULL;

        //share memory mapping
        pSysConfig = (struct SysConfigData *)GetShmSysConfigData();
        pSysInfo = (struct SysInfoData *)GetShmSysInfoData();
        pAlarmCode = (struct AlarmCodeData *)GetShmAlarmCodeData();
        ShmRelayModuleData = (struct RelayModuleData *)GetShmRelayModuleData();
        ShmPsuData = (struct PsuData *)GetShmPsuData();
        ShmDcCommonData = (DcCommonInfo *)GetShmDcCommonData();
        ShmPrimaryMcuData = (struct PrimaryMcuData *)GetShmPrimaryMcuData();

        Uart5Fd = uartFD;

        //relay init
        outputRelayInit(uartFD);

        while (isContinue) {
            // 程序開始之前~ 必須先確定 FW 版本與硬體版本,確認後!!~ 該模組才算是真正的 Initial Comp.
            if (ShmRelayModuleData->SelfTest_Comp == NO) {
                GetFwAndHwVersion_Relay();
                SetModelName_Relay(); //DS60-120 add
                SetRtcData_Relay();
                sleep(1);

                continue;
            }

            // ==============優先權最高 10 ms ==============
            // 輸出電壓
            GetPersentOutputVol();

#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
            // 三相輸入電壓
            GetPresentInputVol();
#endif //!defined DD360 && !defined DD360Audi

            // 讀取當前 AC relay 狀態
            regRelay.relay_event.bits.AC_Contactor = pSysInfo->AcContactorStatus;

            GetRelayOutputStatus();

            for (i = 0; i < pSysConfig->TotalConnectorCount; i++) {
                pDcChargingInfo = (struct ChargingInfoData *)GetDcChargingInfoData(i);

                // Cable check (Set)
                CableCheckDetected(i);

                // check k1 k2 relay 狀態
                CheckK1K2RelayOutput(i);

                // 依據當前各槍的狀態選擇 搭上/放開 Relay
                SetK1K2RelayStatus(i);

#if !defined DD360 && !defined DD360Audi && !defined DD360ComBox
                if (pSysConfig->PhaseLossPolicy == YES) {
                    CheckPhaseLossStatus(i);
                }

                CheckAcInputOvpStatus(i);
#endif //!defined DD360 && !defined DD360Audi

                if (pDcChargingInfo->SystemStatus == S_IDLE ||
                        pDcChargingInfo->SystemStatus == S_RESERVATION ||
                        pDcChargingInfo->SystemStatus == S_MAINTAIN) {
                    //pDcChargingInfo->RelayWeldingCheck = NO;
                    //_isRelayWelding[i] = NO;
                    _isOvpChkTimeFlag[i] = NO;
                    //ResetDetAlarmStatus(i); //DS60-120 add
                }

                if (pDcChargingInfo->SystemStatus == S_BOOTING ||
                        (pDcChargingInfo->SystemStatus >= S_REASSIGN_CHECK &&
                         pDcChargingInfo->SystemStatus <= S_COMPLETE) ||
                        (pDcChargingInfo->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
                         pDcChargingInfo->SystemStatus <= S_CCS_PRECHARGE_ST1) ||
                        pSysInfo->WaitForPlugit == YES ||
                        (pSysInfo->PageIndex >= _LCM_AUTHORIZING &&
                         pSysInfo->PageIndex <= _LCM_WAIT_FOR_PLUG)
                   ) {
                    pDcChargingInfo->IsReadyToCharging = YES;
                    isCharging = true;

                    // 限定只有在槍類別為 GBT 的時候才做 relay welding 的判斷
                    //if (pDcChargingInfo->Type == _Type_GB) {
                    //    if (pDcChargingInfo->SystemStatus >= S_PREPARING_FOR_EVSE &&
                    //            pDcChargingInfo->RelayWeldingCheck == NO) {
                    //        CheckRelayWeldingStatus(i);
                    //    }
                    //} else {
                    //pDcChargingInfo->RelayWeldingCheck = YES;
                    //}

                    if (pDcChargingInfo->SystemStatus == S_CHARGING) {
                        CheckOutputPowerOverCarReq(i);
                        //CheckOutputVolNoneMatchFire(i);
                    }
                    /*else {
                        _isOutputNoneMatch[i] = NO;
                    }*/
                } else {
                    pDcChargingInfo->IsReadyToCharging = NO;
                }
            }

            // Cable check (Get)
            GetGfdAdc();

            // 橋接 relay
            SetParalleRelayStatus();

            // 搭上 AC Contactor
            //if (isCharging) {
            //    outputRelay.relay_event.bits.AC_Contactor = YES;
            //} else {
            //    outputRelay.relay_event.bits.AC_Contactor = NO;
            //}

            if (isCharging ||
                    (ShmPsuData->Work_Step >= _TEST_MODE &&
                     ShmPsuData->Work_Step <= _TEST_MODE)) {
                isStopChargingCount = false;
                outputRelay.relay_event.bits.AC_Contactor = YES;
            } else {
                if (!isStopChargingCount) {
                    gettimeofday(&_close_ac_contactor, NULL);
                    isStopChargingCount = true;
                } else {
                    if ((outputRelay.relay_event.bits.AC_Contactor == YES &&
                            GetTimeoutValue(_close_ac_contactor) / 1000 >= (TEN_MINUTES * 1000))) {
                        outputRelay.relay_event.bits.AC_Contactor = NO;
                    }
                }
            }

            if (ShmPrimaryMcuData->InputDet.bits.EmergencyButton == ABNORMAL) {
                outputRelay.relay_event.bits.AC_Contactor = NO;
            }

            if (pAlarmCode->AlarmEvents.bits.PsuFailureAlarm == ABNORMAL) {
                RunForceStopProcess();
                outputRelay.relay_event.bits.AC_Contactor = NO;
            }

            if (ShmPsuData->Work_Step >= _TEST_MODE && ShmPsuData->Work_Step <= _TEST_MODE) {
                outputRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_P = YES;
            }

            // 搭上/鬆開 Relay
            if (IsNoneMatchRelayStatus()) {
                if (Config_Relay_Output(Uart5Fd, ADDR_RELAY, &outputRelay)) {
                    //regRelay.relay_event.bits.AC_Contactor = pSysInfo->AcContactorStatus;

                    //regRelay.relay_event.bits.CCS_Precharge = outputRelay.relay_event.bits.CCS_Precharge;
                    //regRelay.relay_event.bits.Gun1_P = outputRelay.relay_event.bits.Gun1_P;
                    //regRelay.relay_event.bits.Gun1_N = outputRelay.relay_event.bits.Gun1_N;
                    //regRelay.relay_event.bits.Gun2_P = outputRelay.relay_event.bits.Gun2_P;
                    //regRelay.relay_event.bits.Gun2_N = outputRelay.relay_event.bits.Gun2_N;
                    //regRelay.relay_event.bits.Gun1_Parallel_P = outputRelay.relay_event.bits.Gun1_Parallel_P;
                    //regRelay.relay_event.bits.Gun1_Parallel_N = outputRelay.relay_event.bits.Gun1_Parallel_N;

                    //MatchRelayStatus();

                    //log_info("Match Relay, AC = %x, g1_p = %x, g1_n = %x, g2_p = %x, g2_n = %x, pre = %x, bri_p = %x, bri_n = %x \n",
                    //         regRelay.relay_event.bits.AC_Contactor,
                    //         regRelay.relay_event.bits.Gun1_P,
                    //         regRelay.relay_event.bits.Gun1_N,
                    //         regRelay.relay_event.bits.Gun2_P,
                    //         regRelay.relay_event.bits.Gun2_N,
                    //         regRelay.relay_event.bits.CCS_Precharge,
                    //         regRelay.relay_event.bits.Gun1_Parallel_P,
                    //         regRelay.relay_event.bits.Gun1_Parallel_N);

                }
            } /*else {
                    log_info("======== Relay Status Start========\n");
                    if (regRelay.relay_event.bits.AC_Contactor == YES) {
                        log_info("AC Power : ON \n");
                    } else {
                        log_info("AC Power : OFF \n");
                    }

                    if (regRelay.relay_event.bits.Gun1_P == YES) {
                        log_info("Conn1(+) : ON \n");
                    } else {
                        log_info("Conn1(+) : OFF \n");
                    }

                    if (regRelay.relay_event.bits.Gun1_N == YES) {
                        log_info("Conn1(-) : ON \n");
                    } else {
                        log_info("Conn1(-) : OFF \n");
                    }

                    if (regRelay.relay_event.bits.Gun2_P == YES) {
                        log_info("Conn2(+) : ON \n");
                    } else {
                        log_info("Conn2(+) : OFF \n");
                    }

                    if (regRelay.relay_event.bits.Gun2_N == YES) {
                        log_info("Conn2(-) : ON \n");
                    } else {
                        log_info("Conn2(-) : OFF \n");
                    }

                    if (regRelay.relay_event.bits.CCS_Precharge == YES) {
                        log_info("Precharge : ON \n");
                    } else {
                        log_info("Precharge : OFF \n");
                    }

                    if (regRelay.relay_event.bits.Gun1_Parallel_P == YES) {
                        log_info("Parallel(+) : ON \n");
                    } else {
                        log_info("Parallel(+) : OFF \n");
                    }

                    if (regRelay.relay_event.bits.Gun1_Parallel_N == YES) {
                        log_info("Parallel(-) : ON \n");
                    } else {
                        log_info("Parallel(-) : OFF \n");
                    }
                    log_info("======== Relay Status End========\n");
                }*/
        }
        usleep(100000);
    }
}