Selaa lähdekoodia

2021-08-23 / Wendell

Actions
1. use clock time to calculate timeout function
2. fix StartWaitPlug logic
3. add power cabinet gfd function when dispenser pantograph enable
4. allow idtag = AutoStartCharging when dispenser is dk model and OFFLINE_POLICY is local list
5. send power cabinet voltage and current to dispenset when pantograph enable

Files
1. As follow commit history

Image version : V1.02.XX.XXXX.XX
Wendell 3 vuotta sitten
vanhempi
commit
46cfb4015b

+ 34 - 0
EVSE/Projects/DO360/Apps/Common.c

@@ -64,3 +64,37 @@ int StorePsuLogMsg(const char *fmt, ...)
     return rc;
 }
 
+void GetClockTime(struct timespec *_now_time)
+{
+    clock_gettime(CLOCK_MONOTONIC, _now_time);
+}
+
+// return value unit: 1us
+long GetTimeoutValue(struct timespec _start_time)
+{
+    struct timespec ts_end;
+    long ret = 0;
+
+    clock_gettime(CLOCK_MONOTONIC, &ts_end);
+
+    ret = ((ts_end.tv_sec - _start_time.tv_sec) * 1000000) + ((ts_end.tv_nsec - _start_time.tv_nsec) / 1000);
+    /*
+    printf("\r\n TimeInterval: %ld.%09ld - %ld.%09ld = %ld.%06ld ns",
+        ts_end.tv_sec, ts_end.tv_nsec,  _start_time.tv_sec, _start_time.tv_nsec,
+        (ret / 1000000), (ret % 1000000));
+    */
+#if 0
+    struct timespec ts_interval;
+    ts_interval.tv_sec = ts_end.tv_sec - _start_time.tv_sec;
+    ts_interval.tv_nsec = ts_end.tv_nsec - _start_time.tv_nsec;
+
+    if(ts_interval.tv_nsec < 0)
+    {
+        ts_interval.tv_nsec += 1000000000;
+        ts_interval.tv_sec--;
+    }
+#endif
+
+    return ret;
+}
+

+ 4 - 0
EVSE/Projects/DO360/Apps/Common.h

@@ -8,6 +8,8 @@
 #ifndef COMMON_H_
 #define COMMON_H_
 
+#include <time.h>
+
 #define LOG_INFO(format, args...) StoreSysLogMsg("[%s:%4d][%s][Info] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__), __LINE__, __FUNCTION__, ##args)
 #define LOG_WARN(format, args...) StoreSysLogMsg("[%s:%4d][%s][Warn] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__), __LINE__, __FUNCTION__, ##args)
 #define LOG_ERROR(format, args...) StoreSysLogMsg("[%s:%4d][%s][Erro] "format, (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__), __LINE__, __FUNCTION__, ##args)
@@ -16,5 +18,7 @@
 
 int StoreSysLogMsg(const char *fmt, ...);
 int StorePsuLogMsg(const char *fmt, ...);
+void GetClockTime(struct timespec *_now_time);
+long GetTimeoutValue(struct timespec _start_time);
 
 #endif /* COMMON_H_ */

+ 61 - 59
EVSE/Projects/DO360/Apps/Config.h

@@ -9,42 +9,42 @@
 
 #include <stdbool.h>
 
-typedef unsigned char			    byte;
-
-
-#define MODE_BOOT					0
-#define MODE_IDLE					1
-#define MODE_AUTHORIZING			2
-#define MODE_REASSIGN_CHECK			3
-#define MODE_REASSIGN				4
-#define MODE_PRECHARGE				5
-#define MODE_PREPARE_FOR_EV			6
-#define MODE_PREPARE_FOR_EVSE		7
-#define MODE_CHARGING				8
-#define MODE_TERMINATING			9
-#define MODE_COMPLETE				10
-#define MODE_ALARM					11
-#define MODE_FAULT					12
-#define MODE_RESERVATION			13
-#define MODE_BOOKING				14
-#define MODE_MAINTAIN				15
-#define MODE_DEBUG					16
-#define MODE_CCS_PRECHARGE_STEP0	17 	// ready for ccs precharge processing, For D+ relay to precharge relay
-#define MODE_CCS_PRECHARGE_STEP1	18	// waitting for ev board inform to enter to charging, For precharge relay to D+ relay
-#define MODE_UPDATE					19
-
-#define GFD_WAIT			0
-#define GFD_PASS			1
-#define GFD_FAIL			2
-#define GFD_WARNING			3
-
-#define PRECHARGE_WAIT				0
-#define PRECHARGE_READY				1
-#define PRECHARGE_PRERELAY_PASS		2
-#define PRECHARGE_CHARELAY_PASS		3
-
-#define BOOTTING			0
-#define BOOT_COMPLETE		1
+typedef unsigned char               byte;
+
+
+#define MODE_BOOT                   0
+#define MODE_IDLE                   1
+#define MODE_AUTHORIZING            2
+#define MODE_REASSIGN_CHECK         3
+#define MODE_REASSIGN               4
+#define MODE_PRECHARGE              5
+#define MODE_PREPARE_FOR_EV         6
+#define MODE_PREPARE_FOR_EVSE       7
+#define MODE_CHARGING               8
+#define MODE_TERMINATING            9
+#define MODE_COMPLETE               10
+#define MODE_ALARM                  11
+#define MODE_FAULT                  12
+#define MODE_RESERVATION            13
+#define MODE_BOOKING                14
+#define MODE_MAINTAIN               15
+#define MODE_DEBUG                  16
+#define MODE_CCS_PRECHARGE_STEP0    17 	// ready for ccs precharge processing, For D+ relay to precharge relay
+#define MODE_CCS_PRECHARGE_STEP1    18	// waitting for ev board inform to enter to charging, For precharge relay to D+ relay
+#define MODE_UPDATE                 19
+
+#define GFD_WAIT                    0
+#define GFD_PASS                    1
+#define GFD_FAIL                    2
+#define GFD_WARNING                 3
+
+#define PRECHARGE_WAIT              0
+#define PRECHARGE_READY             1
+#define PRECHARGE_PRERELAY_PASS     2
+#define PRECHARGE_CHARELAY_PASS     3
+
+#define BOOTTING                    0
+#define BOOT_COMPLETE               1
 
 #define uSEC_VAL                    1000000
 #define mSEC_VAL                    1000
@@ -71,7 +71,7 @@ typedef unsigned char			    byte;
 
 enum _SYSTEM_STATUS
 {
-	S_BOOTING = 						0,
+	S_BOOTING =                         0,
     S_IDLE,
 	S_AUTHORIZING,
 	S_REASSIGN_CHECK,
@@ -121,17 +121,17 @@ enum _GUN_TYPE
 
 enum _LCM_INDEX
 {
-	_LCM_INIT = 			0x00,
-	_LCM_IDLE = 			0x01,
-	_LCM_AUTHORIZING = 		0x02,
-	_LCM_AUTHORIZ_COMP = 	0x03,
-	_LCM_AUTHORIZ_FAIL = 	0x04,
-	_LCM_WAIT_FOR_PLUG = 	0x05,
-	_LCM_PRE_CHARGE = 		0x06,
-	_LCM_CHARGING = 		0x07,
-	_LCM_COMPLETE = 		0x08,
-	_LCM_FIX = 				0x09,
-	_LCM_NONE = 			0xFF,
+	_LCM_INIT               = 0x00,
+	_LCM_IDLE               = 0x01,
+	_LCM_AUTHORIZING        = 0x02,
+	_LCM_AUTHORIZ_COMP      = 0x03,
+	_LCM_AUTHORIZ_FAIL      = 0x04,
+	_LCM_WAIT_FOR_PLUG      = 0x05,
+	_LCM_PRE_CHARGE         = 0x06,
+	_LCM_CHARGING           = 0x07,
+	_LCM_COMPLETE           = 0x08,
+	_LCM_FIX                = 0x09,
+	_LCM_NONE               = 0xFF,
 };
 
 enum _DispenserAuthorizeStatus
@@ -159,12 +159,12 @@ enum _AuthorizedType
 
 enum _SELF_TEST_SEQ
 {
-	_STEST_VERSION = 0x00,
-	_STEST_AC_CONTACTOR = 0x01,
-	_STEST_PSU_DETECT = 0x02,
-	_STEST_PSU_CAP = 0x03,
-	_STEST_FAIL = 0x04,
-	_STEST_COMPLETE = 0xEE,
+	_STEST_VERSION          = 0x00,
+	_STEST_AC_CONTACTOR     = 0x01,
+	_STEST_PSU_DETECT       = 0x02,
+	_STEST_PSU_CAP          = 0x03,
+	_STEST_FAIL             = 0x04,
+	_STEST_COMPLETE         = 0xEE,
 };
 
 enum _MODULE_PSU_WORK_STEP
@@ -187,10 +187,10 @@ enum _MODULE_PSU_WORK_STEP
 
 enum _OFFLINE_POLICY
 {
-	_OFFLINE_POLICY_LOCAL_LIST = 0x00,
-	_OFFLINE_POLICY_PHIHONG_RFID_TAG = 0x01,
-	_OFFLINE_POLICY_FREE_CHARGING = 0x02,
-	_OFFLINE_POLICY_NO_CHARGING = 0x03,
+	_OFFLINE_POLICY_LOCAL_LIST          = 0x00,
+	_OFFLINE_POLICY_PHIHONG_RFID_TAG    = 0x01,
+	_OFFLINE_POLICY_FREE_CHARGING       = 0x02,
+	_OFFLINE_POLICY_NO_CHARGING         = 0x03,
 };
 
 enum _REASSIGNED_RESOURCE_STEP
@@ -407,7 +407,9 @@ typedef union
         unsigned int AcContactorOffByPsu:1;         // 0: no effect,                1: ac contactor off
         unsigned int AcContactorOffByEmergency:1;   // 0: no effect,                1: ac contactor off
         unsigned int StandbyCountdown:1;            // 0: charger is using,         1: start countdown
-        unsigned int res:27;
+        unsigned int AcInputDisable:1;              // 0: ac input enable,          1: ac input disable
+        unsigned int DcInputEnable:1;               // 0: dc input disable,         1: dc input enable
+        unsigned int res:25;
     }bits;
 }RelayControl;
 

+ 8 - 8
EVSE/Projects/DO360/Apps/Makefile

@@ -23,40 +23,40 @@ MainTask:
 	rm -f main;
 	$(CC) -D $(Project) -include../../../Modularization/ocppfiles/sqlite3.h -include../../../Modularization/Module_Upgrade.h -include../../../Modularization/Module_RFID.h -O0 -g3 -Wall -c -fmessage-length=0 -o main.o main.c
 	$(CC) -D $(Project) -include../../../Modularization/ocppfiles/sqlite3.h -include../../../Modularization/Module_Upgrade.h -include../../../Modularization/Module_RFID.h -O0 -g3 -Wall -c -fmessage-length=0 -o timeout.o timeout.c
-	$(CC) -o main main.o timeout.o Common.o ${Lib_Module_RFID} ${Lib_Module_Upgrade} ${Lib_SQLite3}	
+	$(CC) -o main main.o timeout.o Common.o ${Lib_Module_RFID} ${Lib_Module_Upgrade} ${Lib_SQLite3}	-lrt
 	cp -f main ../Images/root
 
 EvCommTask:
 	rm -f Module_EvComm;
 	$(CC) -D $(Project) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Ev_Comm.o Ev_Comm.c
 	$(CC) -D $(Project) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_EvComm.o Module_EvComm.c
-	$(CC) -o Module_EvComm Ev_Comm.o Module_EvComm.o Common.o
+	$(CC) -o Module_EvComm Ev_Comm.o Module_EvComm.o Common.o -lrt
 	cp -f Module_EvComm ../Images/root	
 	
 EventLoggingTask:
 	rm -f Module_EventLogging;
 	$(CC) -D $(Project) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_EventLogging.o Module_EventLogging.c
-	$(CC) -o Module_EventLogging Module_EventLogging.o Common.o
+	$(CC) -o Module_EventLogging Module_EventLogging.o Common.o -lrt
 	cp -f Module_EventLogging ../Images/root	
 	
 InternalCommTask:
 	rm -f Module_InternalComm; 
 	$(CC) -D $(Project) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o internalComm.o internalComm.c
 	$(CC) -D $(Project) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_InternalComm.o Module_InternalComm.c
-	$(CC) -o Module_InternalComm Module_InternalComm.o internalComm.o Common.o
+	$(CC) -o Module_InternalComm Module_InternalComm.o internalComm.o Common.o -lrt
 	cp -f Module_InternalComm ../Images/root
 	
 LcmControlTask:
 	rm -f Module_LcmControl; 
 	$(CC) -D $(Project) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_LcmControl.o Module_LcmControl.c
-	$(CC) -o Module_LcmControl Module_LcmControl.o
+	$(CC) -o Module_LcmControl Module_LcmControl.o -lrt
 	cp -f Module_LcmControl ../Images/root			
 
 PrimaryCommTask:
 	rm -f Module_PrimaryComm; 
 	$(CC) -D $(Project) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_PrimaryComm.o Module_PrimaryComm.c
 	$(CC) -D $(Project) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o PrimaryComm.o PrimaryComm.c
-	$(CC) -o Module_PrimaryComm Module_PrimaryComm.o PrimaryComm.o Common.o
+	$(CC) -o Module_PrimaryComm Module_PrimaryComm.o PrimaryComm.o Common.o -lrt
 	cp -f Module_PrimaryComm ../Images/root	
 
 InfyGroup_PsuCommObj:
@@ -68,13 +68,13 @@ InfyGroup_PsuCommObj:
 PsuCommTask:
 	rm -f Module_PsuComm; 
 	$(CC) -D $(Project) -includeInfyGroup_PsuCommObj.h -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o Module_PsuComm.o Module_PsuComm.c
-	$(CC) -o Module_PsuComm Module_PsuComm.o libInfyGroup_PsuCommObj.a Common.o
+	$(CC) -o Module_PsuComm Module_PsuComm.o libInfyGroup_PsuCommObj.a Common.o -lrt
 	cp -f Module_PsuComm ../Images/root	
 	
 ReadCmdlineTask:
 	rm -f ReadCmdline; 
 	$(CC) -D $(Project) -includeConfig.h -O0 -g3 -Wall -c -fmessage-length=0 -o ReadCmdline.o ReadCmdline.c
-	$(CC) -o ReadCmdline ReadCmdline.o
+	$(CC) -o ReadCmdline ReadCmdline.o Common.o -lrt
 	cp -f ReadCmdline ../Images/root
 
 UnsafetyOutputTool:

+ 116 - 29
EVSE/Projects/DO360/Apps/Module_EvComm.c

@@ -777,8 +777,9 @@ void tcpSocketClientStart(void)
 
 BOOL IsAvalibleGunType(char name, unsigned char *type)
 {
-	char         modelList[11] = {'J', 'U', 'V', 'E', 'F', 'G', 'T', 'D', 'K', 'P', 'R'};
-	unsigned char typeList[11] = {  0,   1,   1,   1,   1,   2,   1,   1,   0,   1,   1}; // 0 : Chademo, 1: CCS, 2: GB
+    // 20210817 remove type "R"
+	char         modelList[10] = {'J', 'U', 'V', 'E', 'F', 'G', 'T', 'D', 'K', 'P'};
+	unsigned char typeList[10] = {  0,   1,   1,   1,   1,   2,   1,   1,   0,   1}; // 0 : Chademo, 1: CCS, 2: GB
 
 	for(int i = 0; i < 11; i++)
 	{
@@ -1378,15 +1379,21 @@ void WriteChargingInfoResponse(int socket, struct PACKET_STRUCTURE *packet, unsi
     struct PACKET_STRUCTURE sendBuffer;
 
     unsigned short voltage = 0, current = 0;
+    unsigned char gun = packet->Header.id - 1;
 
 #if 0
     // for safety test
-    unsigned char gun = packet->Header.id - 1;
     voltage = (unsigned short)(chargingInfo[gun]->PresentChargingVoltage * 10);
     current = (unsigned short)(chargingInfo[gun]->PresentChargingCurrent * 10);
     voltage -= ((current * 8 * 10) / 10000);
 #endif
 
+    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.PantographEnable)
+    {
+        voltage = (unsigned short)(chargingInfo[gun]->PresentChargingVoltage * 10);
+        current = (unsigned short)(chargingInfo[gun]->PresentChargingCurrent * 10);
+    }
+
     memset(&sendBuffer, 0x00, sizeof(sendBuffer));
     sendBuffer.Header.se = packet->Header.se;
     sendBuffer.Header.id = packet->Header.id;
@@ -1482,6 +1489,22 @@ void WriteWaitPlugInResponse(int socket, struct PACKET_STRUCTURE *packet, unsign
     SendPacket(socket, &sendBuffer);
 }
 
+void GroundFaultDetectionResponse(int socket, struct PACKET_STRUCTURE *packet, unsigned char result)
+{
+    struct PACKET_STRUCTURE sendBuffer;
+
+    memset(&sendBuffer, 0x00, sizeof(sendBuffer));
+    sendBuffer.Header.se = packet->Header.se;
+    sendBuffer.Header.id = packet->Header.id;
+    sendBuffer.Header.op = _Header_Response;
+    sendBuffer.Header.len = 3;
+    sendBuffer.Payload.reg = _Reg_GroundFaultDetection;
+    sendBuffer.Payload.data[0] = result;
+    sendBuffer.Payload.data[1] = result == _R_OK ? chargingInfo[packet->Header.id - 1]->GroundFaultStatus : GFD_WAIT;
+
+    SendPacket(socket, &sendBuffer);
+}
+
 BOOL FindConnectorID(unsigned char dispenserIndex, unsigned char id)
 {
 	BOOL find = false;
@@ -1500,8 +1523,9 @@ BOOL FindConnectorID(unsigned char dispenserIndex, unsigned char id)
 
 void ConnectorPhysicalLimitBindingHandler(unsigned char connectorIndex, unsigned char physical)
 {
-    //char         modelList[11] = {'J', 'U', 'V', 'E', 'F', 'G', 'T', 'D', 'K', 'P', 'R'};
-    //unsigned char typeList[11] = {  0,   1,   1,   1,   1,   2,   1,   1,   0,   1,   1}; // 0 : Chademo, 1: CCS, 2: GB
+    // 20210817 remove type "R"
+    //char         modelList[11] = {'J', 'U', 'V', 'E', 'F', 'G', 'T', 'D', 'K', 'P'};
+    //unsigned char typeList[11] = {  0,   1,   1,   1,   1,   2,   1,   1,   0,   1}; // 0 : Chademo, 1: CCS, 2: GB
 
     switch(physical)
     {
@@ -1525,7 +1549,7 @@ void ConnectorPhysicalLimitBindingHandler(unsigned char connectorIndex, unsigned
         case 'V':
         case 'F':
         case 'P':
-        case 'R':
+        //case 'R': // 20210817 remove type "R"
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalVoltage = CCS_MAX_PHYSICAL_VOLTAGE;
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].RemoteMaxPhysicalCurrent = CCS_LIQUID_MAX_CURRENT;
             break;
@@ -1543,6 +1567,19 @@ void ConnectorPhysicalLimitBindingHandler(unsigned char connectorIndex, unsigned
     }
 }
 
+void ConnectorPantographBindingHandler(unsigned char connectorIndex, unsigned char physical)
+{
+    switch(physical)
+    {
+        case 'P':
+            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].Parameter.bits.PantographEnable = 1;
+            break;
+        default:
+            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[connectorIndex].Parameter.bits.PantographEnable = 0;
+            break;
+    }
+}
+
 void ConnectorTypeBindingHandler(unsigned char dispenserIndex, unsigned char *type, unsigned char *physicalType)
 {
     char *str_gun_type[] = {STR_GUN_TYPE_CHADEMO, STR_GUN_TYPE_CCS, STR_GUN_TYPE_GBT};
@@ -1554,11 +1591,13 @@ void ConnectorTypeBindingHandler(unsigned char dispenserIndex, unsigned char *ty
 		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].GeneralChargingData.Index = gunIndex;
 		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].GeneralChargingData.Type = type[i];
         ConnectorPhysicalLimitBindingHandler(gunIndex, physicalType[i]);
+        ConnectorPantographBindingHandler(gunIndex, physicalType[i]);
 
-		LOG_INFO("Dispenser %d Connector %d type %s, MaxVol: %4d, MaxCur: %4d",
+		LOG_INFO("Dispenser %d Connector %d type: %s, MaxVol: %4d, MaxCur: %4d, %s",
             dispenserIndex + 1, gunIndex + 1, str_gun_type[type[i]],
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].RemoteMaxPhysicalVoltage,
-            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].RemoteMaxPhysicalCurrent);
+            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].RemoteMaxPhysicalCurrent,
+            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gunIndex].Parameter.bits.PantographEnable ? "Normal" : "Pantograph");
 	}
 }
 
@@ -1645,7 +1684,7 @@ BOOL CheckNewDispenserSequence(unsigned char index, unsigned char quantity)
         ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence = index + 1;
         ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity += quantity;
         ShmSysConfigAndInfo->SysConfig.WiringInfo.WiringSetting[index] = quantity;
-        ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.WiringInfoChanged = true;
+        ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged = true;
 
         ShmSysConfigAndInfo->SysInfo.DispenserInfo.DispenserQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence;
         ShmSysConfigAndInfo->SysInfo.DispenserInfo.TotalConnectorQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity;
@@ -1779,14 +1818,6 @@ BOOL ConnectorChargingCapabilityHandler(struct PACKET_STRUCTURE *packet, unsigne
     return done;
 }
 
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-    struct timeval _end_time;
-    gettimeofday(&_end_time, NULL);
-
-    return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-
 BOOL ConnectorChargingTargetHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
 {
 	BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
@@ -2360,26 +2391,72 @@ unsigned char WriteWaitPlugInHandler(struct PACKET_STRUCTURE *packet, unsigned c
     {
         unsigned char StartWait = packet->Payload.data[0];
 
-        if(StartWait)
+        if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus == S_AUTHORIZING)
         {
-            if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug)
+            if(StartWait)
             {
-                LOG_INFO("Connector %d Start Wait Plug In", packet->Header.id);
-                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.SwipeRfidConfirm = true;
+                if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug)
+                {
+                    LOG_INFO("Connector %d Start Wait Plug In", packet->Header.id);
+                    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.SwipeRfidConfirm = true;
+                }
+                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug = true;
+            }
+            else
+            {
+                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug)
+                {
+                    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus != S_IDLE)
+                    {
+                        LOG_INFO("Connector %d Stop Wait Plug In", packet->Header.id);
+                        ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.NeedCleanAuthorizeInfo = true;
+                    }
+                }
+                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug = false;
             }
-            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug = true;
         }
         else
         {
-            if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug)
+            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug = false;
+        }
+    }
+    else
+    {
+
+    }
+
+    return find;
+}
+
+unsigned char GroundFaultDetectionHandler(struct PACKET_STRUCTURE *packet, unsigned char dispenserIndex)
+{
+    BOOL find = FindConnectorID(dispenserIndex, packet->Header.id);
+    unsigned char gun = 0;
+
+    if(find)
+    {
+        gun = packet->Header.id - 1;
+        unsigned char enable = packet->Payload.data[0];
+
+        if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.PantographEnable)
+        {
+            if(enable == _GFD_Enable &&
+                (chargingInfo[gun]->SystemStatus >= S_PREPARING_FOR_EVSE && chargingInfo[gun]->SystemStatus <= S_CHARGING))
             {
-                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].GeneralChargingData.SystemStatus != S_IDLE)
+                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.GfdDetection != _GFD_Enable)
                 {
-                    LOG_INFO("Connector %d Stop Wait Plug In", packet->Header.id);
-                    ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.NeedCleanAuthorizeInfo = true;
+                    LOG_INFO("Connector %d Gfd Detection Start", gun + 1);
                 }
+                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.GfdDetection = _GFD_Enable;
+            }
+            else
+            {
+                if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.GfdDetection != _GFD_Disable)
+                {
+                    LOG_INFO("Connector %d Gfd Detection Stop", gun + 1);
+                }
+                ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun].Parameter.bits.GfdDetection = _GFD_Disable;
             }
-            ShmSysConfigAndInfo->SysInfo.ConnectorInfo[packet->Header.id - 1].Parameter.bits.StartWaitPlug = false;
         }
     }
     else
@@ -2651,6 +2728,16 @@ void DispenserSocketProcess(int socketFd, struct sockaddr_in clientInfo, unsigne
                         }
                         WriteWaitPlugInResponse(socketFd, &receiveBuffer, ackResult);
                     }
+
+                    // Reg: 0x12, Ground Fault Detection
+                    if(receiveBuffer.Header.op == _Header_Write && receiveBuffer.Payload.reg == _Reg_GroundFaultDetection)
+                    {
+                        if(GroundFaultDetectionHandler(&receiveBuffer, dispenserIndex))
+                        {
+                            ackResult = _R_OK;
+                        }
+                        GroundFaultDetectionResponse(socketFd, &receiveBuffer, ackResult);
+                    }
 				}
 
 				// clean timeout
@@ -2804,7 +2891,7 @@ void InitDispenserInfo(void)
 	ShmSysConfigAndInfo->SysInfo.DispenserInfo.Currency = ShmSysConfigAndInfo->SysConfig.BillingData.Currency;
 }
 
-struct timeval _IpConflicted_time[CONNECTOR_QUANTITY];
+struct timespec _IpConflicted_time[CONNECTOR_QUANTITY];
 
 void DispenserIpConflictedCheck(void)
 {
@@ -2816,7 +2903,7 @@ void DispenserIpConflictedCheck(void)
             {
                 if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DuplicateIpConfirm == NO)
                 {
-                    gettimeofday(&_IpConflicted_time[i], NULL);
+                    GetClockTime(&_IpConflicted_time[i]);
                     ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Setting.bits.DuplicateIpConfirm = true;
                     LOG_INFO("Dispenser %d IP Conflicted Confirm", i + 1);
                 }

+ 13 - 0
EVSE/Projects/DO360/Apps/Module_EvComm.h

@@ -72,6 +72,7 @@ enum PAYLOAD_REGISTER
 	_Reg_Charging_Info              = 0x0F,
 	_Reg_Charger_System_Id          = 0x10,
 	_Reg_WaitPlugIn                 = 0x11,
+	_Reg_GroundFaultDetection       = 0x12,
 };
 
 enum Response_Result
@@ -196,4 +197,16 @@ struct ChargingCapabilityResponse
     int            AccountBalance;          // unit = 0.01 dollar
 };
 
+enum WaitPlug
+{
+    _WaitPlug_None  = 0x0,
+    _WaitPlug_Start = 0x1,
+};
+
+enum GroundFaultDetection
+{
+    _GFD_Disable    = 0x0,
+    _GFD_Enable     = 0x1,
+};
+
 #endif /* MODULE_EVCOMM_H_ */

+ 135 - 121
EVSE/Projects/DO360/Apps/Module_InternalComm.c

@@ -68,6 +68,7 @@ PsuGroupParallelRelay           *ShmParallelRelayConfig;
 PsuGroupParallelRelay           *ShmParallelRelayConfirmed;
 RBRelayControl                  *LocationRelayCtrl[MAX_GROUP_QUANTITY];
 RBRelayControl                  *LocationRelayResponse[MAX_GROUP_QUANTITY];
+Connector_GFD                   *LocaltionGfd[MAX_GROUP_QUANTITY];
 
 #define VIN_MAX_VOLTAGE_IEC         285	// 大於該值 : OVP
 #define VIN_MAX_REV_VOLTAGE_IEC     275 // 小於賦歸 OVP
@@ -122,10 +123,10 @@ struct ChargingInfoData *_chargingData[CONNECTOR_QUANTITY];
 struct ChargingInfoData *ac_chargingInfo[AC_QUANTITY];
 
 bool _isOutputNoneMatch[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-struct timeval _checkOutputNoneMatchTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timespec _checkOutputNoneMatchTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 
 bool _isRelayWelding[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
-struct timeval _checkRelayWeldingTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
+struct timespec _checkRelayWeldingTimer[CHAdeMO_QUANTITY + CCS_QUANTITY + GB_QUANTITY];
 
 byte _threePhaseOvp[3] = {0, 0, 0};
 byte _threePhaseUvp[3] = {0, 0, 0};
@@ -136,20 +137,21 @@ int Uart5Fd;
 char *relayRs485PortName = "/dev/ttyS5";
 unsigned short fanSpeedSmoothValue = 500;
 
-struct timeval _close_ac_contactor;
+//struct timeval _close_ac_contactor;
 
-struct timeval _priority_time;
-struct timeval _led_priority_time;
+struct timespec _priority_time;
+struct timespec _led_priority_time;
 
-struct timeval	_ac_charging_comp;
-struct timeval	_ac_preparing;
-struct timeb 	_ac_startChargingTime;
-struct timeb 	_ac_endChargingTime;
+//struct timeval	_ac_charging_comp;
+//struct timeval	_ac_preparing;
+//struct timeb 	_ac_startChargingTime;
+//struct timeb 	_ac_endChargingTime;
 
 unsigned short _setFanSpeed = 0;
 float _beforeChargingTotalEnergy = 0.0;
 byte _checkLedChanged = 3;
 byte _RelaySelfTestOK;
+bool _isGfdEnable = false;
 
 Ver ver;
 PresentInputVoltage inputVoltage;
@@ -157,7 +159,7 @@ PresentOutputVoltage outputVoltage;
 FanSpeed fanSpeed;
 Temperature temperature;
 AuxPower auxPower;
-Gfd gfd_adc;
+Gfd gfd_adc[2];
 Gfd_config gfd_config;
 Gpio_in gpio_in;
 Gpio_out gpio_out;
@@ -199,16 +201,6 @@ int _alarm_code[] = {AC_OVP, AC_UVP, AC_OCP, AC_OTP, AC_GMI_FAULT, AC_CP_ERROR,
 		, AC_GF_MODULE_FAULT, AC_SHUTTER_FAULT, AC_LOCKER_FAULT, AC_POWER_DROP, AC_CIRCUIT_SHORT
 		, AC_ROTARY_SWITCH_FAULT, AC_RELAY_DRIVE_FAULT};
 
-unsigned long GetTimeoutValue(struct timeval _sour_time);
-
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-	struct timeval _end_time;
-	gettimeofday(&_end_time, NULL);
-
-	return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-
 int DiffTimeb(struct timeb ST, struct timeb ET)
 {
 	//return milli-second
@@ -899,62 +891,65 @@ void CheckK1K2RelayOutput(byte index)
 #endif
 }
 
-void GetGfdAdc()
+void GetGfdAdc(void)
 {
-	// 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 (int i = 0; i < gunCount; i++)
-//		{
-//			if (_chargingData[i]->Type == 0x09 && !ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag)
-//			{
-//				if ((_chargingData[i]->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE)
-//					_chargingData[i]->GroundFaultStatus = GFD_PASS;
-//				continue;
-//			}
-
-//			if (i == 0)
-//			{
-//				_chargingData[i]->GroundFaultStatus = gfd_adc.result_conn1;
-//				LOG_INFO("GFD ******** Result = %d, Step = %d, R = %d, Vol = %d",
-//						_chargingData[i]->GroundFaultStatus, gfd_adc.rb_step_1, gfd_adc.Resister_conn1, gfd_adc.voltage_conn1);
-//				if (_chargingData[i]->GroundFaultStatus == GFD_FAIL)
-//				{
-//					LOG_INFO("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d",
-//							i, gfd_adc.rb_step_1, gfd_adc.Resister_conn1, gfd_adc.voltage_conn1);
-//				}
-//				else if (_chargingData[i]->GroundFaultStatus == GFD_PASS ||
-//						_chargingData[i]->GroundFaultStatus == GFD_WARNING)
-//				{
-//					if (_chargingData[i]->GroundFaultStatus == GFD_WARNING)
-//					{
-//						LOG_INFO("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d",
-//								i, _chargingData[i]->GroundFaultStatus, gfd_adc.Resister_conn1, gfd_adc.voltage_conn1);
-//					}
-//				}
-//			}
-//			else if (i == 1)
-//			{
-//				_chargingData[i]->GroundFaultStatus = gfd_adc.result_conn2;
-//				if (_chargingData[i]->GroundFaultStatus == GFD_FAIL)
-//				{
-//					LOG_INFO("GFD Fail. index = %d, Step = %d, R = %d, Vol = %d",
-//							i, gfd_adc.rb_step_2, gfd_adc.Resister_conn2, gfd_adc.voltage_conn2);
-//				}
-//				else if (_chargingData[i]->GroundFaultStatus == GFD_PASS ||
-//						_chargingData[i]->GroundFaultStatus == GFD_WARNING)
-//				{
-//					if (_chargingData[i]->GroundFaultStatus == GFD_WARNING)
-//					{
-//						LOG_INFO("GFD Warning. index = %d, Result = %d, R = %d, Vol = %d",
-//							i, _chargingData[i]->GroundFaultStatus, gfd_adc.Resister_conn1, gfd_adc.voltage_conn1);
-//					}
-//				}
-//			}
-//		}
-//	}
+    unsigned char location = 0, result = 0;
+    char *str_gfd[] = {"Idle", "Pass", "Fail", "Warning"};
+
+    if(!_isGfdEnable)
+    {
+        for(int i = 0; i < ShmChargerInfo->Control.MaxConnector; i++)
+        {
+            if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].Parameter.bits.PantographEnable)
+            {
+                _isGfdEnable = true;
+                LOG_INFO("Enable Power Cabinet GFD Function");
+            }
+        }
+    }
+
+    if(_isGfdEnable)
+    {
+        // define : 每 0.2 ~ 1 秒一次
+        // occur : <= 75k 歐姆 @ 150 - 750 Vdc
+        // warning : >= 100 歐姆 && <= 500 歐姆 @ 150-750 Vdc
+        if(Query_Gfd_Adc(Uart5Fd, Addr.DO360_RC1, &gfd_adc[0]) == PASS)
+        {
+
+        }
+        if(ShmChargerInfo->Control.SysCtrl.bits.SecondRelayBoardEnable)
+        {
+            if(Query_Gfd_Adc(Uart5Fd, Addr.DO360_RC2, &gfd_adc[1]) == PASS)
+            {
+
+            }
+        }
+
+        // update output relay feedback status
+        for(int i = 0; i < ShmChargerInfo->Control.MaxConnector; i++)
+        {
+            location = ShmPsuGrouping->GroupCollection[i].Location;
+
+            result = LocaltionGfd[location]->bits.GFD_Result;
+            if(_chargingData[i]->GroundFaultStatus != result)
+            {
+                if(result <= GFD_WARNING)
+                {
+                    LOG_INFO("Gun %d GFD Result %s at Location %d", i + 1, str_gfd[result], location + 1);
+                    if(result == GFD_FAIL || result == GFD_WARNING)
+                    {
+                        LOG_INFO("Gun %d GFD Step = %d, R = %d, Vol = %d", i + 1, LocaltionGfd[location]->bits.rb_step,
+                            LocaltionGfd[location]->bits.Resister, LocaltionGfd[location]->bits.Voltage);
+                    }
+                }
+                else
+                {
+                    LOG_INFO("Gun %d Unknown GFD Result %d at Location %d", i + 1, result, location + 1);
+                }
+            }
+            _chargingData[i]->GroundFaultStatus = result;
+        }
+    }
 }
 
 void GetGpioInput()
@@ -1092,18 +1087,31 @@ void SetK1K2RelayStatus(byte index)
         if ((_chargingData[index]->SystemStatus >= S_PREPARING_FOR_EVSE &&
                 _chargingData[index]->SystemStatus <= S_CHARGING))
         {
-            if(!ShmOutputRelayConfig[index]->bits.Output_N || !ShmOutputRelayConfig[index]->bits.Output_P)
+            if(_chargingData[index]->GroundFaultStatus == GFD_FAIL)
+            {
+                if(ShmOutputRelayConfig[index]->bits.Output_N || ShmOutputRelayConfig[index]->bits.Output_P)
+                {
+                    LOG_INFO("Gun %d Set K1K2 Open By GFD Fail", index + 1);
+                }
+                ShmOutputRelayConfig[index]->bits.Output_N = false;
+                ShmOutputRelayConfig[index]->bits.Output_P = false;
+            }
+            else
             {
-                LOG_INFO("Gun %d Set K1K2 Close And Prepare To Charging", index + 1);
+                if(!ShmOutputRelayConfig[index]->bits.Output_N || !ShmOutputRelayConfig[index]->bits.Output_P)
+                {
+                    LOG_INFO("Gun %d Set K1K2 Close And Prepare To Charging", index + 1);
+                }
+                ShmOutputRelayConfig[index]->bits.Output_N = true;
+                ShmOutputRelayConfig[index]->bits.Output_P = true;
             }
-            ShmOutputRelayConfig[index]->bits.Output_N = true;
-            ShmOutputRelayConfig[index]->bits.Output_P = true;
         }
         else if ((_chargingData[index]->SystemStatus >= S_TERMINATING &&
                 _chargingData[index]->SystemStatus <= S_COMPLETE) ||
                 _chargingData[index]->SystemStatus == S_ALARM)
         {
-            if ((_chargingData[index]->PresentChargingCurrent * 10) <= SEFETY_SWITCH_RELAY_CUR)
+            if ((_chargingData[index]->PresentChargingCurrent * 10) <= SEFETY_SWITCH_RELAY_CUR ||
+                _chargingData[index]->GroundFaultStatus == GFD_FAIL)
             {
                 if(ShmOutputRelayConfig[index]->bits.Output_N || ShmOutputRelayConfig[index]->bits.Output_P)
                 {
@@ -1536,6 +1544,8 @@ int InitShareMemory()
             LocationRelayCtrl[1] = (RBRelayControl *)&outputRelay[0].relay_event.relay_status[2];
             LocationRelayResponse[0] = (RBRelayControl *)&regRelay[0].relay_event.relay_status[1];
             LocationRelayResponse[1] = (RBRelayControl *)&regRelay[0].relay_event.relay_status[2];
+            LocaltionGfd[0] = (Connector_GFD *)&gfd_adc[0].Resister_conn1;
+            LocaltionGfd[1] = (Connector_GFD *)&gfd_adc[0].Resister_conn2;
 
             if(ShmChargerInfo->Control.SysCtrl.bits.SecondRelayBoardEnable)
             {
@@ -1543,6 +1553,8 @@ int InitShareMemory()
                 LocationRelayCtrl[3] = (RBRelayControl *)&outputRelay[1].relay_event.relay_status[2];
                 LocationRelayResponse[2] = (RBRelayControl *)&regRelay[1].relay_event.relay_status[1];
                 LocationRelayResponse[3] = (RBRelayControl *)&regRelay[1].relay_event.relay_status[2];
+                LocaltionGfd[2] = (Connector_GFD *)&gfd_adc[1].Resister_conn1;
+                LocaltionGfd[3] = (Connector_GFD *)&gfd_adc[1].Resister_conn2;
             }
         }
     }
@@ -1617,7 +1629,7 @@ bool FindChargingInfoData(byte target, struct ChargingInfoData **chargingData)
 	//DO360
 	if(GENERAL_GUN_QUANTITY > 0 && target < GENERAL_GUN_QUANTITY)
 	{
-		ShmSysConfigAndInfo->SysInfo.ConnectorInfo[target].GeneralChargingData.Index = target;
+		//ShmSysConfigAndInfo->SysInfo.ConnectorInfo[target].GeneralChargingData.Index = target;
 		chargingData[target] = &ShmSysConfigAndInfo->SysInfo.ConnectorInfo[target].GeneralChargingData;
 		return true;
 	}
@@ -1794,20 +1806,25 @@ void CheckRelayStatusByADC()
 
 void SetGfdConfig(byte index, byte resister)
 {
-	gfd_config.index = index;
+    unsigned char add = 0;
+
+	gfd_config.index = (index % 2);
 	gfd_config.state = resister;
+	add = index < 2 ? Addr.DO360_RC1 : Addr.DO360_RC2;
 
 	//LOG_INFO("************************GFD Vol = %d, GFD Res = %d", gfd_config.reqVol, gfd_config.resister);
-	if (Config_Gfd_Value(Uart5Fd, Addr.Relay, &gfd_config) == PASS)
+	if (Config_Gfd_Value(Uart5Fd, add, &gfd_config) == PASS)
 	{
 //		LOG_INFO("Set reqVol = %f, resister = %d",
 //				gfd_config.reqVol,
 //				gfd_config.resister);
 	}
 }
-/*
+
 void CableCheckDetected(byte index)
 {
+    unsigned char location = 0;
+
 	// Cable Check
 	// 當火線上的電壓 = 車端要求的電壓電流
 	// _chargingData[targetGun]->EvBatterytargetVoltage
@@ -1815,39 +1832,30 @@ void CableCheckDetected(byte index)
 	// 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 ((_chargingData[index]->Type >= _Type_Chademo && _chargingData[index]->Type <= _Type_GB) ||
-			(_chargingData[index]->Type == 0x09 && ShmSysConfigAndInfo->SysConfig.AlwaysGfdFlag))
-	{
-		if ((_chargingData[index]->SystemStatus >= S_PREPARING_FOR_EVSE && _chargingData[index]->SystemStatus <= S_TERMINATING) ||
-			(_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 && _chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1))
-		{
-			if (_chargingData[index]->SystemStatus == S_PREPARING_FOR_EVSE &&
-					_chargingData[index]->RelayWeldingCheck == YES)
-			{
-				SetGfdConfig(index, GFD_CABLECHK);
-			}
-			else if (_chargingData[index]->SystemStatus >= S_CCS_PRECHARGE_ST0 &&
-					_chargingData[index]->SystemStatus <= S_CCS_PRECHARGE_ST1)
-			{
-				SetGfdConfig(index, GFD_PRECHARGE);
-			}
-			else if (_chargingData[index]->SystemStatus >= S_CHARGING &&
-					_chargingData[index]->SystemStatus <= S_TERMINATING)
-			{
-				if (_chargingData[index]->Type == _Type_GB || _chargingData[index]->Type == _Type_Chademo)
-					SetGfdConfig(index, GFD_IDLE);
-				else
-					SetGfdConfig(index, GFD_CHARGING);
-			}
-		}
-		else if(_chargingData[index]->SystemStatus == S_COMPLETE || _chargingData[index]->SystemStatus == S_PREPARNING
-				|| _chargingData[index]->SystemStatus == S_IDLE)
-		{
-			SetGfdConfig(index, GFD_IDLE);
-		}
-	}
+
+    if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.PantographEnable)
+    {
+        location = ShmPsuGrouping->GroupCollection[index].Location;
+
+        if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[index].Parameter.bits.GfdDetection &&
+            _chargingData[index]->SystemStatus >= S_PREPARING_FOR_EVSE && _chargingData[index]->SystemStatus < S_TERMINATING)
+        {
+            if(_chargingData[index]->SystemStatus == S_PREPARING_FOR_EVSE && _chargingData[index]->RelayWeldingCheck == YES)
+            {
+                SetGfdConfig(location, GFD_CABLECHK);
+            }
+            else
+            {
+                SetGfdConfig(location, GFD_CHARGING);
+            }
+        }
+        else
+        {
+            SetGfdConfig(location, GFD_IDLE);
+        }
+    }
 }
-*/
+
 void CheckOutputPowerOverCarReq(byte index)
 {
 	float fireV = _chargingData[index]->FireChargingVoltage;
@@ -1882,7 +1890,7 @@ void CheckOutputVolNoneMatchFire(byte index)
 			if (!_isOutputNoneMatch[index])
 			{
 				_isOutputNoneMatch[index] = YES;
-				gettimeofday(&_checkOutputNoneMatchTimer[index], NULL);
+				GetClockTime(&_checkOutputNoneMatchTimer[index]);
 			}
 			else
 			{
@@ -1907,7 +1915,7 @@ void CheckRelayWeldingStatus(byte index)
 	{
 		if ((_chargingData[index]->PresentChargingVoltage * 10) >= VOUT_MIN_VOLTAGE * 10)
 		{
-			gettimeofday(&_checkRelayWeldingTimer[index], NULL);
+		    GetClockTime(&_checkRelayWeldingTimer[index]);
 			_isRelayWelding[index] = YES;
 		}
 	}
@@ -2170,7 +2178,7 @@ unsigned char isModeChange()
 
 	return result;
 }
-
+#if 0
 void AcChargeTypeProcess()
 {
 	if (acgunCount > 0)
@@ -2370,6 +2378,7 @@ void AcChargeTypeProcess()
 		}
 	}
 }
+#endif
 
 int main(void)
 {
@@ -2484,7 +2493,7 @@ int main(void)
                     SetModelName_Fan();
                     SetRtcData_Fan();
                     sleep(1);
-                    gettimeofday(&_priority_time, NULL);
+                    GetClockTime(&_priority_time);
 
                     if(strlen((char *)ShmSysConfigAndInfo->SysInfo.FanModuleFwRev) != 0)
                     {
@@ -2505,8 +2514,13 @@ int main(void)
 
                 GetRelayOutputStatus();
 
+                GetGfdAdc();
+
                 for(int i = 0; i < ShmChargerInfo->Control.MaxConnector; i++)
                 {
+                    // Cable check (Set)
+                    CableCheckDetected(i);
+
                     // check k1 k2 relay 狀態
                     CheckK1K2RelayOutput(i);
 
@@ -2604,7 +2618,7 @@ int main(void)
                     GetFanSpeedByFunction();
                     GetFanSpeed();
                     ShmSysConfigAndInfo->SysInfo.SystemFanRotaSpeed = _setFanSpeed;
-                    gettimeofday(&_priority_time, NULL);
+                    GetClockTime(&_priority_time);
 
                     unsigned short TargetSpeed = ShmFanModuleData->TestFanSpeed;
 

+ 0 - 10
EVSE/Projects/DO360/Apps/Module_PrimaryComm.c

@@ -59,7 +59,6 @@ Ver ver;
 Gpio_in gpio_in;
 Rtc rtc;
 
-struct timeval _flash_time;
 byte _OutputDrv = 0;
 
 byte _acStatus = 0;
@@ -394,14 +393,6 @@ int InitComPort()
 	return fd;
 }
 
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-	struct timeval _end_time;
-	gettimeofday(&_end_time, NULL);
-
-	return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-
 int main(void)
 {
 	if(InitShareMemory() == FAIL)
@@ -434,7 +425,6 @@ int main(void)
 	}
 
 	SetRtcData();
-	gettimeofday(&_flash_time, NULL);
 
 	// update ac contact status
 	//_acStatus = ShmSysConfigAndInfo->SysInfo.AcContactorStatus;

+ 80 - 89
EVSE/Projects/DO360/Apps/Module_PsuComm.c

@@ -87,18 +87,19 @@ bool psuReceiveRecovery = false;
 unsigned short evseOutVol[CONNECTOR_QUANTITY] = {0, 0, 0, 0};
 unsigned short evseOutCur[CONNECTOR_QUANTITY] = {0, 0, 0, 0};
 unsigned short evseOutputDelay[CONNECTOR_QUANTITY] = {0, 0, 0, 0};
-struct timeval _PsuReceiveRecoveryCheck_time;
-struct timeval _PsuWorkStep_time;
-struct timeval _PsuGroupRole_time[CONNECTOR_QUANTITY];
-struct timeval _ChargingRequest_time[CONNECTOR_QUANTITY];
-struct timeval _PsuGroupDerating_time[CONNECTOR_QUANTITY];
-struct timeval _StopCharging_time[CONNECTOR_QUANTITY];
-struct timeval _ExtendCapability_time[CONNECTOR_QUANTITY];
-struct timeval _ReachCurrent_time[CONNECTOR_QUANTITY];
-struct timeval _BalanceCurrent_time[CONNECTOR_QUANTITY];
-struct timeval _MaxCurrent_time[CONNECTOR_QUANTITY];
-struct timeval _StageCurrent_time[CONNECTOR_QUANTITY];
-struct timeval _CheckSlaveReady_time[CONNECTOR_QUANTITY];
+struct timespec _PsuReceiveRecoveryCheck_time;
+struct timespec _PsuWorkStep_time;
+struct timespec _cmdSubPriority_time;
+struct timespec _PsuGroupRole_time[CONNECTOR_QUANTITY];
+struct timespec _ChargingRequest_time[CONNECTOR_QUANTITY];
+struct timespec _PsuGroupDerating_time[CONNECTOR_QUANTITY];
+struct timespec _StopCharging_time[CONNECTOR_QUANTITY];
+struct timespec _ExtendCapability_time[CONNECTOR_QUANTITY];
+struct timespec _ReachCurrent_time[CONNECTOR_QUANTITY];
+struct timespec _BalanceCurrent_time[CONNECTOR_QUANTITY];
+struct timespec _MaxCurrent_time[CONNECTOR_QUANTITY];
+struct timespec _StageCurrent_time[CONNECTOR_QUANTITY];
+struct timespec _CheckSlaveReady_time[CONNECTOR_QUANTITY];
 
 unsigned short  GCTargetVoltage[CONNECTOR_QUANTITY];
 unsigned short  GCTargetCurrent[CONNECTOR_QUANTITY];
@@ -110,16 +111,6 @@ GroupOutputConfigInfo PreGroupOutput[MAX_GROUP_QUANTITY];
 unsigned char OutputConfigStep[MAX_GROUP_QUANTITY];
 unsigned char _preOutputConfigStep[MAX_GROUP_QUANTITY];
 
-unsigned long GetTimeoutValue(struct timeval _sour_time);
-
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-	struct timeval _end_time;
-	gettimeofday(&_end_time, NULL);
-
-	return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-
 //=================================
 // Common routine
 //=================================
@@ -1984,7 +1975,7 @@ void UpdateMaxCurrent(unsigned char master, unsigned short current)
     {
         StageMaxCurrent[master] = current;
         ShmGroupCollection[master].GroupCtrl.bits.ReachMaxStageCurrent = false;
-        gettimeofday(&_StageCurrent_time[master], NULL);
+        GetClockTime(&_StageCurrent_time[master]);
     }
 
     if(!ShmGroupCollection[master].GroupCtrl.bits.ReachMaxStageCurrent)
@@ -2006,7 +1997,7 @@ void UpdateMaxCurrent(unsigned char master, unsigned short current)
         }
         MaxCurrentDemand[master] = current;
         ShmGroupCollection[master].GroupCtrl.bits.ReachMaxCurrentDemand = false;
-        gettimeofday(&_MaxCurrent_time[master], NULL);
+        GetClockTime(&_MaxCurrent_time[master]);
     }
 
     if(!ShmGroupCollection[master].GroupCtrl.bits.ReachMaxCurrentDemand)
@@ -2035,7 +2026,7 @@ bool IsMasterOutputCurrentStable(unsigned char master)
     if((presentOutput >= StableOutputCurrent[master] && presentOutput - StableOutputCurrent[master] > REACH_CURRENT_TOLERANCE) ||
         (presentOutput < StableOutputCurrent[master] && StableOutputCurrent[master] - presentOutput > REACH_CURRENT_TOLERANCE))
     {
-        gettimeofday(&_ReachCurrent_time[master], NULL);
+        GetClockTime(&_ReachCurrent_time[master]);
         StableOutputCurrent[master] = presentOutput;
     }
 
@@ -2080,7 +2071,7 @@ void MasterBalanceCurrent(unsigned char master)
         //LOG_INFO("Gun %d Increase Balance Current %d.%d A", master + 1, (realBalance / 10), (realBalance % 10));
 
         UpdateMasterPsuGroupLoading(master);
-        gettimeofday(&_BalanceCurrent_time[master], NULL);
+        GetClockTime(&_BalanceCurrent_time[master]);
     }
 }
 
@@ -2125,7 +2116,7 @@ void CheckCurrentBalance(unsigned char master)
         {
             ShmGroupCollection[master].GroupCtrl.bits.NeedCurrentBalance = true;
             PSU_LOG("Gun %d Output Current Is Unbalance, diffLoading = %d.%02d", master + 1, (diffLoading / 100), (diffLoading % 100));
-            gettimeofday(&_BalanceCurrent_time[master], NULL);
+            GetClockTime(&_BalanceCurrent_time[master]);
         }
     }
 
@@ -2271,7 +2262,7 @@ void CheckReleaseOrExtend(unsigned char master)
                 if(!ShmGroupCollection[master].GroupCtrl.bits.ExtendAvailable)
                 {
                     LOG_INFO("Gun %d Extend Capability Available", master + 1);
-                    gettimeofday(&_ExtendCapability_time[master], NULL);
+                    GetClockTime(&_ExtendCapability_time[master]);
                 }
                 ShmGroupCollection[master].GroupCtrl.bits.ExtendAvailable = true;
             }
@@ -2460,7 +2451,7 @@ void UpdatePsuGroupOutputConfig(unsigned char master)
                     OutputConfigStep[master] = _CURRENT_MODE_BALANCE;
                     if(OutputConfigStep[master] != _preOutputConfigStep[master])
                     {
-                        gettimeofday(&_ReachCurrent_time[master], NULL);
+                        GetClockTime(&_ReachCurrent_time[master]);
                         LOG_INFO("Gun %d In Balance Mode", master + 1);
                         StableOutputCurrent[master] = (int)chargingInfo[master]->PresentChargingCurrent * 10;
                         ShmGroupCollection[master].GroupCtrl.bits.OutputCurrentStable = false;
@@ -2832,7 +2823,7 @@ void ChargingRequestProcess(unsigned char group)
 
     if(ShmGroupCollection[group].GroupCtrl.bits.ChargingRequest && !ShmGroupCollection[group].GroupCtrl.bits.ChargingRequestConfirmed)
     {
-        gettimeofday(&_ChargingRequest_time[group], NULL);
+        GetClockTime(&_ChargingRequest_time[group]);
         ShmGroupCollection[group].GroupCtrl.bits.ChargingRequest = false;
         ShmGroupCollection[group].GroupCtrl.bits.ChargingRequestConfirmed = true;
         ShmGroupCollection[group].GroupCtrl.bits.GroupShareCheck = true;
@@ -2843,7 +2834,7 @@ void ChargingRequestProcess(unsigned char group)
         // check is there psu group to grab
         if(PsuGroupGrabCheck(group, &partner))
         {
-            gettimeofday(&_ChargingRequest_time[group], NULL);
+            GetClockTime(&_ChargingRequest_time[group]);
             ShmGroupCollection[group].GroupCtrl.bits.GrabGroupWait = true;
             PrepareToPowerOff(group + 1, &partner);
             memcpy(&ShmGroupCollection[group].PossibleMember, &partner, sizeof(PsuGroupPartner));
@@ -2871,7 +2862,7 @@ void ChargingRequestProcess(unsigned char group)
 
     if(ShmGroupCollection[group].GroupCtrl.bits.ShareCheckDone && !ShmGroupCollection[group].GroupCtrl.bits.FindGroupPartner)
     {
-        gettimeofday(&_ChargingRequest_time[group], NULL);
+        GetClockTime(&_ChargingRequest_time[group]);
         AddAvailableMember(group);
         ShmGroupCollection[group].GroupCtrl.bits.FindGroupPartner = true;
     }
@@ -2884,7 +2875,7 @@ void ChargingRequestProcess(unsigned char group)
         if(time >= WAIT_PARALLEL_RELAY_DELAY)
         {
             unsigned short original = ShmPsuGrouping->ParallelRelayConfig.CtrlValue;
-            gettimeofday(&_ChargingRequest_time[group], NULL);
+            GetClockTime(&_ChargingRequest_time[group]);
             SetParallelRelayOnOff(group, YES, _GROLE_MASTER);
             ShmGroupCollection[group].GroupCtrl.bits.ParallelRelayOn = true;
             LOG_INFO("Gun %d Charging Request Set All Member Parallel Relay On %X -> %X", group + 1, original, ShmPsuGrouping->ParallelRelayConfig.CtrlValue);
@@ -2900,7 +2891,7 @@ void ChargingRequestProcess(unsigned char group)
         //if(confirmed || time >= WAIT_RELAY_CONFIRMED_TIME)
         if(time >= WAIT_RELAY_CONFIRMED_TIME)
         {
-            gettimeofday(&_ChargingRequest_time[group], NULL);
+            GetClockTime(&_ChargingRequest_time[group]);
             ShmGroupCollection[group].GroupCtrl.bits.ParallelRelayConfirmed = true;
             LOG_INFO("Gun %d Charging Request Parallel Relay Confirmed %s", group + 1, confirmed ? "OK" : "Timeout");
         }
@@ -2928,7 +2919,7 @@ void PsuGroupDeratingProcess(unsigned char master)
     if(ShmGroupCollection[master].GroupCtrl.bits.NeedDerating)
     {
         // reduce output current capability start
-        gettimeofday(&_PsuGroupDerating_time[master], NULL);
+        GetClockTime(&_PsuGroupDerating_time[master]);
         unsigned short ReAssignCurrent = GetPresentTargetCurrent(master, _GROLE_SLAVE);
         ShmGroupCollection[master].ReAssignAvailableCurrent = ReAssignCurrent;
         ShmGroupCollection[master].GroupCtrl.bits.NeedDerating = false;
@@ -2954,7 +2945,7 @@ void PsuGroupDeratingProcess(unsigned char master)
 
         if(start || time >= WAIT_EV_DERATING_TIMEOUT || bypass)
         {
-            gettimeofday(&_PsuGroupDerating_time[master], NULL);
+            GetClockTime(&_PsuGroupDerating_time[master]);
             ShmGroupCollection[master].GroupCtrl.bits.DeratingStart = true;
             LOG_INFO("Gun %d %s Start Derating%s", master + 1, start ? "Normal" : "Force", bypass ? " (Bypass)" : "");
             SetMemberStartPowerOff(master, _GROLE_PREPARE_SWITCH_OFF);
@@ -2966,7 +2957,7 @@ void PsuGroupDeratingProcess(unsigned char master)
                     (int)(chargingInfo[master]->EvBatterytargetCurrent * 10) :
                     ShmGroupCollection[master].ReAssignAvailableCurrent;
                 ShmGroupCollection[master].GroupCtrl.bits.ReachMaxStageCurrent = false;
-                gettimeofday(&_StageCurrent_time[master], NULL);
+                GetClockTime(&_StageCurrent_time[master]);
             }
         }
     }
@@ -2979,7 +2970,7 @@ void PsuGroupDeratingProcess(unsigned char master)
 
         if(power_off_ok || time >= WAIT_SLAVE_POWER_OFF_TIMEOUT)
         {
-            gettimeofday(&_PsuGroupDerating_time[master], NULL);
+            GetClockTime(&_PsuGroupDerating_time[master]);
             SetMemberPowerOffDone(master);
             ShmGroupCollection[master].GroupCtrl.bits.DeratingPowerOffDone = true;
             LOG_INFO("Gun %d Set Derating Member Power Off %s", master + 1, power_off_ok ? "OK" : "Timeout");
@@ -2994,7 +2985,7 @@ void PsuGroupDeratingProcess(unsigned char master)
         if(time >= WAIT_PARALLEL_RELAY_DELAY)
         {
             unsigned short original = ShmPsuGrouping->ParallelRelayConfig.CtrlValue;
-            gettimeofday(&_PsuGroupDerating_time[master], NULL);
+            GetClockTime(&_PsuGroupDerating_time[master]);
             SetParallelRelayOnOff(master, NO, _GROLE_SWITCH_OFF_OK);
             ShmGroupCollection[master].GroupCtrl.bits.DeratingRelayOff = true;
             LOG_INFO("Gun %d Set Parallel Relay Off %X -> %X", master + 1, original, ShmPsuGrouping->ParallelRelayConfig.CtrlValue);
@@ -3010,7 +3001,7 @@ void PsuGroupDeratingProcess(unsigned char master)
         //if(confirmed || time >= WAIT_RELAY_CONFIRMED_TIME)
         if(time >= WAIT_RELAY_CONFIRMED_TIME)
         {
-            gettimeofday(&_PsuGroupDerating_time[master], NULL);
+            GetClockTime(&_PsuGroupDerating_time[master]);
             ShmGroupCollection[master].GroupCtrl.bits.DeratingRelayConfirmed = true;
             LOG_INFO("Gun %d Parallel Relay Confirmed %s", master + 1, confirmed ? "OK" : "Timeout");
         }
@@ -3038,7 +3029,7 @@ void MasterStopChargingProcess(unsigned char master)
     if(ShmGroupCollection[master].GroupCtrl.bits.StopChargingRequest && !ShmGroupCollection[master].GroupCtrl.bits.StopChargingConfirmed)
     {
         // set all member to power off
-        gettimeofday(&_StopCharging_time[master], NULL);
+        GetClockTime(&_StopCharging_time[master]);
         SetMemberStartPowerOff(master, _GROLE_MASTER);
         ShmGroupCollection[master].GroupCtrl.bits.StopChargingConfirmed = true;
     }
@@ -3051,7 +3042,7 @@ void MasterStopChargingProcess(unsigned char master)
 
         if(power_off_ok || time >= WAIT_SLAVE_POWER_OFF_TIMEOUT)
         {
-            gettimeofday(&_StopCharging_time[master], NULL);
+            GetClockTime(&_StopCharging_time[master]);
             SetMemberPowerOffDone(master);
             ShmGroupCollection[master].GroupCtrl.bits.AllPowerOffDone = true;
             LOG_INFO("Gun %d Set All Member Power Off %s", master + 1, power_off_ok ? "OK" : "Timeout");
@@ -3066,7 +3057,7 @@ void MasterStopChargingProcess(unsigned char master)
         if(time >= WAIT_PARALLEL_RELAY_DELAY)
         {
             unsigned short original = ShmPsuGrouping->ParallelRelayConfig.CtrlValue;
-            gettimeofday(&_StopCharging_time[master], NULL);
+            GetClockTime(&_StopCharging_time[master]);
             SetParallelRelayOnOff(master, NO, _GROLE_MASTER);
             ShmGroupCollection[master].GroupCtrl.bits.AllParallelRelayOff = true;
             LOG_INFO("Gun %d Set All Member Parallel Relay Off %X -> %X", master + 1, original, ShmPsuGrouping->ParallelRelayConfig.CtrlValue);
@@ -3082,7 +3073,7 @@ void MasterStopChargingProcess(unsigned char master)
         //if(confirmed || time >= WAIT_RELAY_CONFIRMED_TIME)
         if(time >= WAIT_RELAY_CONFIRMED_TIME)
         {
-            gettimeofday(&_StopCharging_time[master], NULL);
+            GetClockTime(&_StopCharging_time[master]);
             ShmGroupCollection[master].GroupCtrl.bits.AllParallelRelayConfirmed = true;
             LOG_INFO("Gun %d All Member Parallel Relay Confirmed %s", master + 1, confirmed ? "OK" : "Timeout");
         }
@@ -3134,12 +3125,12 @@ void SlaveStopChargingProcess(unsigned char slave)
         if(ShmGroupCollection[master].Role == _GROLE_REQUEST_TO_CHARGING)
         {
             LOG_INFO("Gun %d Need Wait Gun %d Grouping Completed", slave + 1, master + 1);
-            gettimeofday(&_CheckSlaveReady_time[slave], NULL);
+            GetClockTime(&_CheckSlaveReady_time[slave]);
         }
         else if(ShmGroupCollection[master].Role == _GROLE_MASTER && ShmGroupCollection[master].GroupCtrl.bits.DeratingConfirmed)
         {
             LOG_INFO("Gun %d Need Wait Gun %d Derating Completed", slave + 1, master + 1);
-            gettimeofday(&_CheckSlaveReady_time[slave], NULL);
+            GetClockTime(&_CheckSlaveReady_time[slave]);
         }
         else
         {
@@ -3165,7 +3156,7 @@ void SlaveStopChargingProcess(unsigned char slave)
             {
                 ShmGroupCollection[slave].GroupCtrl.bits.WaitSlaveReady = true;
                 LOG_INFO("Gun %d Is Ready", slave + 1);
-                gettimeofday(&_CheckSlaveReady_time[slave], NULL);
+                GetClockTime(&_CheckSlaveReady_time[slave]);
             }
         }
     }
@@ -3232,7 +3223,7 @@ void MasterExtendCapabilityProcess(unsigned char master)
 
     if(ShmGroupCollection[master].GroupCtrl.bits.MorePowerRequest && !ShmGroupCollection[master].GroupCtrl.bits.MorePowerConfirmed)
     {
-        gettimeofday(&_ExtendCapability_time[master], NULL);
+        GetClockTime(&_ExtendCapability_time[master]);
         memset(&ShmGroupCollection[master].PossibleMember, 0x00, sizeof(PsuGroupPartner));
 
         FindPsuGroupPartner(master, MAX_GROUP_QUANTITY, &ShmGroupCollection[master].PossibleMember);
@@ -3264,7 +3255,7 @@ void MasterExtendCapabilityProcess(unsigned char master)
         }
         if(!ShmGroupCollection[master].GroupCtrl.bits.ExtendPrecharge)
         {
-            gettimeofday(&_ExtendCapability_time[master], NULL);
+            GetClockTime(&_ExtendCapability_time[master]);
             LOG_INFO("Gun %d Set ExtendPrecharge Voltage %d.%d V", master + 1, (voltage / 10), (voltage % 10));
         }
         ShmGroupCollection[master].GroupCtrl.bits.ExtendPrecharge = true;
@@ -3280,7 +3271,7 @@ void MasterExtendCapabilityProcess(unsigned char master)
             LOG_INFO("Gun %d ExtendPrecharge %s", master + 1, ready ? "Ready" : "Timeout");
             if(ready)
             {
-                gettimeofday(&_ExtendCapability_time[master], NULL);
+                GetClockTime(&_ExtendCapability_time[master]);
                 SetExtendPrechargeCompleted(master);
                 ShmGroupCollection[master].GroupCtrl.bits.ExtendPrechargeDone = true;
             }
@@ -3300,7 +3291,7 @@ void MasterExtendCapabilityProcess(unsigned char master)
         if(time >= WAIT_PARALLEL_RELAY_DELAY)
         {
             unsigned short original = ShmPsuGrouping->ParallelRelayConfig.CtrlValue;
-            gettimeofday(&_ExtendCapability_time[master], NULL);
+            GetClockTime(&_ExtendCapability_time[master]);
             SetParallelRelayOnOff(master, YES, _GROLE_PRECHARGE_READY);
             ShmGroupCollection[master].GroupCtrl.bits.ExtendRelayOn = true;
             LOG_INFO("Gun %d Set Extend Parallel Relay On %X -> %X", master + 1, original, ShmPsuGrouping->ParallelRelayConfig.CtrlValue);
@@ -3331,10 +3322,10 @@ void MasterExtendCapabilityProcess(unsigned char master)
     {
         ShmGroupCollection[master].GroupCtrl.RoleCtrl.ExtendCapabilityCtrlValue = 0;
         ShmGroupCollection[master].GroupCtrl.bits.OutputCurrentStable = false;
-        gettimeofday(&_ReachCurrent_time[master], NULL);
+        GetClockTime(&_ReachCurrent_time[master]);
         UpdateGunAvailableCapability(master);
         ShmGroupCollection[master].GroupCtrl.bits.ReachMaxStageCurrent = false;
-        gettimeofday(&_StageCurrent_time[master], NULL);
+        GetClockTime(&_StageCurrent_time[master]);
         LOG_INFO("Gun %d Extend Capability Completed", master + 1);
     }
 }
@@ -3392,7 +3383,7 @@ void PsuGroupControlProcess(void)
                     ShmGroupCollection[group].GroupCtrl.RoleCtrl.ExtendCapabilityCtrlValue = 0;
                     ShmGroupCollection[group].GroupCtrl.RoleCtrl.SlaveCtrlValue = 0;
                     PSU_LOG("===== PSU Group[%02X] ===== Idle", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
 
                     ShmPsuGrouping->GroupOutput[group].GTargetVoltage = 0;
                     ShmPsuGrouping->GroupOutput[group].GTargetCurrent = 0;
@@ -3421,7 +3412,7 @@ void PsuGroupControlProcess(void)
                     ShmGroupCollection[group].GroupCtrl.RoleCtrl.StopChargingCtrlValue = 0;
                     ShmGroupCollection[group].GroupCtrl.RoleCtrl.DeratingCtrlValue = 0;
                     PSU_LOG("===== PSU Group[%02X] ===== Master", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
 
                     OutputConfigStep[group] = _CURRENT_MODE_NONE;
                     _preOutputConfigStep[group] = _CURRENT_MODE_NONE;
@@ -3437,8 +3428,8 @@ void PsuGroupControlProcess(void)
                         ShmGroupCollection[group].GroupCtrl.bits.AlreadyInChargingMode = true;
                         ShmGroupCollection[group].GroupCtrl.bits.ReachMaxCurrentDemand = false;
                         ShmGroupCollection[group].GroupCtrl.bits.ReachMaxStageCurrent = false;
-                        gettimeofday(&_MaxCurrent_time[group], NULL);
-                        gettimeofday(&_StageCurrent_time[group], NULL);
+                        GetClockTime(&_MaxCurrent_time[group]);
+                        GetClockTime(&_StageCurrent_time[group]);
                     }
                 }
 
@@ -3507,7 +3498,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Slave", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
 
                 if(ShmGroupCollection[group].GroupCtrl.RoleCtrl.SlaveCtrlValue != 0)
@@ -3525,7 +3516,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Prepare Off", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
 
                 time = GetTimeoutValue(_PsuGroupRole_time[group]) / uSEC_VAL;
@@ -3546,7 +3537,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Slave Power Off", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
 
                 time = GetTimeoutValue(_PsuGroupRole_time[group]) / uSEC_VAL;
@@ -3571,7 +3562,7 @@ void PsuGroupControlProcess(void)
                     PSU_LOG("===== PSU Group[%02X] ===== Switch Off OK, %d.%d V, %d.%d A", group,
                         (ShmPsuData->PsuGroup[group].GroupPresentOutputVoltage / 10), (ShmPsuData->PsuGroup[group].GroupPresentOutputVoltage % 10),
                         (ShmPsuData->PsuGroup[group].GroupPresentOutputCurrent / 10), (ShmPsuData->PsuGroup[group].GroupPresentOutputCurrent % 10));
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
                 break;
 
@@ -3582,7 +3573,7 @@ void PsuGroupControlProcess(void)
                     PSU_LOG("===== PSU Group[%02X] ===== Wait Idle, %d.%d V, %d.%d A", group,
                         (ShmPsuData->PsuGroup[group].GroupPresentOutputVoltage / 10), (ShmPsuData->PsuGroup[group].GroupPresentOutputVoltage % 10),
                         (ShmPsuData->PsuGroup[group].GroupPresentOutputCurrent / 10), (ShmPsuData->PsuGroup[group].GroupPresentOutputCurrent % 10));
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
                 break;
 
@@ -3591,7 +3582,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Wait Slave", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
 
                 time = GetTimeoutValue(_PsuGroupRole_time[group]) / uSEC_VAL;
@@ -3618,7 +3609,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Prepare Attach On", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
 
                 SetPsuGroupOutput(group);
@@ -3630,7 +3621,7 @@ void PsuGroupControlProcess(void)
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Precharge %d.%d V Ready",
                         group, (ShmPsuData->PsuGroup[group].GroupPresentOutputVoltage / 10), (ShmPsuData->PsuGroup[group].GroupPresentOutputVoltage % 10));
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
                 break;
 
@@ -3639,7 +3630,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Extend Stop", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
 
                 time = GetTimeoutValue(_PsuGroupRole_time[group]) / uSEC_VAL;
@@ -3663,7 +3654,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Request To Charging", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
 
                 if(ShmGroupCollection[group].GroupCtrl.RoleCtrl.IdleCtrlValue != 0)
@@ -3677,7 +3668,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Terminate", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
                 break;
 
@@ -3686,7 +3677,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Wait Terminated", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
                 break;
 
@@ -3695,7 +3686,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== None", group);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
                 break;
 
@@ -3704,7 +3695,7 @@ void PsuGroupControlProcess(void)
                 {
                     ShmGroupCollection[group].PreRole = role;
                     PSU_LOG("===== PSU Group[%02X] ===== Unknown Role = %d", group, role);
-                    gettimeofday(&_PsuGroupRole_time[group], NULL);
+                    GetClockTime(&_PsuGroupRole_time[group]);
                 }
 
                 SetPsuGroupRole(group, _GROLE_NONE);
@@ -3902,7 +3893,7 @@ int main(void)
 		if((GetTimeoutValue(_PsuReceiveRecoveryCheck_time) / uSEC_VAL) >= PSU_TASK_CHECK_TIME)
 		{
 		    PsuReceiveRecoveryCheck();
-		    gettimeofday(&_PsuReceiveRecoveryCheck_time, NULL);
+		    GetClockTime(&_PsuReceiveRecoveryCheck_time);
 		}
 
 		switch(ShmPsuData->Work_Step)
@@ -3931,8 +3922,8 @@ int main(void)
                 {
                     _PrePsuWorkStep = ShmPsuData->Work_Step;
                     LOG_INFO("== PSU == GET_PSU_COUNT");
-                    gettimeofday(&_PsuWorkStep_time, NULL);
-                    gettimeofday(&_cmdSubPriority_time, NULL);
+                    GetClockTime(&_PsuWorkStep_time);
+                    GetClockTime(&_cmdSubPriority_time);
                 }
 
 				int time = GetTimeoutValue(_PsuWorkStep_time) / uSEC_VAL;
@@ -3969,7 +3960,7 @@ int main(void)
 	                        GetModuleCount(index);
 	                    }
 					}
-					gettimeofday(&_cmdSubPriority_time, NULL);
+					GetClockTime(&_cmdSubPriority_time);
 				}
 			}
 				break;
@@ -3983,7 +3974,7 @@ int main(void)
                     // clean psu location info
                     memset(ShmPsuPosition, 0x00, sizeof(PsuPositionInfoData));
 
-                    gettimeofday(&_cmdSubPriority_time, NULL);
+                    GetClockTime(&_cmdSubPriority_time);
                 }
 
                 int interval = GetTimeoutValue(_cmdSubPriority_time) / mSEC_VAL;
@@ -4029,8 +4020,8 @@ int main(void)
                     _PrePsuWorkStep = ShmPsuData->Work_Step;
                     LOG_INFO("== PSU == PSU_COUNT_CONFIRM");
 
-                    gettimeofday(&_PsuWorkStep_time, NULL);
-                    gettimeofday(&_cmdSubPriority_time, NULL);
+                    GetClockTime(&_PsuWorkStep_time);
+                    GetClockTime(&_cmdSubPriority_time);
                 }
 
                 int time = GetTimeoutValue(_PsuWorkStep_time) / uSEC_VAL;
@@ -4070,7 +4061,7 @@ int main(void)
                         // 取各群模組數量
                         GetModuleCount(index);
                     }
-                    gettimeofday(&_cmdSubPriority_time, NULL);
+                    GetClockTime(&_cmdSubPriority_time);
                 }
             }
                 break;
@@ -4080,7 +4071,7 @@ int main(void)
                 {
                     _PrePsuWorkStep = ShmPsuData->Work_Step;
                     LOG_INFO("== PSU == Get_PSU_VERSION");
-                    gettimeofday(&_cmdSubPriority_time, NULL);
+                    GetClockTime(&_cmdSubPriority_time);
 
                     // clean version info
                     memset(ShmPsuData->PsuVersion, 0x00, sizeof(ShmPsuData->PsuVersion));
@@ -4124,7 +4115,7 @@ int main(void)
                             }
                         }
                     }
-                    gettimeofday(&_cmdSubPriority_time, NULL);
+                    GetClockTime(&_cmdSubPriority_time);
                 }
             }
                 break;
@@ -4134,8 +4125,8 @@ int main(void)
                 {
                     _PrePsuWorkStep = ShmPsuData->Work_Step;
                     LOG_INFO("== PSU == GET_SYS_CAP");
-                    gettimeofday(&_PsuWorkStep_time, NULL);
-                    gettimeofday(&_cmdSubPriority_time, NULL);
+                    GetClockTime(&_PsuWorkStep_time);
+                    GetClockTime(&_cmdSubPriority_time);
                 }
 
                 int time = GetTimeoutValue(_PsuWorkStep_time) / uSEC_VAL;
@@ -4172,7 +4163,7 @@ int main(void)
                             }
                         }
 				    }
-					gettimeofday(&_cmdSubPriority_time, NULL);
+				    GetClockTime(&_cmdSubPriority_time);
 				}
 			}
 				break;
@@ -4198,8 +4189,8 @@ int main(void)
                 {
                     _PrePsuWorkStep = ShmPsuData->Work_Step;
                     LOG_INFO("== PSU == _WORK_CHARGING");
-                    gettimeofday(&_PsuWorkStep_time, NULL);
-                    gettimeofday(&_cmdSubPriority_time, NULL);
+                    GetClockTime(&_PsuWorkStep_time);
+                    GetClockTime(&_cmdSubPriority_time);
 
                     PsuGroupingInitial();
                 }
@@ -4211,7 +4202,7 @@ int main(void)
 				{
 					//PreCheckSmartChargingStep();
 					startModuleFlag = true;
-					gettimeofday(&_cmdSubPriority_time, NULL);
+					GetClockTime(&_cmdSubPriority_time);
 
 				    for(byte group = 0; group < GENERAL_GUN_QUANTITY; group++)
 				    {
@@ -4243,7 +4234,7 @@ int main(void)
 						GetModuleOutputF(index); Await();
 					}
 
-					gettimeofday(&_cmdSubPriority_time, NULL);
+					GetClockTime(&_cmdSubPriority_time);
 				}
 
 				byte _switch = 0x00;
@@ -4272,7 +4263,7 @@ int main(void)
                 {
                     _PrePsuWorkStep = ShmPsuData->Work_Step;
                     LOG_INFO("== PSU == _INIT_PSU_STATUS");
-                    gettimeofday(&_cmdSubPriority_time, NULL);
+                    GetClockTime(&_cmdSubPriority_time);
                 }
 			    break;
 			default:

+ 0 - 6
EVSE/Projects/DO360/Apps/Module_PsuComm.h

@@ -39,12 +39,6 @@ typedef unsigned int 		unit;
 struct ChargingInfoData *chargingInfo[CONNECTOR_QUANTITY];
 bool isStartOutputSwitch[CONNECTOR_QUANTITY];
 
-struct timeval _cmdSubPriority_time;
-struct timeval _derating_time;
-struct timeval _max_time;
-
-struct timeval _test_time;
-
 bool isCharging = false;
 bool isWaitingAver = false;
 bool isReadToCharging = false;

+ 148 - 25
EVSE/Projects/DO360/Apps/ReadCmdline.c

@@ -39,6 +39,7 @@
 #include 	"../../define.h"
 #include    "Config.h"
 #include    "Module_EvComm.h"
+#include    "Common.h"
 
 typedef unsigned char			byte;
 #define PASS				1
@@ -252,14 +253,6 @@ int InitShareMemory()
     return result;
 }
 
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-	struct timeval _end_time;
-	gettimeofday(&_end_time, NULL);
-
-	return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-
 void RunStatusProc(char *v1, char *v2)
 {
 	printf("OrderCharging = %d \n", ShmSysConfigAndInfo->SysInfo.OrderCharging);
@@ -411,6 +404,55 @@ void RunSelfProc()
 	printf("self test status = %x\n", ShmSysConfigAndInfo->SysInfo.SelfTestSeq);
 }
 
+void ShowFwVer(void)
+{
+    printf("\r\nPower Cabinet, Model Name: %s, SN: %s", ShmSysConfigAndInfo->SysConfig.ModelName, ShmSysConfigAndInfo->SysConfig.SerialNumber);
+    printf("\r\n  Csu Bootload: %s", ShmSysConfigAndInfo->SysInfo.CsuBootLoadFwRev);
+    //printf("\r\n    Csu Kernel: %s", ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev);
+    printf("\r\n    Csu Kernel: ");
+    for(int i = 0; i < strlen((char *)ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev); i++)
+    {
+        if(ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev[i] != '\r' && ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev[i] != '\n')
+        {
+            printf("%c", ShmSysConfigAndInfo->SysInfo.CsuKernelFwRev[i]);
+        }
+    }
+    printf("\r\n   Csu Root Fs: %s", ShmSysConfigAndInfo->SysInfo.CsuRootFsFwRev);
+    printf("\r\n   Csu Primary: %s", ShmSysConfigAndInfo->SysInfo.CsuPrimFwRev);
+    printf("\r\n    Fan Module: %s", ShmSysConfigAndInfo->SysInfo.FanModuleFwRev);
+    printf("\r\n Relay1 Module: %s", ShmSysConfigAndInfo->SysInfo.RelayModuleFwRev);
+    printf("\r\n Relay2 Module: %s", ShmSysConfigAndInfo->SysInfo.Relay2ModuleFwRev);
+
+    for(int i = 0; i < ShmSysConfigAndInfo->SysInfo.DispenserInfo.DispenserQuantity; i++)
+    {
+        printf("\r\n\r\nDispenser[%d] Status: %d", i, ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus);
+        if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_None &&
+            ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LocalStatus != _DS_Timeout)
+        {
+            printf(", Model Name: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ModelName);
+            printf("\r\n Csu Bootload: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].CsuBootLoadFwRev);
+            //printf("\r\n   Csu Kernel: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].CsuKernelFwRev);
+            printf("\r\n    Csu Kernel: ");
+            for(int j = 0; j < strlen((char *)ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].CsuKernelFwRev); j++)
+            {
+                if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].CsuKernelFwRev[j] != '\r' &&
+                    ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].CsuKernelFwRev[j] != '\n')
+                {
+                    printf("%c", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].CsuKernelFwRev[j]);
+                }
+            }
+            printf("\r\n  Csu Root Fs: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].CsuRootFsFwRev);
+            printf("\r\n  Csu Primary: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].CsuPrimFwRev);
+            printf("\r\n   Fan Module: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].FanModuleFwRev);
+            printf("\r\n Relay Module: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].RelayModuleFwRev);
+            printf("\r\n  Connector 1: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Connector1FwRev);
+            printf("\r\n  Connector 2: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].Connector2FwRev);
+            printf("\r\n   Led Module: %s", ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].LedModuleFwRev);
+        }
+    }
+    printf("\r\n\r\n");
+}
+
 void GetFwVerProc(char *v1)
 {
     if (strcmp(v1, "407") == 0)
@@ -562,13 +604,14 @@ void SetPowerValue(char *v1, char *v2)
 
 void GetSystemInfo()
 {
-	printf ("ModelName = %s \n", ShmSysConfigAndInfo->SysConfig.ModelName);
-	printf ("SerialNumber = %s \n", ShmSysConfigAndInfo->SysConfig.SerialNumber);
-	printf ("InternetConn = %d \n", ShmSysConfigAndInfo->SysInfo.InternetConn);
+	printf ("\r\n   ModelName = %s", ShmSysConfigAndInfo->SysConfig.ModelName);
+	printf ("\r\nSerialNumber = %s", ShmSysConfigAndInfo->SysConfig.SerialNumber);
+	printf ("\r\nInternetConn = %d", ShmSysConfigAndInfo->SysInfo.InternetConn);
 
-	printf ("MaxChargingPower = %d, MaxChargingCurrent = %d \n",
+	printf ("\r\nMaxChargingPower = %d, MaxChargingCurrent = %d",
 			ShmSysConfigAndInfo->SysConfig.MaxChargingPower,
 			ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent);
+	printf("\r\n\r\n");
 }
 
 void ChangeGunNum()
@@ -1371,7 +1414,7 @@ void SetWiringInfo(char *v1, char *v2)
             ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence = dispenser;
             ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity += connector;
 
-            ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.WiringInfoChanged = true;
+            ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged = true;
 
             ShmSysConfigAndInfo->SysInfo.DispenserInfo.DispenserQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence;
             ShmSysConfigAndInfo->SysInfo.DispenserInfo.TotalConnectorQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity;
@@ -1390,7 +1433,7 @@ void SetWiringInfo(char *v1, char *v2)
             }
             ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity = quantity;
 
-            ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.WiringInfoChanged = true;
+            ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged = true;
 
             ShmSysConfigAndInfo->SysInfo.DispenserInfo.DispenserQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.DispenserSequence;
             ShmSysConfigAndInfo->SysInfo.DispenserInfo.TotalConnectorQuantity = ShmSysConfigAndInfo->SysConfig.WiringInfo.MaxConnectorQuantity;
@@ -1422,7 +1465,7 @@ void CleanWiringInfo(void)
 
     memset((char *)&ShmSysConfigAndInfo->SysConfig.WiringInfo, 0x00, sizeof(WiringInfoData));
 
-    ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.WiringInfoChanged = true;
+    ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged = true;
     ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.CleanWiringInfo = true;
 
     printf("\r\n");
@@ -1997,7 +2040,7 @@ void ShowCabinetInfo(void)
 
     for(int i = 0; i < GENERAL_GUN_QUANTITY; i++)
     {
-        printf("\r\n Connector[%d] Index: %d, Status = %2d , %s", i, _chargingData[i]->Index, _chargingData[i]->SystemStatus,
+        printf("\r\n Connector[%d] Index: %2X, Status = %2d , %s", i, _chargingData[i]->Index, _chargingData[i]->SystemStatus,
             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].Enable ? "Enable" : "Disable");
     }
 
@@ -2020,7 +2063,8 @@ void ShowCabinetInfo(void)
                 ((ipAddress >> 0) & 0xFF), ((ipAddress >> 8) & 0xFF), ((ipAddress >> 16) & 0xFF), ((ipAddress >> 24) & 0xFF));
             for(int j = 0; j < ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorQuantity; j++)
             {
-                printf("\r\n   - Connector[%d] Gun %d", j, ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorID[j]);
+                unsigned char gun = ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[i].ConnectorID[j];
+                printf("\r\n   - Connector[%d] Gun %d, %s", j, gun, _chargingData[gun - 1]->ConnectorPlugIn ? "Plugged" : "Unplugged");
             }
         }
         else
@@ -2168,7 +2212,7 @@ void SetGunStartCharging(char *v1, char *v2, char *v3)
 */
     bool wait = true;
     int time = 0;
-    struct timeval _Wait_time;
+    struct timespec _Wait_time;
     unsigned char PreviousSystemStatus = 0xFF;
     unsigned short _targetVoltage = 0, _targetCurrent = 0;
 
@@ -2257,7 +2301,7 @@ void SetGunStartCharging(char *v1, char *v2, char *v3)
                     }
 
                     PreviousSystemStatus = _chargingData[gun - 1]->SystemStatus;
-                    gettimeofday(&_Wait_time, NULL);
+                    GetClockTime(&_Wait_time);
                 }
                 if(_targetVoltage != (int)_chargingData[gun - 1]->EvBatterytargetVoltage ||
                     _targetCurrent != (int)_chargingData[gun - 1]->EvBatterytargetCurrent)
@@ -2389,7 +2433,7 @@ void SetGunStopCharging(char *v1)
 
     bool wait = true;
     int time = 0;
-    struct timeval _Wait_time;
+    struct timespec _Wait_time;
     unsigned char PreviousSystemStatus = 0xFF;
 
     while(wait)
@@ -2411,7 +2455,7 @@ void SetGunStopCharging(char *v1)
                     }
                     PreviousSystemStatus = _chargingData[gun - 1]->SystemStatus;
 
-                    gettimeofday(&_Wait_time, NULL);
+                    GetClockTime(&_Wait_time);
                 }
 
                 time = GetTimeoutValue(_Wait_time) / uSEC_VAL;
@@ -2716,6 +2760,61 @@ void ShowStatus(void)
     printf("\r\n\r\n");
 }
 
+void ShowWhiteCardList(void)
+{
+    printf("\r\nWhite Card List");
+    for(int i = 0; i < 10; i++)
+    {
+        printf("\r\n White Card [%2d]: %s", i + 1, (char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i]);
+    }
+
+    printf("\r\n\r\n");
+}
+
+void WriteWhiteCard(char *v1, char *v2)
+{
+    int cardIndex = 0;
+
+    cardIndex = atoi(v1);
+
+    if(cardIndex < 1 || cardIndex > 10)
+    {
+        printf("\r\n White Card Index Fail\r\n\r\n");
+        return;
+    }
+
+    if(strlen(v2) == 0 || strlen(v2) > 31)
+    {
+        printf("\r\n White Card Fail\r\n\r\n");
+        return;
+    }
+    printf("\r\n Str Len = %d = %s", strlen(v2), v2);
+    printf("\r\n Set White Card Index %d = %s", cardIndex, v2);
+    memcpy((char *)&ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[cardIndex - 1][0], v2, strlen(v2));
+    ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged = true;
+
+    printf("\r\n\r\n");
+}
+
+void EraseWhiteCard(char *v1)
+{
+    int cardIndex = 0;
+
+    cardIndex = atoi(v1);
+
+    if(cardIndex < 1 || cardIndex > 10)
+    {
+        printf("\r\n White Card Index Fail\r\n\r\n");
+        return;
+    }
+
+    printf("\r\n Erase White Card Index = %d", cardIndex);
+    memset((char *)&ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[cardIndex - 1][0], 0x00, 32);
+    ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged = true;
+
+    printf("\r\n\r\n");
+}
+
 int main(void)
 {
 	if(InitShareMemory() == FAIL)
@@ -2755,7 +2854,7 @@ int main(void)
 	for(;;)
 	{
 		char word[128];
-		char newString[7][10];
+		char newString[7][32];
 		int i,j,ctr;
 
 		fgets(word, sizeof(word), stdin);
@@ -2819,10 +2918,11 @@ int main(void)
 		}
 		else if(strcmp(newString[0], "ver") == 0)
 		{
-			if (strcmp(newString[1], "-1") == 0	|| strcmp(newString[1], "") == 0)
-				continue;
+			//if (strcmp(newString[1], "-1") == 0	|| strcmp(newString[1], "") == 0)
+			//	continue;
 			// 取 FW 版號
-			GetFwVerProc(newString[1]);
+			//GetFwVerProc(newString[1]);
+			ShowFwVer();
 		}
 		else if (strcmp(newString[0], "update") == 0)
 		{
@@ -3059,6 +3159,29 @@ int main(void)
         else if(strcmp(newString[0], "status") == 0)
         {
             ShowStatus();
+        }
+        else if(strcmp(newString[0], "whiteR") == 0)
+        {
+            ShowWhiteCardList();
+        }
+        else if(strcmp(newString[0], "whiteW") == 0)
+        {
+            if(strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0 ||
+                strcmp(newString[2], "-1") == 0 || strcmp(newString[2], "") == 0)
+            {
+                printf ("Input cmd fail ------  whiteW [index 1-10] [card id]\n\n");
+                continue;
+            }
+            WriteWhiteCard(newString[1], newString[2]);
+        }
+        else if(strcmp(newString[0], "whiteE") == 0)
+        {
+            if(strcmp(newString[1], "-1") == 0 || strcmp(newString[1], "") == 0)
+            {
+                printf ("Input cmd fail ------  whiteE [index 1-10]\n\n");
+                continue;
+            }
+            EraseWhiteCard(newString[1]);
         }
 		else
 			printf ("%s\n", msg);

+ 12 - 0
EVSE/Projects/DO360/Apps/internalComm.h

@@ -151,6 +151,18 @@ typedef struct RELAY
 	}relay_event;
 }Relay;
 
+typedef union
+{
+    unsigned char gfd_vlaue[6];
+    struct
+    {
+        unsigned short Resister;
+        unsigned short Voltage;
+        unsigned char  GFD_Result;
+        unsigned char  rb_step;
+    }bits;
+}Connector_GFD;
+
 typedef struct GFD
 {
 	unsigned short Resister_conn1;

+ 234 - 213
EVSE/Projects/DO360/Apps/main.c

@@ -76,6 +76,7 @@
 
 #define 	DB_FILE				"/Storage/ChargeLog/localCgargingRecord.db"
 
+#define     MAIN_PRIORITY_INTERVAL  5
 #define		SELFTEST_TIMEOUT		60
 #define		AUTHORIZE_TIMEOUT		30
 #define 	AUTHORIZE_COMP_TIMEOUT	1
@@ -83,8 +84,8 @@
 #define 	AUTHORIZE_STOP_TIMEOUT	30
 #define 	RETURN_TO_CHARGING_PAGE	30
 #define		GUN_PREPARE_TIMEOUT		30
-#define		GUN_EV_WAIT_TIMEOUT		120
-#define		GUN_EVSE_WAIT_TIMEOUT	60
+#define		GUN_EV_WAIT_TIMEOUT		(120 + 10)
+#define		GUN_EVSE_WAIT_TIMEOUT	(60 + 10)
 #define		GUN_COMP_WAIT_TIMEOUT	10
 #define		GUN_PRECHARGING_TIMEOUT	60
 
@@ -110,6 +111,9 @@
 #define     FORCE_CHARGING_WAIT_EVSE    10              // unit: second
 #define     TRY_RESET_4G_WIFI_TIME      300             // unit: second
 #define     FAST_RESET_4G_WIFI_TIME     60              // unit: second
+#define     ENERAGY_INTERVAL            1               // unit: second
+
+#define     AUTO_START_CHARGING         "AutoStartCharging"
 
 char 	*valid_Internet[2] 	  = {"8.8.8.8", "180.76.76.76"};
 unsigned char mask_table[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
@@ -165,12 +169,12 @@ unsigned char DetectBitValue(unsigned char _byte, unsigned char _bit);
 void SetBitValue(unsigned char *_byte, unsigned char _bit, unsigned char value);
 void ChargingTerminalProcess(byte gunIndex);
 void ChkPrimaryStatus();
-void StartSystemTimeoutDet(unsigned char flag);
-void StopSystemTimeoutDet();
-void StartGunInfoTimeoutDet(unsigned char gunIndex, unsigned char flag);
-void StopGunInfoTimeoutDet(unsigned char gunIndex);
+//void StartSystemTimeoutDet(unsigned char flag);
+//void StopSystemTimeoutDet();
+//void StartGunInfoTimeoutDet(unsigned char gunIndex, unsigned char flag);
+//void StopGunInfoTimeoutDet(unsigned char gunIndex);
 int StoreLogMsg_1(const char *fmt, ...);
-unsigned long GetTimeoutValue(struct timeval _sour_time);
+
 void gpio_set_value(unsigned int gpio, unsigned int value);
 void ChangeGunSelectByIndex(byte sel);
 void ChargingAlarmProcess(byte gunIndex);
@@ -210,21 +214,20 @@ PsuGroupCollectionData          *ShmGroupCollection;
 
 struct ChargingInfoData			*chargingInfo[CONNECTOR_QUANTITY];
 struct ChargingInfoData			*ac_chargingInfo[AC_QUANTITY];
-struct timeb 					startChargingTime[CONNECTOR_QUANTITY];
-struct timeb 					endChargingTime[CONNECTOR_QUANTITY];
 
-struct timeval                  _ConnectorAuthorizing_Time[CONNECTOR_QUANTITY];
-struct timeval                  _ConnectorAuthorizeFail_Time[CONNECTOR_QUANTITY];
-struct timeval                  _DispenserAuthorizing_Time[CONNECTOR_QUANTITY];
-int chargingTime[CONNECTOR_QUANTITY];
-struct timeval                  _DispenserUpgrade_time;
-struct timeval                  _Standby_time;
-struct timeval                  _SystemStatus_Time[CONNECTOR_QUANTITY];
+struct timespec                 _cmdMainPriority_time;
+struct timespec                 _cmdSubPriority_time;
+struct timespec                 _ConnectorAuthorizing_Time[CONNECTOR_QUANTITY];
+struct timespec                 _ConnectorAuthorizeFail_Time[CONNECTOR_QUANTITY];
+struct timespec                 _DispenserAuthorizing_Time[CONNECTOR_QUANTITY];
+struct timespec                 _DispenserUpgrade_time;
+struct timespec                 _Standby_time;
+struct timespec                 _SystemStatus_Time[CONNECTOR_QUANTITY];
 
 unsigned char                   _PsuGroupAvailable[CONNECTOR_QUANTITY];
 
 bool _NeedReset4gWifi;
-struct timeval _4gWifiReset_time;
+struct timespec _4gWifiReset_time;
 
 // for initial index to check EV board type is correct
 byte _gunIndex = 0;
@@ -243,7 +246,7 @@ bool isModelNameMatch = true;
 
 //int rfidFd = -1;
 //char* rfidPortName = "/dev/ttyS2";
-char* fwVersion = "V1.01.00.0000.00";
+char* fwVersion = "V1.02.00.0000.00";
 
 sqlite3 *localDb;
 bool isDb_ready;
@@ -392,14 +395,6 @@ int StoreLogMsg_1(const char *fmt, ...)
 	return rc;
 }
 
-unsigned long GetTimeoutValue(struct timeval _sour_time)
-{
-	struct timeval _end_time;
-	gettimeofday(&_end_time, NULL);
-
-	return 1000000 * (_end_time.tv_sec - _sour_time.tv_sec) + _end_time.tv_usec - _sour_time.tv_usec;
-}
-
 int mystrcmp(unsigned char *p1, unsigned char *p2)
 {
     while(*p1==*p2)
@@ -1356,7 +1351,7 @@ void Check4gWifiReset(void)
         {
             if(!_NeedReset4gWifi)
             {
-                gettimeofday(&_4gWifiReset_time, NULL);
+                GetClockTime(&_4gWifiReset_time);
                 LOG_INFO("Backend Enable But Internet Not Available!");
             }
             _NeedReset4gWifi = true;
@@ -2097,8 +2092,7 @@ bool DisplaySelfTestFailReason()
 
 void SelfTestRun()
 {
-    struct timeval _selfTest_time;
-
+    struct timespec _selfTest_time;
 
 	ShmRelayModuleData[0]->SelfTest_Comp = NO;
 	ShmRelayModuleData[1]->SelfTest_Comp = NO;
@@ -2106,7 +2100,7 @@ void SelfTestRun()
 	ShmPrimaryMcuData->SelfTest_Comp = NO;
 
 	ShmSysConfigAndInfo->SysInfo.SelfTestSeq = _STEST_VERSION;
-	gettimeofday(&_selfTest_time, NULL);
+	GetClockTime(&_selfTest_time);
 
 	while (ShmSysConfigAndInfo->SysInfo.SelfTestSeq != _STEST_COMPLETE)
 	{
@@ -2868,7 +2862,7 @@ void ChkPrimaryStatus()
 	}
 }
 
-struct timeval _AcContactReOpen_Time;
+struct timespec _AcContactReOpen_Time;
 
 void ChkPsuStatus(void)
 {
@@ -2921,7 +2915,7 @@ void PsuFailureResume(void)
         {
             LOG_INFO("Ac Contactor Off By Psu Failure");
             // update _AcContactReOpen_Time
-            gettimeofday(&_AcContactReOpen_Time, NULL);
+            GetClockTime(&_AcContactReOpen_Time);
             ShmChargerInfo->Control.RelayCtrl.bits.AcContactorOffByPsu = YES;
             AcContactorReOpenCount++;
         }
@@ -2934,7 +2928,7 @@ void PsuFailureResume(void)
                     ReleaseEmsOccureByString(0, "042267");
 
                     // update _AcContactReOpen_Time
-                    gettimeofday(&_AcContactReOpen_Time, NULL);
+                    GetClockTime(&_AcContactReOpen_Time);
                     ShmChargerInfo->Control.RelayCtrl.bits.AcContactorOffByPsu = NO;
                     ShmChargerInfo->Control.PsuCtrl.bits.FailureResume = NO;
                     LOG_INFO("Psu Failure Resume");
@@ -2993,7 +2987,7 @@ void StandbyCheck(void)
         else
         {
             ShmChargerInfo->Control.RelayCtrl.bits.StandbyCountdown = YES;
-            gettimeofday(&_Standby_time, NULL);
+            GetClockTime(&_Standby_time);
         }
     }
     else
@@ -3367,7 +3361,7 @@ void ScannerCardProcess()
 {
 }
 
-struct timeval _StartAuthorizing_Time;
+struct timespec _StartAuthorizing_Time;
 
 void PowerCabinetAuthorizingSettingInitial(void)
 {
@@ -3599,7 +3593,7 @@ void PowerCabinetAuthorizeProcess(void)
                 }
 
                 // update start authorizing timeout
-                gettimeofday(&_StartAuthorizing_Time, NULL);
+                GetClockTime(&_StartAuthorizing_Time);
                 ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_Busy;
             }
             break;
@@ -3662,12 +3656,23 @@ void PowerCabinetAuthorizeProcess(void)
                                 if (strcmp((char *)ShmSysConfigAndInfo->SysConfig.LocalWhiteCard[i], (char *)ShmSysConfigAndInfo->SysConfig.UserId) == EQUAL)
                                 {
                                     find = true;
+                                    LOG_INFO("*********** Dispenser %d White Card OK ***********", dispenser + 1);
                                     break;
                                 }
                             }
                         }
 
-                        LOG_INFO("*********** Dispenser %d White Card %s   ***********", dispenser + 1, find ? "OK" : "NG");
+                        if(find == false)
+                        {
+                            if(ShmChargerInfo->AuthInfo.AuthMode.bits.AutoStartEnable &&
+                                strcmp((char *)ShmSysConfigAndInfo->SysConfig.UserId, AUTO_START_CHARGING) == EQUAL)
+                            {
+                                find = true;
+                                LOG_INFO("******** Dispenser %d Auto Start Charging ********", dispenser + 1);
+                            }
+                        }
+
+                        LOG_INFO("*********** Dispenser %d Local Authorization %s ***********", dispenser + 1, find ? "OK" : "NG");
 
                         ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult = find ? _AuthResult_Valid : _AuthResult_Invalid;
                         ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_Done;
@@ -3714,18 +3719,18 @@ void PowerCabinetAuthorizeProcess(void)
                 else if(ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthResult == _AuthResult_Invalid)
                 {
                     // update connector authorizing timeout
-                    gettimeofday(&_ConnectorAuthorizeFail_Time[connector], NULL);
+                    GetClockTime(&_ConnectorAuthorizeFail_Time[connector]);
                 }
             }
             // authorize completed
             ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.AuthorizingCompleted = true;
 
             // update dispenser authorizing timeout
-            gettimeofday(&_DispenserAuthorizing_Time[dispenser], NULL);
+            GetClockTime(&_DispenserAuthorizing_Time[dispenser]);
             ShmSysConfigAndInfo->SysInfo.DispenserInfo.Dispenser[dispenser].AuthStatus = _AuthorizeStatus_End;
 
             // update authorizing completed timeout
-            gettimeofday(&_StartAuthorizing_Time, NULL);
+            GetClockTime(&_StartAuthorizing_Time);
             ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_End;
             break;
         case _AuthorizeStatus_End:
@@ -3737,7 +3742,7 @@ void PowerCabinetAuthorizeProcess(void)
             break;
         default:
             // update authorizing completed timeout
-            gettimeofday(&_StartAuthorizing_Time, NULL);
+            GetClockTime(&_StartAuthorizing_Time);
             ShmSysConfigAndInfo->SysInfo.AuthorizedStatus = _AuthorizeStatus_End;
             break;
     }
@@ -4003,7 +4008,7 @@ BOOL WaitAllDispenserUpgradeCompleted(void)
 {
     BOOL completed = TRUE;
 
-    gettimeofday(&_DispenserUpgrade_time, NULL);
+    GetClockTime(&_DispenserUpgrade_time);
     do
     {
         completed = TRUE;
@@ -4325,7 +4330,7 @@ void CreateRfidFork()
 	}
 }
 */
-
+#if 0
 void StartSystemTimeoutDet(unsigned char flag)
 {
 	if (ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag != flag)
@@ -4360,6 +4365,7 @@ void StopGunInfoTimeoutDet(unsigned char gunIndex)
 		chargingInfo[gunIndex]->TimeoutFlag = Timeout_None;
 	}
 }
+#endif
 
 void TriggerDispenserConnectionTimeoutSetting(void)
 {
@@ -4417,7 +4423,7 @@ void CreateTimeoutFork()
 	timeoutPid = fork();
 	if (timeoutPid > 0)
 	{
-		gettimeofday(&_cmdSubPriority_time, NULL);
+	    GetClockTime(&_cmdSubPriority_time);
 		CheckConnectionTimeout();
 
 		while(true)
@@ -4425,13 +4431,13 @@ void CreateTimeoutFork()
 			if ((GetTimeoutValue(_cmdSubPriority_time) / 1000) > 5000)
 			{
 				CheckConnectionTimeout();
-				gettimeofday(&_cmdSubPriority_time, NULL);
+				GetClockTime(&_cmdSubPriority_time);
 			}
 
 			//printf("Timeout ***********SystemTimeoutFlag = %d, ********\n", ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag);
 			// 系統
-			switch(ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag)
-			{
+//			switch(ShmSysConfigAndInfo->SysInfo.SystemTimeoutFlag)
+//			{
 //				case Timeout_SelftestChk:
 //					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= SELFTEST_TIMEOUT)
 //					{
@@ -4460,85 +4466,85 @@ void CreateTimeoutFork()
 //						StopSystemTimeoutDet();
 //					}
 //					break;
-				case Timeout_WaitPlug:
-					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= _connectionTimeout)
-					{
-						_DetectPlugInTimeout();
-						StopSystemTimeoutDet();
-					}
-					break;
-				case Timeout_ReturnToChargingGunDet:
-				{
-					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= RETURN_TO_CHARGING_PAGE)
-					{
-						DisplayChargingInfo();
-						StopSystemTimeoutDet();
-					}
-				}
-					break;
-				case Timeout_AuthorizingForStop:
-				{
-					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_STOP_TIMEOUT)
-					{
-						strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-						ClearAuthorizedFlag();
-						StopSystemTimeoutDet();
-					}
-				}
-					break;
-			}
+//				case Timeout_WaitPlug:
+//					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= _connectionTimeout)
+//					{
+//						_DetectPlugInTimeout();
+//						StopSystemTimeoutDet();
+//					}
+//					break;
+//				case Timeout_ReturnToChargingGunDet:
+//				{
+//					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= RETURN_TO_CHARGING_PAGE)
+//					{
+//						DisplayChargingInfo();
+//						StopSystemTimeoutDet();
+//					}
+//				}
+//					break;
+//				case Timeout_AuthorizingForStop:
+//				{
+//					if (GetTimeoutValue(ShmSysConfigAndInfo->SysInfo.SystemTimeoutTimer) / uSEC_VAL >= AUTHORIZE_STOP_TIMEOUT)
+//					{
+//						strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
+//						ClearAuthorizedFlag();
+//						StopSystemTimeoutDet();
+//					}
+//				}
+//					break;
+//			}
 			// 各槍
-			for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
-			{
+//			for (byte gun_index = 0; gun_index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; gun_index++)
+//			{
 				//printf("Timeout ***********TimeoutFlag = %d, ********\n", chargingInfo[gun_index]->TimeoutFlag);
-				switch(chargingInfo[gun_index]->TimeoutFlag)
-				{
-					case Timeout_Preparing:
-					{
-						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_PREPARE_TIMEOUT)
-						{
-							_PrepareTimeout(gun_index);
-							StopGunInfoTimeoutDet(gun_index);
-						}
-					}
-						break;
-					case Timeout_EvChargingDet:
-					{
-						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_EV_WAIT_TIMEOUT)
-						{
-							_DetectEvChargingEnableTimeout(gun_index);
-							StopGunInfoTimeoutDet(gun_index);
-						}
-					}
-						break;
-					case Timeout_EvseChargingDet:
-					{
-						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_EVSE_WAIT_TIMEOUT)
-						{
-							_DetectEvseChargingEnableTimeout(gun_index);
-							StopGunInfoTimeoutDet(gun_index);
-						}
-					}
-						break;
-					case Timeout_EvseCompleteDet:
-					{
-						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_COMP_WAIT_TIMEOUT)
-						{
-							StopGunInfoTimeoutDet(gun_index);
-						}
-					}
-						break;
-					case Timeout_ForCcsPrechargeDet:
-					{
-						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_PRECHARGING_TIMEOUT)
-						{
-							_CcsPrechargeTimeout(gun_index);
-							StopGunInfoTimeoutDet(gun_index);
-						}
-					}
-						break;
-				}
-			}
+//				switch(chargingInfo[gun_index]->TimeoutFlag)
+//				{
+//					case Timeout_Preparing:
+//					{
+//						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_PREPARE_TIMEOUT)
+//						{
+//							_PrepareTimeout(gun_index);
+//							StopGunInfoTimeoutDet(gun_index);
+//						}
+//					}
+//						break;
+//					case Timeout_EvChargingDet:
+//					{
+//						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_EV_WAIT_TIMEOUT)
+//						{
+//							_DetectEvChargingEnableTimeout(gun_index);
+//							StopGunInfoTimeoutDet(gun_index);
+//						}
+//					}
+//						break;
+//					case Timeout_EvseChargingDet:
+//					{
+//						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_EVSE_WAIT_TIMEOUT)
+//						{
+//							_DetectEvseChargingEnableTimeout(gun_index);
+//							StopGunInfoTimeoutDet(gun_index);
+//						}
+//					}
+//						break;
+//					case Timeout_EvseCompleteDet:
+//					{
+//						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_COMP_WAIT_TIMEOUT)
+//						{
+//							StopGunInfoTimeoutDet(gun_index);
+//						}
+//					}
+//						break;
+//					case Timeout_ForCcsPrechargeDet:
+//					{
+//						if (GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) / uSEC_VAL >= GUN_PRECHARGING_TIMEOUT)
+//						{
+//							_CcsPrechargeTimeout(gun_index);
+//							StopGunInfoTimeoutDet(gun_index);
+//						}
+//					}
+//						break;
+//				}
+//			}
 			sleep(1);
 		}
 	}
@@ -4656,40 +4662,39 @@ void ExecuteWriteWiringInfo(void)
     int result = StoreUsrConfigData(&config);
     if(result != 1)
     {
-        LOG_INFO("Write Wiring Info NG");
+        LOG_INFO("Store User Config NG");
     }
     else
     {
-        LOG_INFO("WriteWiringInfo OK");
+        LOG_INFO("Store User Config OK");
     }
 }
 
-struct timeval _WiringInfo_time;
+struct timespec _WiringInfo_time;
 int CheckWiringInfoUpdate(void)
 {
-    if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.WiringInfoChanged)
+    if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged)
     {
-        ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.WiringInfoChanged = false;
-        LOG_INFO("Wiring Info Changed");
+        ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.FlashConfigChanged = false;
+        LOG_INFO("Flash Config Changed");
 
-        gettimeofday(&_WiringInfo_time, NULL);
-        ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteWiringInfo = true;
+        GetClockTime(&_WiringInfo_time);
+        ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteFlash = true;
     }
 
-    if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteWiringInfo)
+    if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteFlash)
     {
         // 30s for reboot request timeout
         if((GetTimeoutValue(_WiringInfo_time) / uSEC_VAL) >= WIRING_INFO_DELAY ||
             ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.CleanWiringInfo)
         {
-            ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteWiringInfo = false;
-            LOG_INFO("Start Wirte Wiring Info To Flash");
+            ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.EnableWriteFlash = false;
+            LOG_INFO("Start Write To Flash");
 
             pid_t writePid = fork();
             if(writePid == 0)
             {
                 ExecuteWriteWiringInfo();
-                LOG_INFO("Wirte Wiring Info OK");
 
                 if(ShmSysConfigAndInfo->SysInfo.CabinetSetting.bits.CleanWiringInfo)
                 {
@@ -4699,7 +4704,7 @@ int CheckWiringInfoUpdate(void)
                 }
                 return NO;
             }
-            LOG_INFO("Clean Wirte Wiring Info Flag");
+            LOG_INFO("Clean Write Flahs Flag");
         }
     }
 
@@ -4756,7 +4761,7 @@ int isReservationExpired(unsigned char gun_index)
 	return result;
 }
 
-struct timeval _Reboot_time;
+struct timespec _Reboot_time;
 
 void TriggerDispenserHardwareReboot(void)
 {
@@ -4777,7 +4782,7 @@ void TriggerDispenserHardwareReboot(void)
 
     if(trigger)
     {
-        gettimeofday(&_Reboot_time, NULL);
+        GetClockTime(&_Reboot_time);
         LOG_INFO("********** Trigger Dispenser Hardware Reboot **********");
     }
 }
@@ -4807,7 +4812,7 @@ BOOL IsDispenserHardwareRebootResponsed(void)
     return response_ok;
 }
 
-struct timeval _Reset_time;
+struct timespec _Reset_time;
 
 void TriggerDispenserSoftwareReset(void)
 {
@@ -4828,7 +4833,7 @@ void TriggerDispenserSoftwareReset(void)
 
     if(trigger)
     {
-        gettimeofday(&_Reset_time, NULL);
+        GetClockTime(&_Reset_time);
         LOG_INFO("********** Trigger Dispenser Software Reset **********");
     }
 }
@@ -4994,7 +4999,7 @@ void RunningFinalCostHandler(void)
                 ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost = TotalCost;
                 ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance = AccountBalance;
 
-                memset(&ShmOCPP16Data->Cost.RunningCost[i], 0x00, sizeof(struct StrcutRunningFinalCost));
+                memset(&ShmOCPP16Data->Cost.RunningCost[i], 0x00, sizeof(struct StrcutRunningCost));
             }
 
             if(strlen((char *)ShmOCPP16Data->Cost.FinalCost[i].description) > 0)
@@ -5021,13 +5026,13 @@ void RunningFinalCostHandler(void)
                 ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].TotalCost = TotalCost;
                 ShmSysConfigAndInfo->SysInfo.ConnectorInfo[i].AccountBalance = AccountBalance;
 
-                memset(&ShmOCPP16Data->Cost.FinalCost[i], 0x00, sizeof(struct StrcutRunningFinalCost));
+                memset(&ShmOCPP16Data->Cost.FinalCost[i], 0x00, sizeof(struct StrcutFinalCost));
             }
         }
     }
 }
 
-struct timeval _Cost_Price_time;
+struct timespec _Cost_Price_time;
 char MyDefaultPriceString[128];
 struct StrcutSetUserPrice MyUserPrice;
 char MyConnectorRunningCostString[CONNECTOR_QUANTITY][128];
@@ -5038,7 +5043,7 @@ void CheckOcppCostAndPrice(void)
     // 5s for reboot request timeout
     if((GetTimeoutValue(_Cost_Price_time) / uSEC_VAL) >= OCPP_COST_REQ_INTERVAL)
     {
-        gettimeofday(&_Cost_Price_time, NULL);
+        GetClockTime(&_Cost_Price_time);
 
         if(strcmp(MyDefaultPriceString, (char *)ShmOCPP16Data->ConfigurationTable.CoreProfile[DefaultPrice].ItemData) != EQUAL)
         {
@@ -5987,14 +5992,10 @@ void CheckSmartChargeProfile(byte _index)
 
 void TheEndCharging(byte gun_index)
 {
-    ftime(&endChargingTime[gun_index]);
-    if (chargingInfo[gun_index]->PresentChargedDuration != 0)
-            chargingInfo[gun_index]->PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index]);
-
     chargingInfo[gun_index]->isRemoteStart = NO;
 
-    StopGunInfoTimeoutDet(gun_index);
-    StartGunInfoTimeoutDet(gun_index, Timeout_EvseCompleteDet);
+    //StopGunInfoTimeoutDet(gun_index);
+    //StartGunInfoTimeoutDet(gun_index, Timeout_EvseCompleteDet);
     ChangeStartOrStopDateTime(NO, gun_index);
     //DB_Insert_Record(localDb, gun_index);
 }
@@ -6147,10 +6148,10 @@ void SetLedIndicationStatus(unsigned char connector, unsigned char indication)
     }
 }
 
-struct timeval _standardIndication_time;
+struct timespec _standardIndication_time;
 unsigned char _standardLedStatus, _preStandardLedStatus;
 unsigned char _e4youLedStatus[2], _preE4youLedStatus[2];
-struct timeval _e4youIndication_time[2];
+struct timespec _e4youIndication_time[2];
 
 void LedIndicationProcess(void)
 {
@@ -6176,7 +6177,7 @@ void LedIndicationProcess(void)
                     _preStandardLedStatus = _standardLedStatus;
 
                     // reset led status & indication time
-                    gettimeofday(&_standardIndication_time, NULL);
+                    GetClockTime(&_standardIndication_time);
                     SetLedIndicationStatus(0, _LED_INDICATION_OFF);
                 }
 
@@ -6184,7 +6185,7 @@ void LedIndicationProcess(void)
                 {
                     SetLedIndicationStatus(0, _LED_INDICATION_GREEN_TOGGLE);
                     SetLedIndicationStatus(0, _LED_INDICATION_RED_TOGGLE);
-                    gettimeofday(&_standardIndication_time, NULL);
+                    GetClockTime(&_standardIndication_time);
                 }
             }
             else
@@ -6223,13 +6224,13 @@ void LedIndicationProcess(void)
                     _preE4youLedStatus[i] = _e4youLedStatus[i];
 
                     // reset led status & indication time
-                    gettimeofday(&_e4youIndication_time[i], NULL);
+                    GetClockTime(&_e4youIndication_time[i]);
                     SetLedIndicationStatus(i, _LED_INDICATION_OFF);
                 }
 
                 if((GetTimeoutValue(_e4youIndication_time[i]) / mSEC_VAL) >= INDICATION_BLINK_INTERVAL)
                 {
-                    gettimeofday(&_e4youIndication_time[i], NULL);
+                    GetClockTime(&_e4youIndication_time[i]);
                     SetLedIndicationStatus(i, _LED_INDICATION_GREEN_TOGGLE);
                     SetLedIndicationStatus(i, _LED_INDICATION_RED_TOGGLE);
                 }
@@ -6255,13 +6256,13 @@ void LedIndicationProcess(void)
                     _preE4youLedStatus[i] = _e4youLedStatus[i];
 
                     // reset led status & indication time
-                    gettimeofday(&_e4youIndication_time[i], NULL);
+                    GetClockTime(&_e4youIndication_time[i]);
                     SetLedIndicationStatus(i, _LED_INDICATION_OFF);
                 }
 
                 if((GetTimeoutValue(_e4youIndication_time[i]) / mSEC_VAL) >= E4YOU_BLINK_INTERVAL)
                 {
-                    gettimeofday(&_e4youIndication_time[i], NULL);
+                    GetClockTime(&_e4youIndication_time[i]);
                     SetLedIndicationStatus(i, _LED_INDICATION_GREEN_TOGGLE);
                 }
             }
@@ -6491,7 +6492,7 @@ int main(void)
 
 	// Main loop
 	LOG_INFO("****************************Main Loop********************************** \n");
-	gettimeofday(&_cmdMainPriority_time, NULL);
+	GetClockTime(&_cmdMainPriority_time);
 	for (;;)
 	{
 		CheckOcppStatus();
@@ -6525,7 +6526,7 @@ int main(void)
 		// 當 AC 沒有搭上時,清除一些錯誤碼
 		ClearAlarmCodeWhenAcOff();
 
-		if ((GetTimeoutValue(_cmdMainPriority_time) / 1000) > 5000)
+		if ((GetTimeoutValue(_cmdMainPriority_time) / uSEC_VAL) > MAIN_PRIORITY_INTERVAL)
 		{
 			CheckTask();
 			for (byte _index = 0; _index < ShmSysConfigAndInfo->SysConfig.TotalConnectorCount; _index++)
@@ -6534,7 +6535,7 @@ int main(void)
 					CheckSmartChargeProfile(_index);
 			}
 
-			gettimeofday(&_cmdMainPriority_time, NULL);
+			GetClockTime(&_cmdMainPriority_time);
 		}
 
         //LedIndicationProcess();
@@ -6579,7 +6580,6 @@ int main(void)
                             LOG_INFO("==================        S_IDLE (%x)        ================== \n", gun_index + 1);
                             chargingInfo[gun_index]->PresentChargedDuration = 0;
                             chargingInfo[gun_index]->RemainChargingDuration = 0;
-                            chargingTime[gun_index] = 0;
                             strcpy((char *)chargingInfo[gun_index]->StartDateTime, "");
                             strcpy((char *)chargingInfo[gun_index]->StopDateTime, "");
                             strcpy((char *)chargingInfo[gun_index]->StartUserId, "");
@@ -6619,8 +6619,8 @@ int main(void)
                             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.FaultStatusRequest = false;
                             memset(chargingInfo[gun_index]->ConnectorAlarmCode, 0x00, sizeof(chargingInfo[gun_index]->ConnectorAlarmCode));
 
-                            memset(&ShmOCPP16Data->Cost.RunningCost[gun_index], 0x00, sizeof(struct StrcutRunningFinalCost));
-                            memset(&ShmOCPP16Data->Cost.FinalCost[gun_index], 0x00, sizeof(struct StrcutRunningFinalCost));
+                            memset(&ShmOCPP16Data->Cost.RunningCost[gun_index], 0x00, sizeof(struct StrcutRunningCost));
+                            memset(&ShmOCPP16Data->Cost.FinalCost[gun_index], 0x00, sizeof(struct StrcutFinalCost));
                             chargingInfo[gun_index]->PresentChargedEnergy = 0;
                             chargingInfo[gun_index]->PresentChargingPower = 0;
 
@@ -6759,10 +6759,10 @@ int main(void)
                         ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
                         if (ShmSysConfigAndInfo->SysInfo.OrderCharging != NO_DEFINE)
                             ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
-                        StopSystemTimeoutDet();
+                        //StopSystemTimeoutDet();
                         ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = false;
                         SetAcContactor(ON);
-                        gettimeofday(&_ConnectorAuthorizing_Time[gun_index], NULL);
+                        GetClockTime(&_ConnectorAuthorizing_Time[gun_index]);
                     }
 
                     if(GetTimeoutValue(_ConnectorAuthorizing_Time[gun_index]) / uSEC_VAL >= FORCE_BALANCE_TIME)
@@ -6776,7 +6776,7 @@ int main(void)
                         {
                             // sync with dispenser
                             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.RemoteStartConfirm = false;
-                            gettimeofday(&_ConnectorAuthorizing_Time[gun_index], NULL);
+                            GetClockTime(&_ConnectorAuthorizing_Time[gun_index]);
                             LOG_INFO("Sync with Connector %d through remote start", gun_index + 1);
                             FouceAnnounceAccountBalance(gun_index);
                         }
@@ -6788,7 +6788,7 @@ int main(void)
                         {
                             // sync with dispenser
                             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.SwipeRfidConfirm = false;
-                            gettimeofday(&_ConnectorAuthorizing_Time[gun_index], NULL);
+                            GetClockTime(&_ConnectorAuthorizing_Time[gun_index]);
                             LOG_INFO("Sync with Connector %d through swipe rfid", gun_index + 1);
                         }
                     }
@@ -6835,7 +6835,7 @@ int main(void)
 						ShmSysConfigAndInfo->SysInfo.SystemPage = _LCM_NONE;
 						if (ShmSysConfigAndInfo->SysInfo.OrderCharging != NO_DEFINE)
 							ShmSysConfigAndInfo->SysInfo.OrderCharging = NO_DEFINE;
-						StopSystemTimeoutDet();
+						//StopSystemTimeoutDet();
 						ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable = false;
 						ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxTotalChargingCurrent = ShmSysConfigAndInfo->SysConfig.MaxChargingCurrent * 10;
 						ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxTotalChargingPower = ShmSysConfigAndInfo->SysConfig.MaxChargingPower * 10;
@@ -6848,7 +6848,7 @@ int main(void)
                             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputEnergy,
                             ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].MaxOutputDuration);
 						SetAcContactor(ON);
-						gettimeofday(&_SystemStatus_Time[gun_index], NULL);
+						GetClockTime(&_SystemStatus_Time[gun_index]);
 					}
 
                     time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
@@ -6876,8 +6876,8 @@ int main(void)
 					if (isModeChange(gun_index))
 					{
 					    LOG_INFO("==================      S_REASSIGN (%x)      ================== \n", gun_index + 1);
-						gettimeofday(&_toAverage_time, NULL);
-						gettimeofday(&_SystemStatus_Time[gun_index], NULL);
+						//gettimeofday(&_toAverage_time, NULL);
+						GetClockTime(&_SystemStatus_Time[gun_index]);
 					}
 
                     time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
@@ -6898,10 +6898,10 @@ int main(void)
 					if (isModeChange(gun_index))
 					{
 					    LOG_INFO("==================     S_PREPARNING (%x)     ================== \n", gun_index + 1);
-						StopGunInfoTimeoutDet(gun_index);
-						StartGunInfoTimeoutDet(gun_index, Timeout_Preparing);
+						//StopGunInfoTimeoutDet(gun_index);
+						//StartGunInfoTimeoutDet(gun_index, Timeout_Preparing);
 						SetAcContactor(ON);
-						gettimeofday(&_SystemStatus_Time[gun_index], NULL);
+						GetClockTime(&_SystemStatus_Time[gun_index]);
 					}
 
 					time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
@@ -6932,14 +6932,23 @@ int main(void)
                         }
 					    ChargingTerminalProcess(gun_index);
 					}
-					/*
-					if(time >= GUN_PREPARE_TIMEOUT)
+
+					if(time > GUN_PREPARE_TIMEOUT)
 					{
 					    LOG_INFO("********** Gun %d PrepareTimeout **********", gun_index + 1);
 					    ShmStatusCodeData->AlarmCode.AlarmEvents.bits.PsuNoResource = YES;
-					    ChargingTerminalProcess(gun_index);
+
+                        if(strncmp((char *)chargingInfo[gun_index]->ConnectorAlarmCode, "", 6) == EQUAL)
+                        {
+                            memcpy(chargingInfo[gun_index]->ConnectorAlarmCode, "012279", 6);
+                            LOG_INFO("Gun %d No Psu Resource", gun_index + 1);
+                        }
+					    if (strcmp((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "") == EQUAL)
+                        {
+                            strcpy((char *)ShmOCPP16Data->StopTransaction[gun_index].StopReason, "Local");
+                        }
+                        ChargingAlarmProcess(gun_index);
 					}
-					*/
 				}
 					break;
 				case S_PREPARING_FOR_EV: // 等待車端的通訊 (EV 小板),待車端回報後,開始樁端的測試
@@ -6948,11 +6957,13 @@ int main(void)
 					{
 					    LOG_INFO("==================  S_PREPARING_FOR_EV (%x)  ================== \n", gun_index + 1);
 						//strcpy((char *)ShmSysConfigAndInfo->SysConfig.UserId, "");
-						StopGunInfoTimeoutDet(gun_index);
-						StartGunInfoTimeoutDet(gun_index, Timeout_EvChargingDet);
-						gettimeofday(&_SystemStatus_Time[gun_index], NULL);
+						//StopGunInfoTimeoutDet(gun_index);
+						//StartGunInfoTimeoutDet(gun_index, Timeout_EvChargingDet);
+						GetClockTime(&_SystemStatus_Time[gun_index]);
 					}
 
+					time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
+
 					if(ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PermissionRequest)
 					{
 					    setChargerMode(gun_index, MODE_PREPARE_FOR_EVSE);
@@ -6984,6 +6995,12 @@ int main(void)
                         }
                         ChargingTerminalProcess(gun_index);
                     }
+
+					if(time >= GUN_EV_WAIT_TIMEOUT)
+					{
+					    LOG_INFO("********** Gun %d Wait Dispenser Timeout **********", gun_index + 1);
+					    ChargingTerminalProcess(gun_index);
+					}
 				}
 					break;
 				case S_PREPARING_FOR_EVSE: // 等待 RB 通訊及測試,並將狀態回報, CSU 確認 Pass 後,開始進入充電
@@ -6991,11 +7008,13 @@ int main(void)
 					if (isModeChange(gun_index))
 					{
 					    LOG_INFO("================== S_PREPARING_FOR_EVSE (%x) ================== \n", gun_index + 1);
-						StopGunInfoTimeoutDet(gun_index);
-						StartGunInfoTimeoutDet(gun_index, Timeout_EvseChargingDet);
-						gettimeofday(&_SystemStatus_Time[gun_index], NULL);
+						//StopGunInfoTimeoutDet(gun_index);
+						//StartGunInfoTimeoutDet(gun_index, Timeout_EvseChargingDet);
+						GetClockTime(&_SystemStatus_Time[gun_index]);
 					}
 
+					time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
+
                     // only for test & debug purpose
                     if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
                     {
@@ -7017,8 +7036,6 @@ int main(void)
                     // only for test & debug purpose
                     else if(ShmChargerInfo->Control.FCharging[gun_index].FCtrl.bits.EnableForceCharging)
                     {
-                        time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
-
                         if(time >= FORCE_CHARGING_WAIT_EVSE)
                         {
                             LOG_INFO("Gun %d [Charging Simulation] S_PREPARING_FOR_EVSE OK", gun_index + 1);
@@ -7046,6 +7063,12 @@ int main(void)
                         }
                         ChargingTerminalProcess(gun_index);
                     }
+
+					if(time >= GUN_EVSE_WAIT_TIMEOUT)
+					{
+					    LOG_INFO("********** Gun %d GFD timeout **********", gun_index + 1);
+                        ChargingTerminalProcess(gun_index);
+					}
 				}
 					break;
 				case S_CHARGING: // 剛進入充電狀態,等待 EV 小板要求的輸出電流後開始輸出
@@ -7053,8 +7076,9 @@ int main(void)
 					if (isModeChange(gun_index))
 					{
 					    LOG_INFO("==================      S_CHARGING (%x)      ================== \n", gun_index + 1);
-						StopGunInfoTimeoutDet(gun_index);
-						ftime(&startChargingTime[gun_index]);
+						//StopGunInfoTimeoutDet(gun_index);
+						GetClockTime(&_SystemStatus_Time[gun_index]);
+						chargingInfo[gun_index]->PresentChargedDuration = 0;
 						ChangeStartOrStopDateTime(YES, gun_index);
 						OcppStartTransation(gun_index);
 					}
@@ -7073,33 +7097,24 @@ int main(void)
                         chargingInfo[gun_index]->EvBatterytargetCurrent = current;
                     }
 
-					ftime(&endChargingTime[gun_index]);
-					chargingInfo[gun_index]->PresentChargedDuration = DiffTimeb(startChargingTime[gun_index], endChargingTime[gun_index]);
+                    time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
 
                     // 計算 Power
                     //chargingInfo[gun_index]->PresentChargingPower = ((float)((chargingInfo[gun_index]->PresentChargingVoltage) * (chargingInfo[gun_index]->PresentChargingCurrent)) / 1000);
                     chargingInfo[gun_index]->PresentChargingPower = (((float)((ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingVoltage) * (ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].RemoteChargingCurrent))) / 1000 / 100);
 
-                    if (chargingTime[gun_index] == 0 || chargingTime[gun_index] > chargingInfo[gun_index]->PresentChargedDuration)
+                    if(time >= (chargingInfo[gun_index]->PresentChargedDuration + ENERAGY_INTERVAL))
                     {
-                        chargingTime[gun_index] = chargingInfo[gun_index]->PresentChargedDuration;
-                    }
-                    else
-                    {
-                        int passTime = chargingInfo[gun_index]->PresentChargedDuration - chargingTime[gun_index];
+                        chargingInfo[gun_index]->PresentChargedDuration++;
 
-                        if(passTime > 0)
+                        float changingPow = (chargingInfo[gun_index]->PresentChargingPower) / 3600;
+                        if (ShmSysConfigAndInfo->SysConfig.BillingData.isBilling)
                         {
-                            float changingPow = (chargingInfo[gun_index]->PresentChargingPower) * passTime / 3600;
-                            if (ShmSysConfigAndInfo->SysConfig.BillingData.isBilling)
-                            {
-                                chargingInfo[gun_index]->ChargingFee += changingPow * ShmSysConfigAndInfo->SysConfig.BillingData.Cur_fee;
-                            }
-
-                            chargingInfo[gun_index]->PresentChargedEnergy += changingPow;
-                            chargingInfo[gun_index]->PowerConsumption += changingPow;
-                            chargingTime[gun_index] = chargingInfo[gun_index]->PresentChargedDuration;
+                            chargingInfo[gun_index]->ChargingFee += changingPow * ShmSysConfigAndInfo->SysConfig.BillingData.Cur_fee;
                         }
+
+                        chargingInfo[gun_index]->PresentChargedEnergy += changingPow;
+                        chargingInfo[gun_index]->PowerConsumption += changingPow;
                     }
 
 					if (isEvBoardStopChargeFlag(gun_index))
@@ -7164,12 +7179,15 @@ int main(void)
                             LOG_INFO("==================    S_TERMINATING (%x)     ================== \n", gun_index + 1);
                         }
 
-						StopGunInfoTimeoutDet(gun_index);
+						//StopGunInfoTimeoutDet(gun_index);
+						GetClockTime(&_SystemStatus_Time[gun_index]);
 					}
 
+					time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
+
                     if (chargingInfo[gun_index]->SystemStatus == S_ALARM)
                     {
-                        if(GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 10000000)
+                        if(time >= GUN_COMP_WAIT_TIMEOUT)
                         {
                             if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
                             {
@@ -7201,9 +7219,12 @@ int main(void)
 						}
 
 						TheEndCharging(gun_index);
+						GetClockTime(&_SystemStatus_Time[gun_index]);
 					}
 
-					if(GetTimeoutValue(chargingInfo[gun_index]->TimeoutTimer) >= 10000000)
+					time = GetTimeoutValue(_SystemStatus_Time[gun_index]) / uSEC_VAL;
+
+					if(time >= GUN_COMP_WAIT_TIMEOUT)
 					{
 					    if(!ShmSysConfigAndInfo->SysInfo.ConnectorInfo[gun_index].Parameter.bits.PsuReleasable)
 					    {
@@ -7224,8 +7245,8 @@ int main(void)
 					if (isModeChange(gun_index))
 					{
 						LOG_INFO("CCS Precharge Processing 1....................%x \n", gun_index);
-						StopGunInfoTimeoutDet(gun_index);
-						StartGunInfoTimeoutDet(gun_index, Timeout_ForCcsPrechargeDet);
+						//StopGunInfoTimeoutDet(gun_index);
+						//StartGunInfoTimeoutDet(gun_index, Timeout_ForCcsPrechargeDet);
 					}
 					break;
 

+ 3 - 3
EVSE/Projects/DO360/Apps/timeout.h

@@ -53,10 +53,10 @@ enum Timeout_flag
 };
 
 // for timeout fork
-struct timeval _cmdSubPriority_time;
+
 unsigned short _connectionTimeout;
 
 // for main
-struct timeval _cmdMainPriority_time;
-struct timeval _toAverage_time;
+//struct timeval _cmdMainPriority_time;
+//struct timeval _toAverage_time;
 #endif /* TIMEOUT_H_ */

BIN
EVSE/Projects/DO360/Images/FactoryDefaultConfig.bin


BIN
EVSE/Projects/DO360/Images/ramdisk.gz


+ 79 - 79
EVSE/Projects/define.h

@@ -293,9 +293,9 @@ enum CoreProfile {
      DefaultPrice,
      CustomDisplayCostAndPrice,
      CustomIdleFeeAfterStop,
-	 TimeOffset,
-	 NextTimeOffsetTransitionDateTime,
-	 TimeOffsetNextTransition,
+     TimeOffset,
+     NextTimeOffsetTransitionDateTime,
+     TimeOffsetNextTransition,
      ConfigurationVersion,
 	 _CoreProfile_CNT
 };
@@ -383,9 +383,9 @@ struct LED
 
 struct LCD_OVERRIDE
 {
-	unsigned char			page_index;					// LCD override page index
-	unsigned char			duration;					// LCD override duration
-	unsigned char			isOverideReq:1;				// LCD override request
+    unsigned char           page_index;                 // LCD override page index
+    unsigned char           duration;                   // LCD override duration
+    unsigned char           isOverideReq:1;             // LCD override request
 };
 
 struct Schedule
@@ -403,14 +403,14 @@ struct Schedule
 
 struct TTIA
 {
-	unsigned char	server_addr[512];					// Target server address
-	unsigned int	server_port;						// Target server port
-	unsigned int	busVenderId;						// Bus vender id, 0~65535
-	unsigned char	EquipmentProvider[16];				// EVSE vender max 15 bytes
-	unsigned char	TransportationCompanyNo;			// Data provider company number
-	unsigned char 	ChargeBoxId;						// 1 byte
-	unsigned char	evseStation[16];					// UTF-8 15 bytes, Chinese 5 words
-	unsigned char	isEnableTTIA:1;						// TTIA function enable
+    unsigned char   server_addr[512];                   // Target server address
+    unsigned int    server_port;                        // Target server port
+    unsigned int    busVenderId;                        // Bus vender id, 0~65535
+    unsigned char   EquipmentProvider[16];              // EVSE vender max 15 bytes
+    unsigned char   TransportationCompanyNo;            // Data provider company number
+    unsigned char   ChargeBoxId;                        // 1 byte
+    unsigned char   evseStation[16];                    // UTF-8 15 bytes, Chinese 5 words
+    unsigned char   isEnableTTIA:1;                     // TTIA function enable
 };
 
 struct LocalSharingInfo
@@ -442,22 +442,22 @@ typedef struct
 
 typedef struct
 {
-	unsigned int isCalibratedVaGain:1;					// Voltage phase a gain is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedVbGain:1;					// Voltage phase b gain is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedVcGain:1;					// Voltage phase c gain is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedVaOffset:1;				// Voltage phase a offset is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedVbOffset:1;				// Voltage phase b offset is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedVcOffset:1;				// Voltage phase c offset is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedCaGain:1;					// Current phase a gain is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedCbGain:1;					// Current phase b gain is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedCcGain:1;					// Current phase c gain is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedCaOffset:1;				// Current phase a offset is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedCbOffset:1;				// Current phase b offset is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedCcOffset:1;				// Current phase c offset is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedPa:1;						// Phase angle a is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedPb:1;						// Phase angle b gain is calibrated, 0: default	1: Calibrated
-	unsigned int isCalibratedPc:1;						// Phase angle c gain is calibrated, 0: default	1: Calibrated
-	unsigned int :1;
+    unsigned int isCalibratedVaGain:1;                  // Voltage phase a gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedVbGain:1;                  // Voltage phase b gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedVcGain:1;                  // Voltage phase c gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedVaOffset:1;                // Voltage phase a offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedVbOffset:1;                // Voltage phase b offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedVcOffset:1;                // Voltage phase c offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedCaGain:1;                  // Current phase a gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedCbGain:1;                  // Current phase b gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedCcGain:1;                  // Current phase c gain is calibrated, 0: default   1: Calibrated
+    unsigned int isCalibratedCaOffset:1;                // Current phase a offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedCbOffset:1;                // Current phase b offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedCcOffset:1;                // Current phase c offset is calibrated, 0: default 1: Calibrated
+    unsigned int isCalibratedPa:1;                      // Phase angle a is calibrated, 0: default          1: Calibrated
+    unsigned int isCalibratedPb:1;                      // Phase angle b gain is calibrated, 0: default     1: Calibrated
+    unsigned int isCalibratedPc:1;                      // Phase angle c gain is calibrated, 0: default     1: Calibrated
+    unsigned int :1;
 }MeterIcCalibration;
 
 struct SysConfigData
@@ -515,16 +515,16 @@ struct SysConfigData
 	unsigned char 			OcppServerURL[512];			//http: non-secure OCPP 1.5-S, https: secure OCPP 1.5-S, ws: non-secure OCPP 1.6-J, wss: secure OCPP 1.6-J"
 	unsigned char 			ChargeBoxId[128];
 	unsigned char			chargePointVendor[20];		//the Vendor of the ChargePoint
-	unsigned char			OcppSecurityProfile;		//OCPP security profile 0~3
-	unsigned char			OcppSecurityPassword[41];	//OCPP AuthorizationKey for security profile
+    unsigned char           OcppSecurityProfile;        //OCPP security profile 0~3
+    unsigned char           OcppSecurityPassword[41];   //OCPP AuthorizationKey for security profile
 	unsigned int 			Checksum;					//4 bytes checksum
 	struct LED				LedInfo;					// LED configuration info
 	unsigned char			ShowInformation;
 	unsigned char           isReqFirstUpgrade;          //EVSE is request first upgrade from PH server
 	unsigned char           isEnableLocalPowerSharging; //0: Disable power sharing  1: Enable power sharing
 	unsigned char           StopChargingByButton;       //0: Disable  1: Enable
-	struct LCD_OVERRIDE		LcdOveride;					// LCD override info
-	struct TTIA				TTIA_Info;					// TTIA configuration struct
+    struct LCD_OVERRIDE     LcdOveride;                 // LCD override info
+    struct TTIA             TTIA_Info;                  // TTIA configuration struct
 
     /************PowerCabinet************/
     WiringInfoData          WiringInfo;
@@ -572,7 +572,7 @@ struct ChargingInfoData
 	float					ChargingFee;
 	// Connector Temp
 	unsigned char 		ConnectorTemp;			//0x00: -60¢XC  ~  0xFE: 194
-	//Chiller Temp
+    //Chiller Temp
     unsigned char       ChillerTemp;            //0x00: -60¢XC  ~  0xFE: 194
 	// Charging Status
 	unsigned char 		GroundFaultStatus;		// for GFD result => 0x00 : None, 0x01 : Can Start Charging, 0x02 : Stop Charging
@@ -616,11 +616,11 @@ struct ChargingInfoData
 	int 				EvBatteryStartSoc;				// 0~100%
 	unsigned char 		NormalStopChargeFlag;			// for EV board
 	ChargingStop        ChargingStopFlag;
-	char 				ReservedStartFlag;
-	float 				ConnectorMaxVoltage;			// 0~6553.5 volt
-	float 				ConnectorMaxCurrent;			// 0~6553.5 volt
-	unsigned char 		ModelType;
-	MeterIcCalibration  meterIcCalInfo;
+    char                ReservedStartFlag;
+    float               ConnectorMaxVoltage;            // 0~6553.5 volt
+    float               ConnectorMaxCurrent;            // 0~6553.5 volt
+    unsigned char       ModelType;
+    MeterIcCalibration  meterIcCalInfo;
 };
 
 typedef union
@@ -772,7 +772,9 @@ typedef union
         unsigned int  AlarmStopRequest:1;               // 0: no effect,    1: connector alarm stop request                     ( dispenser -> cabinet)
         unsigned int  FaultStatusRequest:1;
         unsigned int  Disconnection:1;
-        unsigned int  res:10;
+        unsigned int  PantographEnable:1;               // 0: disable,      1: enable
+        unsigned int  GfdDetection:1;                   // 0: stop,         1: start
+        unsigned int  res:8;
     }bits;
 }ConnectorParameter;
 
@@ -821,8 +823,8 @@ typedef union
         unsigned int AuthorizingCompleted:1;    // 0: not yet, 1: authorizing completed
         unsigned int DispenserDisconnection:1;  // 0: no connection,  1: dispenser connected
         unsigned int BackendAuthorized:1;       // 0: local authorized, 1: backend authorized
-        unsigned int WiringInfoChanged:1;       // 0: no effect, 1: wiring info has changed
-        unsigned int EnableWriteWiringInfo:1;   // 0: no effect, 1: enable write wiring info after timeout
+        unsigned int FlashConfigChanged:1;      // 0: no effect, 1: flash config has changed
+        unsigned int EnableWriteFlash:1;        // 0: no effect, 1: enable to write flash after timeout
         unsigned int CleanWiringInfo:1;         // 0: no effect, 1: clean wiring info
         unsigned int res:25;
     }bits;
@@ -843,18 +845,16 @@ typedef struct
     unsigned int SoftwareRestart;               // 1: SoftwareRestart, Other value: no effect
 }CabinetMiscCommand;
 
-
 typedef struct DC_METER_INFO
 {
-	double presetVoltage;				// resolution: 1.000v
-	double presentCurrent;			// resolution: 1.000a
-	double presentPower;				// resolution: 1.000kw
-	double totlizeImportEnergy;	// resolution: 1.000kwh
-	double totlizeExportEnergy;	// resolution: 1.000kwh
-	unsigned char LinkStatus;		// 0 = unknow ,1 = link , 2 miss link
+    double presetVoltage;                       // resolution: 1.000v
+    double presentCurrent;                      // resolution: 1.000a
+    double presentPower;                        // resolution: 1.000kw
+    double totlizeImportEnergy;                 // resolution: 1.000kwh
+    double totlizeExportEnergy;                 // resolution: 1.000kwh
+    unsigned char LinkStatus;                   // 0 = unknow ,1 = link , 2 miss link
 }DC_Meter_Info;
 
-
 struct SysInfoData
 {
 	/**************System***************/
@@ -1122,8 +1122,8 @@ struct FaultCodeData
 			unsigned char BleModuleBroken:1;					//bit 2
 			unsigned char RotarySwitchFault:1;					//bit 3 
 			unsigned char CcsLiquidChillerWaterLevelFault:1;    //bit 4
-			unsigned char ChillerTempSensorBroken:1;            //bit 5
-			unsigned char :2;									//bit 6 ~ 7	reserved
+            unsigned char ChillerTempSensorBroken:1;            //bit 5
+            unsigned char :2;                                   //bit 6 ~ 7 reserved
 		}bits;
 	}FaultEvents;
 };
@@ -4310,46 +4310,46 @@ struct StrcutSetUserPrice
 
 struct ChargingPrice
 {
-	float kWhPrice;									// Price per kWh
-	float hourPrice;								// Price per hour of charging
-	float flatFee;									// Flat fee for (part of) charging session
+    float kWhPrice;                                 // Price per kWh
+    float hourPrice;                                // Price per hour of charging
+    float flatFee;                                  // Flat fee for (part of) charging session
 };
 
 struct IdlePrice
 {
-	unsigned int graceMinutes;						// Grace period in minutes before idle time is charged
-	float hourPrice;								// Price per hour while idle
+    unsigned int graceMinutes;                      // Grace period in minutes before idle time is charged
+    float hourPrice;                                // Price per hour while idle
 };
 
 struct NextPeriod
 {
-	unsigned char atTime[36];						// Time when these prices become active
-	struct ChargingPrice chargingPrice;				// Price components while charging
-	struct IdlePrice idlePrice;						// Price components while idle. Optional if no idle fee charged.
+    unsigned char atTime[36];                       // Time when these prices become active
+    struct ChargingPrice chargingPrice;             // Price components while charging
+    struct IdlePrice idlePrice;                     // Price components while idle. Optional if no idle fee charged.
 };
 
 struct Triggers
 {
-	unsigned char atTime[36];						// Time when these prices become active
-	float atEnergykWh;								// Consumed energy amount in kWh upon which a meter value must be sent
-	float atPowerkW;								// Power threshold in kW when meter value must be sent when crossing in downward or upward direction. Can either
-													// be used to trigger a meter value when vehicle stops charging	or when vehicle charges at a high power that requires a
-													// different tariff.
-													// It is recommended to implement a hysteresis around this value to avoid repetitive triggers when the power fluctuates around this level.
+    unsigned char atTime[36];                       // Time when these prices become active
+    float atEnergykWh;                              // Consumed energy amount in kWh upon which a meter value must be sent
+    float atPowerkW;                                // Power threshold in kW when meter value must be sent when crossing in downward or upward direction. Can either
+                                                    // be used to trigger a meter value when vehicle stops charging or when vehicle charges at a high power that requires a
+                                                    // different tariff.
+                                                    // It is recommended to implement a hysteresis around this value to avoid repetitive triggers when the power fluctuates around this level.
 };
 
 struct StrcutRunningCost
 {
-    int             		txId;					// Transaction to which this applies
-    unsigned char   		timestamp[36];			// Timestamp of the meter value upon which this cost is based
-    unsigned int			meterValue;				// Meter value (Wh) upon which this cost is based
-    float					cost;					// Calculated total running cost
-    unsigned char			state[16];				// "Charging" or "Idle"
-    struct ChargingPrice	chargingPrice;			// Price components while charging
-    struct IdlePrice		idlePrice;				// (optional) Price components while not charging. Optional if no idle fee is charged.
-    struct NextPeriod 		nextPeriod;				// (optional) Pricing for next period
-    struct Triggers			triggerMeterValue;		// (optional) Triggers to request a new meter value. Optional if no idle fee charged.
-    unsigned char   		description[256];		// Compatible California pricing V1.0
+    int                     txId;                   // Transaction to which this applies
+    unsigned char           timestamp[36];          // Timestamp of the meter value upon which this cost is based
+    unsigned int            meterValue;             // Meter value (Wh) upon which this cost is based
+    float                   cost;                   // Calculated total running cost
+    unsigned char           state[16];              // "Charging" or "Idle"
+    struct ChargingPrice    chargingPrice;          // Price components while charging
+    struct IdlePrice        idlePrice;              // (optional) Price components while not charging. Optional if no idle fee is charged.
+    struct NextPeriod       nextPeriod;             // (optional) Pricing for next period
+    struct Triggers         triggerMeterValue;      // (optional) Triggers to request a new meter value. Optional if no idle fee charged.
+    unsigned char           description[256];       // Compatible California pricing V1.0
 };
 
 struct StrcutFinalCost
@@ -4361,8 +4361,8 @@ struct StrcutFinalCost
 struct StructCost
 {
     struct StrcutSetUserPrice       SetUserPrice;
-    struct StrcutRunningCost   		RunningCost[CONNECTOR_QUANTITY];
-    struct StrcutFinalCost   		FinalCost[CONNECTOR_QUANTITY];
+    struct StrcutRunningCost        RunningCost[CONNECTOR_QUANTITY];
+    struct StrcutFinalCost          FinalCost[CONNECTOR_QUANTITY];
 };
 
 struct CertificateHashDataType